test.cc 934 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763
  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, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. } // namespace detail
  488. } // namespace httplib
  489. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  490. struct {
  491. const char *line;
  492. const char *version;
  493. int status;
  494. const char *reason;
  495. } cases[] = {
  496. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  497. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  498. // The reason phrase may be empty, or left out along with its space.
  499. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  500. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  501. };
  502. for (const auto &c : cases) {
  503. std::string version;
  504. int status = 0;
  505. std::string reason = "unset";
  506. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  507. << c.line;
  508. EXPECT_EQ(c.version, version);
  509. EXPECT_EQ(c.status, status);
  510. EXPECT_EQ(c.reason, reason);
  511. }
  512. }
  513. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  514. const char *lines[] = {
  515. "HTTP/2 200 OK\r\n",
  516. "HTTP/1.2 200 OK\r\n",
  517. "HTTP/1.1 20 OK\r\n",
  518. "HTTP/1.1 2000 OK\r\n",
  519. "HTTP/1.1 2x0 OK\r\n",
  520. "HTTP/1.1 200 OK\r\n",
  521. "HTTP/1.1 200OK\r\n",
  522. "HTTP/1.1 200 O\rK\r\n",
  523. "HTTP/1.1 200 OK",
  524. "HTTP/1.1 200 OK\r\nX",
  525. "",
  526. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  527. "HTTP/1.1 200 OK\n",
  528. #endif
  529. };
  530. for (auto line : lines) {
  531. std::string version;
  532. int status = 0;
  533. std::string reason;
  534. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  535. << line;
  536. }
  537. }
  538. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  539. // Long enough to overflow the stack when matched with std::regex.
  540. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  541. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  542. std::string version;
  543. int status = 0;
  544. std::string reason;
  545. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  546. EXPECT_EQ(200, status);
  547. EXPECT_EQ(long_reason, reason);
  548. }
  549. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  550. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  551. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  552. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  553. EXPECT_EQ("", detail::file_extension("noext"));
  554. EXPECT_EQ("", detail::file_extension("a."));
  555. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  556. EXPECT_EQ("", detail::file_extension("a.b-c"));
  557. // Long enough to overflow the stack when matched with std::regex.
  558. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  559. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  560. }
  561. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  562. detail::case_ignore::hash hash;
  563. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  564. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  565. // Long enough to overflow the stack if hashed one call per character.
  566. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  567. }
  568. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  569. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  570. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  571. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  572. // Same 26-bit hash as html, svg and js.
  573. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  574. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  575. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  576. }
  577. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  578. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  579. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  580. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  581. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  582. // Same 26-bit hash as application/json.
  583. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  584. }
  585. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  586. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  587. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  588. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  589. // Same 26-bit hash as REMOTE_ADDR.
  590. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  591. }
  592. // Forward declaration: in split builds split.py strips `inline` and moves the
  593. // definition into httplib.cc, so detail::base64_encode is not visible from the
  594. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  595. // in both header-only and split builds.
  596. namespace httplib {
  597. namespace detail {
  598. std::string base64_encode(const std::string &in);
  599. } // namespace detail
  600. } // namespace httplib
  601. TEST(Base64EncodeTest, KnownAnswers) {
  602. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  603. // where the accumulator's top bit is already set before the next shift.
  604. EXPECT_EQ("", detail::base64_encode(""));
  605. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  606. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  607. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  608. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  609. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  610. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  611. // High bytes keep the top bit set across several rounds.
  612. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  613. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  614. }
  615. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  616. string unescapedCharacters = "-_.!~*'()";
  617. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  618. }
  619. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  620. string reservedCharacters = ";,/?:@&=+$";
  621. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  622. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  623. }
  624. TEST(ClientQueryOrder, PreserveOrder) {
  625. // This test reproduces Issue #2259: client may reorder query parameters
  626. // when sending a GET request. The expected behavior is that the client
  627. // preserves the original query string order when the caller supplied it
  628. // as part of the path.
  629. Server svr;
  630. svr.Get("/", [&](const Request &req, Response &res) {
  631. // Echo back the raw target so the test can assert ordering
  632. res.set_content(req.target, "text/plain");
  633. });
  634. std::thread t{[&] { svr.listen(HOST, PORT); }};
  635. auto se = detail::scope_exit([&] {
  636. svr.stop();
  637. t.join();
  638. ASSERT_FALSE(svr.is_running());
  639. });
  640. svr.wait_until_ready();
  641. Client cli(HOST, PORT);
  642. ASSERT_TRUE(cli.is_valid());
  643. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  644. auto res = cli.Get(original);
  645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  646. // Expect the echoed target to exactly match the original path (order
  647. // preserved)
  648. EXPECT_EQ(res->body, original);
  649. }
  650. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  651. string chineseCharacters = U8("中国語");
  652. string russianCharacters = U8("дом");
  653. string brazilianCharacters = U8("óculos");
  654. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  655. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  656. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  657. "%D0%B4%D0%BE%D0%BC");
  658. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  659. }
  660. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  661. string unescapedCharacters = "-_.!~*'()";
  662. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  663. }
  664. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  665. string reservedCharacters = ";,/?:@&=+$";
  666. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  667. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  668. }
  669. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  670. string chineseCharacters = U8("中国語");
  671. string russianCharacters = U8("дом");
  672. string brazilianCharacters = U8("óculos");
  673. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  674. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  675. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  676. "%D0%B4%D0%BE%D0%BC");
  677. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  678. }
  679. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  680. // Issue #2082 use case: encoding path component with ampersand
  681. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  682. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  683. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  684. }
  685. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  686. string unescapedCharacters = "-_.!~*'()";
  687. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  688. }
  689. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  690. string reservedCharacters = ";,/?:@&=+$#";
  691. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  692. }
  693. TEST(EncodeUriTest, TestUTF8Characters) {
  694. string chineseCharacters = U8("中国語");
  695. string russianCharacters = U8("дом");
  696. string brazilianCharacters = U8("óculos");
  697. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  698. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  699. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  700. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  701. }
  702. TEST(EncodeUriTest, TestCompleteUri) {
  703. string uri =
  704. "https://example.com/path/to/resource?query=value&param=test#fragment";
  705. EXPECT_EQ(
  706. httplib::encode_uri(uri),
  707. "https://example.com/path/to/resource?query=value&param=test#fragment");
  708. }
  709. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  710. string uri =
  711. "https://example.com/path with spaces/file name.html?q=hello world";
  712. EXPECT_EQ(httplib::encode_uri(uri),
  713. "https://example.com/path%20with%20spaces/"
  714. "file%20name.html?q=hello%20world");
  715. }
  716. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  717. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  718. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  719. }
  720. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  721. string unescapedCharacters = "-_.!~*'()";
  722. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  723. }
  724. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  725. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  726. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  727. string encodedBrazilian = "%C3%B3culos";
  728. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  729. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  730. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  731. }
  732. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  733. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  734. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  735. "Piri Tommy Villiers - on & on");
  736. }
  737. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  738. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  739. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  740. }
  741. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  742. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  743. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  744. }
  745. TEST(DecodeUriTest, TestUTF8Characters) {
  746. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  747. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  748. string encodedBrazilian = "%C3%B3culos";
  749. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  750. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  751. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  752. }
  753. TEST(DecodeUriTest, TestCompleteUri) {
  754. string encodedUri = "https://example.com/path%20with%20spaces/"
  755. "file%20name.html?q=hello%20world";
  756. EXPECT_EQ(
  757. httplib::decode_uri(encodedUri),
  758. "https://example.com/path with spaces/file name.html?q=hello world");
  759. }
  760. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  761. string original =
  762. "https://example.com/path with spaces/file name.html?q=hello world";
  763. string encoded = httplib::encode_uri(original);
  764. string decoded = httplib::decode_uri(encoded);
  765. EXPECT_EQ(decoded, original);
  766. }
  767. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  768. // decode_uri is the inverse of encode_uri: an escaped reserved character
  769. // stays encoded so it is not promoted into a real delimiter, while
  770. // non-reserved escapes still decode (like JS decodeURI).
  771. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  772. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  773. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  774. "%3F%3A%40%26%3D%2B%24%2C%3B");
  775. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  776. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  777. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  778. "http://example.com/a%2Fb");
  779. // decode_uri_component still decodes the reserved character.
  780. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  781. }
  782. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  783. string original = "Piri Tommy Villiers - on & on";
  784. string encoded = httplib::encode_uri_component(original);
  785. string decoded = httplib::decode_uri_component(encoded);
  786. EXPECT_EQ(decoded, original);
  787. }
  788. TEST(TrimTests, TrimStringTests) {
  789. EXPECT_EQ("abc", detail::trim_copy("abc"));
  790. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  791. EXPECT_TRUE(detail::trim_copy("").empty());
  792. }
  793. TEST(AsciiTest, LocaleIndependentClassification) {
  794. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  795. // which consult the global C locale: std::isalnum(0xC5) can return true
  796. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  797. // helpers must classify every byte by the ASCII grammar alone.
  798. for (int i = 0; i < 256; i++) {
  799. auto c = static_cast<char>(i);
  800. auto is_digit = i >= '0' && i <= '9';
  801. auto is_upper = i >= 'A' && i <= 'Z';
  802. auto is_lower = i >= 'a' && i <= 'z';
  803. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  804. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  805. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  806. << "byte " << i;
  807. }
  808. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  809. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  810. // Non-ASCII bytes must be percent-encoded, never passed through as
  811. // alphanumeric.
  812. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  813. }
  814. TEST(FromCharsTest, Double) {
  815. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  816. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  817. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  818. auto parse = [](const std::string &s, double &v) {
  819. return detail::from_chars(s.data(), s.data() + s.size(), v);
  820. };
  821. double v = -1.0;
  822. // Representative quality values.
  823. EXPECT_EQ(parse("0", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 0.0);
  825. EXPECT_EQ(parse("1", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 1.0);
  827. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.8);
  829. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 0.001);
  831. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  832. EXPECT_DOUBLE_EQ(v, 1.0);
  833. // A missing integer or fractional part is tolerated.
  834. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 0.5);
  836. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  837. EXPECT_DOUBLE_EQ(v, 5.0);
  838. // Values outside [0, 1] still parse; the caller range-checks them.
  839. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  840. EXPECT_DOUBLE_EQ(v, 123.456);
  841. // Stops at the first byte that is not part of the number and reports where.
  842. std::string trailing = "0.9, text/html";
  843. auto r = parse(trailing, v);
  844. EXPECT_EQ(r.ec, std::errc{});
  845. EXPECT_DOUBLE_EQ(v, 0.9);
  846. EXPECT_EQ(*r.ptr, ',');
  847. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  848. // outright, and an 'e'/'E' simply ends the number.
  849. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  850. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  851. std::string exp_input = "1.5e3";
  852. r = parse(exp_input, v);
  853. EXPECT_EQ(r.ec, std::errc{});
  854. EXPECT_DOUBLE_EQ(v, 1.5);
  855. EXPECT_EQ(*r.ptr, 'e');
  856. // Invalid inputs.
  857. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  860. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  861. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  862. // Pathological but well-formed inputs must stay bounded (no overflow, no
  863. // out-of-bounds table access) and stay within [0, 1] for the caller.
  864. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  865. std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.0);
  867. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  868. std::errc{});
  869. EXPECT_GE(v, 0.0);
  870. EXPECT_LE(v, 1.0);
  871. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  872. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  873. }
  874. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  875. // Simple case without quality values
  876. std::vector<std::string> result1;
  877. EXPECT_TRUE(detail::parse_accept_header(
  878. "text/html,application/json,text/plain", result1));
  879. EXPECT_EQ(result1.size(), 3U);
  880. EXPECT_EQ(result1[0], "text/html");
  881. EXPECT_EQ(result1[1], "application/json");
  882. EXPECT_EQ(result1[2], "text/plain");
  883. // With quality values
  884. std::vector<std::string> result2;
  885. EXPECT_TRUE(detail::parse_accept_header(
  886. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  887. EXPECT_EQ(result2.size(), 3U);
  888. EXPECT_EQ(result2[0], "application/json"); // highest q value
  889. EXPECT_EQ(result2[1], "text/html");
  890. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  891. }
  892. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  893. // Mixed with and without quality values
  894. std::vector<std::string> result;
  895. EXPECT_TRUE(detail::parse_accept_header(
  896. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  897. EXPECT_EQ(result.size(), 3U);
  898. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  899. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  900. EXPECT_EQ(result[2], "application/json"); // q=0.5
  901. }
  902. TEST(ParseAcceptHeaderTest, EdgeCases) {
  903. // Empty header
  904. std::vector<std::string> empty_result;
  905. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  906. EXPECT_TRUE(empty_result.empty());
  907. // Single type
  908. std::vector<std::string> single_result;
  909. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  910. EXPECT_EQ(single_result.size(), 1U);
  911. EXPECT_EQ(single_result[0], "application/json");
  912. // Wildcard types
  913. std::vector<std::string> wildcard_result;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  916. EXPECT_EQ(wildcard_result.size(), 3U);
  917. EXPECT_EQ(wildcard_result[0], "application/json");
  918. EXPECT_EQ(wildcard_result[1], "text/*");
  919. EXPECT_EQ(wildcard_result[2], "*/*");
  920. }
  921. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  922. // Common browser Accept header
  923. std::vector<std::string> browser_result;
  924. EXPECT_TRUE(
  925. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  926. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  927. browser_result));
  928. EXPECT_EQ(browser_result.size(), 6U);
  929. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  932. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  933. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  934. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  935. // API client header
  936. std::vector<std::string> api_result;
  937. EXPECT_TRUE(detail::parse_accept_header(
  938. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  939. api_result));
  940. EXPECT_EQ(api_result.size(), 3U);
  941. EXPECT_EQ(api_result[0], "application/json");
  942. EXPECT_EQ(api_result[1], "application/xml");
  943. EXPECT_EQ(api_result[2], "text/plain");
  944. }
  945. TEST(ParseAcceptHeaderTest, SpecialCases) {
  946. // Quality value with 3 decimal places
  947. std::vector<std::string> decimal_result;
  948. EXPECT_TRUE(detail::parse_accept_header(
  949. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  950. EXPECT_EQ(decimal_result.size(), 2U);
  951. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  952. EXPECT_EQ(decimal_result[1], "text/html");
  953. // Zero quality (should still be included but with lowest priority)
  954. std::vector<std::string> zero_q_result;
  955. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  956. zero_q_result));
  957. EXPECT_EQ(zero_q_result.size(), 2U);
  958. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  959. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  960. // No spaces around commas
  961. std::vector<std::string> no_space_result;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  964. no_space_result));
  965. EXPECT_EQ(no_space_result.size(), 3U);
  966. EXPECT_EQ(no_space_result[0], "text/html");
  967. EXPECT_EQ(no_space_result[1], "application/json");
  968. EXPECT_EQ(no_space_result[2], "text/plain");
  969. }
  970. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  971. // Quality values always use '.' as the decimal separator, so parsing must
  972. // not depend on the process locale. An embedding application may have
  973. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  974. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  975. std::string saved = cur ? cur : "C";
  976. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  977. "fr_FR.UTF-8"};
  978. bool switched = false;
  979. for (const auto loc : comma_locales) {
  980. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  981. std::localeconv()->decimal_point[0] == ',') {
  982. switched = true;
  983. break;
  984. }
  985. }
  986. if (!switched) {
  987. std::setlocale(LC_NUMERIC, saved.c_str());
  988. GTEST_SKIP() << "no comma-decimal locale available on this host";
  989. }
  990. // The higher-weighted type appears later in the list, so a correct parse
  991. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  992. // sensitive parse reads both weights as 0 and leaves the original order.
  993. std::vector<std::string> result;
  994. EXPECT_TRUE(detail::parse_accept_header(
  995. "application/json;q=0.1,text/html;q=0.9", result));
  996. ASSERT_EQ(result.size(), 2U);
  997. EXPECT_EQ(result[0], "text/html");
  998. EXPECT_EQ(result[1], "application/json");
  999. std::setlocale(LC_NUMERIC, saved.c_str());
  1000. }
  1001. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1002. std::vector<std::string> result;
  1003. // Invalid quality value (> 1.0)
  1004. EXPECT_FALSE(
  1005. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1006. // Invalid quality value (< 0.0)
  1007. EXPECT_FALSE(
  1008. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1009. // Invalid quality value (not a number)
  1010. EXPECT_FALSE(detail::parse_accept_header(
  1011. "text/html;q=invalid,application/json", result));
  1012. // A valid numeric prefix does not make the entire quality value valid.
  1013. EXPECT_FALSE(detail::parse_accept_header(
  1014. "text/html;q=0.5junk,application/json", result));
  1015. // Empty quality value
  1016. EXPECT_FALSE(
  1017. detail::parse_accept_header("text/html;q=,application/json", result));
  1018. // Invalid media type format (no slash and not wildcard)
  1019. EXPECT_FALSE(
  1020. detail::parse_accept_header("invalidtype,application/json", result));
  1021. // Valid cases should still work
  1022. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1023. EXPECT_EQ(result.size(), 1U);
  1024. EXPECT_EQ(result[0], "*/*");
  1025. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1026. EXPECT_EQ(result.size(), 1U);
  1027. EXPECT_EQ(result[0], "*");
  1028. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1029. EXPECT_EQ(result.size(), 1U);
  1030. EXPECT_EQ(result[0], "text/*");
  1031. }
  1032. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1033. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1034. // and must not be answered with 400 Bad Request.
  1035. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1036. struct {
  1037. const char *value;
  1038. std::vector<std::string> expected;
  1039. } cases[] = {
  1040. {",application/json", {"application/json"}},
  1041. {"text/html,", {"text/html"}},
  1042. {"text/html,,*/*", {"text/html", "*/*"}},
  1043. // An empty element may be spelled with whitespace in it
  1044. {"text/html, , application/json", {"text/html", "application/json"}},
  1045. // Nothing but empty elements is an empty list, which means the same
  1046. // thing as no Accept header at all
  1047. {",,,", {}},
  1048. // Quality values still apply across ignored empty elements
  1049. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1050. };
  1051. for (const auto &c : cases) {
  1052. std::vector<std::string> result;
  1053. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1054. << "value: " << c.value;
  1055. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1056. }
  1057. // An invalid entry is still rejected when empty elements surround it
  1058. std::vector<std::string> result;
  1059. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1060. }
  1061. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1062. // or ';' inside one does not end the list element or the parameter. Section
  1063. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1064. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1065. struct {
  1066. const char *value;
  1067. std::vector<std::string> expected;
  1068. } cases[] = {
  1069. {"text/html;profile=\"a,b\",application/json",
  1070. {"text/html", "application/json"}},
  1071. // A "q=" inside a quoted value is not the weight
  1072. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1073. {"text/html", "application/json"}},
  1074. // The weight after a quoted value still applies
  1075. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1078. {"application/json", "text/html"}},
  1079. {"text/html;profile=\"a\\\"b\",application/json",
  1080. {"text/html", "application/json"}},
  1081. // An escaped backslash does not escape the '"' after it
  1082. {"text/html;profile=\"a\\\\\",application/json",
  1083. {"text/html", "application/json"}},
  1084. };
  1085. for (const auto &c : cases) {
  1086. std::vector<std::string> result;
  1087. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1088. << "value: " << c.value;
  1089. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1090. }
  1091. }
  1092. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1093. Server svr;
  1094. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1095. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1096. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1097. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1098. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1099. res.set_content("ok", "text/plain");
  1100. });
  1101. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1102. EXPECT_TRUE(false);
  1103. res.set_content("bad request", "text/plain");
  1104. });
  1105. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1106. auto se = detail::scope_exit([&] {
  1107. svr.stop();
  1108. listen_thread.join();
  1109. ASSERT_FALSE(svr.is_running());
  1110. });
  1111. svr.wait_until_ready();
  1112. Client cli("localhost", PORT);
  1113. {
  1114. auto res = cli.Get(
  1115. "/accept_ok",
  1116. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. }
  1120. {
  1121. auto res = cli.Get("/accept_bad_request",
  1122. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1124. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1125. }
  1126. }
  1127. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1128. Server svr;
  1129. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1130. res.set_content("ok", "text/plain");
  1131. });
  1132. std::atomic<int> start_count{0};
  1133. std::atomic<bool> running_when_called{false};
  1134. svr.set_start_handler([&]() {
  1135. running_when_called = svr.is_running();
  1136. start_count++;
  1137. });
  1138. auto port = svr.bind_to_any_port(HOST);
  1139. std::thread t([&]() { svr.listen_after_bind(); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. t.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. // A successful request proves the accept loop is running, which the start
  1147. // handler precedes; so by now the handler must have run exactly once.
  1148. Client cli(HOST, port);
  1149. cli.set_connection_timeout(std::chrono::seconds(5));
  1150. auto res = cli.Get("/");
  1151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1152. EXPECT_EQ(StatusCode::OK_200, res->status);
  1153. EXPECT_EQ(1, start_count.load());
  1154. EXPECT_TRUE(running_when_called.load());
  1155. }
  1156. TEST(DivideTest, DivideStringTests) {
  1157. auto divide = [](const std::string &str, char d) {
  1158. std::string lhs;
  1159. std::string rhs;
  1160. detail::divide(str, d,
  1161. [&](const char *lhs_data, std::size_t lhs_size,
  1162. const char *rhs_data, std::size_t rhs_size) {
  1163. lhs.assign(lhs_data, lhs_size);
  1164. rhs.assign(rhs_data, rhs_size);
  1165. });
  1166. return std::make_pair(std::move(lhs), std::move(rhs));
  1167. };
  1168. {
  1169. const auto res = divide("", '=');
  1170. EXPECT_EQ(res.first, "");
  1171. EXPECT_EQ(res.second, "");
  1172. }
  1173. {
  1174. const auto res = divide("=", '=');
  1175. EXPECT_EQ(res.first, "");
  1176. EXPECT_EQ(res.second, "");
  1177. }
  1178. {
  1179. const auto res = divide(" ", '=');
  1180. EXPECT_EQ(res.first, " ");
  1181. EXPECT_EQ(res.second, "");
  1182. }
  1183. {
  1184. const auto res = divide("a", '=');
  1185. EXPECT_EQ(res.first, "a");
  1186. EXPECT_EQ(res.second, "");
  1187. }
  1188. {
  1189. const auto res = divide("a=", '=');
  1190. EXPECT_EQ(res.first, "a");
  1191. EXPECT_EQ(res.second, "");
  1192. }
  1193. {
  1194. const auto res = divide("=b", '=');
  1195. EXPECT_EQ(res.first, "");
  1196. EXPECT_EQ(res.second, "b");
  1197. }
  1198. {
  1199. const auto res = divide("a=b", '=');
  1200. EXPECT_EQ(res.first, "a");
  1201. EXPECT_EQ(res.second, "b");
  1202. }
  1203. {
  1204. const auto res = divide("a=b=", '=');
  1205. EXPECT_EQ(res.first, "a");
  1206. EXPECT_EQ(res.second, "b=");
  1207. }
  1208. {
  1209. const auto res = divide("a=b=c", '=');
  1210. EXPECT_EQ(res.first, "a");
  1211. EXPECT_EQ(res.second, "b=c");
  1212. }
  1213. }
  1214. TEST(SplitTest, ParseQueryString) {
  1215. string s = "key1=val1&key2=val2&key3=val3";
  1216. Params dic;
  1217. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1218. [&](const char *b, const char *e) {
  1219. string key, val;
  1220. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1221. if (key.empty()) {
  1222. key.assign(b2, e2);
  1223. } else {
  1224. val.assign(b2, e2);
  1225. }
  1226. });
  1227. dic.emplace(key, val);
  1228. });
  1229. EXPECT_EQ("val1", dic.find("key1")->second);
  1230. EXPECT_EQ("val2", dic.find("key2")->second);
  1231. EXPECT_EQ("val3", dic.find("key3")->second);
  1232. }
  1233. TEST(SplitTest, ParseInvalidQueryTests) {
  1234. {
  1235. string s = " ";
  1236. Params dict;
  1237. detail::parse_query_text(s, dict);
  1238. EXPECT_TRUE(dict.empty());
  1239. }
  1240. {
  1241. string s = " = =";
  1242. Params dict;
  1243. detail::parse_query_text(s, dict);
  1244. EXPECT_TRUE(dict.empty());
  1245. }
  1246. }
  1247. TEST(ParseQueryTest, ParseQueryString) {
  1248. {
  1249. std::string s = "key1=val1&key2=val2&key3=val3";
  1250. Params dic;
  1251. detail::parse_query_text(s, dic);
  1252. EXPECT_EQ("val1", dic.find("key1")->second);
  1253. EXPECT_EQ("val2", dic.find("key2")->second);
  1254. EXPECT_EQ("val3", dic.find("key3")->second);
  1255. }
  1256. {
  1257. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1258. Params dic;
  1259. detail::parse_query_text(s, dic);
  1260. EXPECT_EQ("", dic.find("key1")->second);
  1261. EXPECT_EQ("val1", dic.find("key2")->second);
  1262. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1263. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1264. }
  1265. }
  1266. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1267. Params dic;
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1269. dic.emplace("key1", "val1");
  1270. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1271. dic.emplace("key2", "val2");
  1272. dic.emplace("key3", "val3");
  1273. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1274. }
  1275. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1276. Params params;
  1277. params.emplace("a", "1");
  1278. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1279. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1280. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1281. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1282. // Long enough to overflow the stack when matched with std::regex.
  1283. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1284. EXPECT_EQ("/p?" + long_query + "&a=1",
  1285. append_query_params("/p?" + long_query, params));
  1286. }
  1287. // Joins every entry of a Headers or Params into "key=value " so a whole
  1288. // traversal can be compared in one assertion. Both are instantiations of the
  1289. // same insertion-ordered container, so one helper serves both.
  1290. template <typename Map> static std::string entries_to_string(const Map &m) {
  1291. std::string s;
  1292. for (const auto &entry : m) {
  1293. s += entry.first + "=" + entry.second + " ";
  1294. }
  1295. return s;
  1296. }
  1297. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1298. // Params used to be a std::multimap, which sorted by name and handed the
  1299. // caller's query back alphabetised. A client signing its query string could
  1300. // not reproduce the order it asked for.
  1301. Params dic;
  1302. dic.emplace("zulu", "1");
  1303. dic.emplace("alpha", "2");
  1304. dic.emplace("mike", "3");
  1305. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1306. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1307. }
  1308. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1309. Params dic;
  1310. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1311. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1312. }
  1313. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1314. Request req;
  1315. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1316. req.params);
  1317. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1318. EXPECT_EQ("first", req.get_param_value("tag"));
  1319. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1320. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1321. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1322. EXPECT_EQ("", req.get_param_value("tag", 3));
  1323. }
  1324. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1325. // Params shares its container with Headers, which matches field names
  1326. // case-insensitively. Parameter names must not pick that up.
  1327. Params dic;
  1328. dic.emplace("Key", "upper");
  1329. dic.emplace("key", "lower");
  1330. EXPECT_EQ(2U, dic.size());
  1331. EXPECT_EQ(1U, dic.count("Key"));
  1332. EXPECT_EQ(1U, dic.count("key"));
  1333. EXPECT_EQ("upper", dic.find("Key")->second);
  1334. EXPECT_EQ("lower", dic.find("key")->second);
  1335. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1336. }
  1337. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1338. Server svr;
  1339. std::string order;
  1340. svr.Get("/order", [&](const Request &req, Response &res) {
  1341. order = entries_to_string(req.params);
  1342. res.set_content("ok", "text/plain");
  1343. });
  1344. auto port = svr.bind_to_any_port(HOST);
  1345. thread t = thread([&] { svr.listen_after_bind(); });
  1346. auto se = detail::scope_exit([&] {
  1347. svr.stop();
  1348. t.join();
  1349. ASSERT_FALSE(svr.is_running());
  1350. });
  1351. svr.wait_until_ready();
  1352. Client cli(HOST, port);
  1353. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1354. ASSERT_TRUE(res);
  1355. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1356. }
  1357. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1358. Server svr;
  1359. std::string field_order, file_order;
  1360. svr.Post("/order", [&](const Request &req, Response &res) {
  1361. for (const auto &field : req.form.fields) {
  1362. field_order += field.first + "=" + field.second.content + " ";
  1363. }
  1364. for (const auto &file : req.form.files) {
  1365. file_order += file.first + "=" + file.second.filename + " ";
  1366. }
  1367. res.set_content("ok", "text/plain");
  1368. });
  1369. auto port = svr.bind_to_any_port(HOST);
  1370. thread t = thread([&] { svr.listen_after_bind(); });
  1371. auto se = detail::scope_exit([&] {
  1372. svr.stop();
  1373. t.join();
  1374. ASSERT_FALSE(svr.is_running());
  1375. });
  1376. svr.wait_until_ready();
  1377. UploadFormDataItems items = {
  1378. {"zulu", "1", "", ""},
  1379. {"alpha", "2", "", ""},
  1380. {"mike", "3", "", ""},
  1381. {"zebra", "z", "z.txt", "text/plain"},
  1382. {"apple", "a", "a.txt", "text/plain"},
  1383. };
  1384. Client cli(HOST, port);
  1385. auto res = cli.Post("/order", items);
  1386. ASSERT_TRUE(res);
  1387. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1388. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1389. }
  1390. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1391. Server svr;
  1392. std::vector<std::string> values;
  1393. std::string first, second, out_of_range, order;
  1394. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1395. values = req.form.get_fields("tag");
  1396. first = req.form.get_field("tag", 0);
  1397. second = req.form.get_field("tag", 1);
  1398. out_of_range = req.form.get_field("tag", 2);
  1399. for (const auto &field : req.form.fields) {
  1400. order += field.first + "=" + field.second.content + " ";
  1401. }
  1402. res.set_content("ok", "text/plain");
  1403. });
  1404. auto port = svr.bind_to_any_port(HOST);
  1405. thread t = thread([&] { svr.listen_after_bind(); });
  1406. auto se = detail::scope_exit([&] {
  1407. svr.stop();
  1408. t.join();
  1409. ASSERT_FALSE(svr.is_running());
  1410. });
  1411. svr.wait_until_ready();
  1412. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1413. // not adjacent in the container.
  1414. UploadFormDataItems items = {
  1415. {"tag", "first", "", ""},
  1416. {"other", "x", "", ""},
  1417. {"tag", "second", "", ""},
  1418. };
  1419. Client cli(HOST, port);
  1420. auto res = cli.Post("/repeated", items);
  1421. ASSERT_TRUE(res);
  1422. ASSERT_EQ(2U, values.size());
  1423. EXPECT_EQ("first", values[0]);
  1424. EXPECT_EQ("second", values[1]);
  1425. EXPECT_EQ("first", first);
  1426. EXPECT_EQ("second", second);
  1427. // std::multimap already kept entries sharing a name in insertion order, so
  1428. // everything above passes without this change too. The whole traversal is
  1429. // what tells the two apart: sorting by name would hoist "other" to the front
  1430. // and the two "tag" parts would end up adjacent.
  1431. EXPECT_EQ("tag=first other=x tag=second ", order);
  1432. // Advancing past the last entry of a name used to run off the container;
  1433. // the container's saturating increment makes it return the default instead.
  1434. EXPECT_EQ("", out_of_range);
  1435. }
  1436. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1437. // Server::read_content() keeps a FormFields::iterator alive across the
  1438. // content callbacks that fill the part it points at. The container is
  1439. // vector-backed, so a later emplace can reallocate and invalidate an older
  1440. // iterator; 64 parts grow the vector through seven reallocations, which
  1441. // checks that every part's content still lands in its own entry.
  1442. const size_t part_count = 64;
  1443. // One formula for both the parts sent and the values expected back, so the
  1444. // two cannot drift apart.
  1445. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1446. auto content_of = [](size_t i) {
  1447. return std::string(64, static_cast<char>('a' + (i % 26)));
  1448. };
  1449. Server svr;
  1450. std::vector<std::pair<std::string, std::string>> received;
  1451. svr.Post("/many", [&](const Request &req, Response &res) {
  1452. for (const auto &field : req.form.fields) {
  1453. received.emplace_back(field.first, field.second.content);
  1454. }
  1455. res.set_content("ok", "text/plain");
  1456. });
  1457. auto port = svr.bind_to_any_port(HOST);
  1458. thread t = thread([&] { svr.listen_after_bind(); });
  1459. auto se = detail::scope_exit([&] {
  1460. svr.stop();
  1461. t.join();
  1462. ASSERT_FALSE(svr.is_running());
  1463. });
  1464. svr.wait_until_ready();
  1465. UploadFormDataItems items;
  1466. for (size_t i = 0; i < part_count; i++) {
  1467. items.push_back({name_of(i), content_of(i), "", ""});
  1468. }
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/many", items);
  1471. ASSERT_TRUE(res);
  1472. ASSERT_EQ(part_count, received.size());
  1473. for (size_t i = 0; i < part_count; i++) {
  1474. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1475. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1476. }
  1477. }
  1478. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1479. string content_type = "multipart/form-data; boundary=something";
  1480. string boundary;
  1481. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1482. EXPECT_TRUE(ret);
  1483. EXPECT_EQ(boundary, "something");
  1484. }
  1485. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1486. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1487. string boundary;
  1488. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1489. EXPECT_TRUE(ret);
  1490. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1491. }
  1492. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1493. string content_type =
  1494. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1495. string boundary;
  1496. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1497. EXPECT_TRUE(ret);
  1498. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1499. }
  1500. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1501. string content_type =
  1502. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1503. string boundary;
  1504. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1505. EXPECT_TRUE(ret);
  1506. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1507. }
  1508. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1509. const string boundary(70, 'a');
  1510. string content_type = "multipart/form-data; boundary=" + boundary;
  1511. string parsed;
  1512. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1513. EXPECT_TRUE(ret);
  1514. EXPECT_EQ(parsed, boundary);
  1515. }
  1516. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1517. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1518. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1519. string parsed;
  1520. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1521. EXPECT_FALSE(ret);
  1522. }
  1523. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1524. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1525. // is 72 characters on the wire and still valid.
  1526. const string boundary(70, 'a');
  1527. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1528. string parsed;
  1529. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1530. EXPECT_EQ(parsed, boundary);
  1531. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1532. parsed.clear();
  1533. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1534. }
  1535. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1536. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1537. // The parameter parser must not treat that '=' as the key/value separator.
  1538. string content_type =
  1539. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1540. "charset=UTF-8";
  1541. string parsed;
  1542. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1543. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1546. // A ';' inside the quoted-string is part of the value, not a parameter
  1547. // separator, so it must not truncate the boundary.
  1548. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1549. string parsed;
  1550. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1551. EXPECT_EQ(parsed, "a;b");
  1552. }
  1553. TEST(ParseDispositionParamsTest, QuotedValues) {
  1554. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1555. // ';' and '=' are ordinary characters inside one.
  1556. struct {
  1557. const char *value;
  1558. std::vector<std::pair<const char *, const char *>> expected;
  1559. } cases[] = {
  1560. {"name=\"file1\"; filename=\"a.txt\"",
  1561. {{"name", "file1"}, {"filename", "a.txt"}}},
  1562. // Whitespace around '=' and ';' is still trimmed
  1563. {"name=\"file2\" ;filename = \"a.html\"",
  1564. {{"name", "file2"}, {"filename", "a.html"}}},
  1565. // '=' inside the value used to leave only the text after the last one
  1566. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1567. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1568. {"name=\"x=y\"", {{"name", "x=y"}}},
  1569. // ';' inside the value used to truncate the pair and leave a bogus one
  1570. {"name=\"file3\"; filename=\"a;b.txt\"",
  1571. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1572. // An unquoted value keeps working, and so does filename*
  1573. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1574. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1575. // A parameter with no key is dropped rather than turned into one whose
  1576. // key is the value
  1577. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1578. // An escaped quote does not end the value
  1579. {"name=\"a\\\"; filename=evil.php\"",
  1580. {{"name", "a\"; filename=evil.php"}}},
  1581. // Other backslashes, as in a Windows path, are kept
  1582. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1583. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1584. };
  1585. for (const auto &c : cases) {
  1586. Params params;
  1587. detail::parse_disposition_params(c.value, params);
  1588. for (const auto &kv : c.expected) {
  1589. auto it = params.find(kv.first);
  1590. ASSERT_NE(it, params.end())
  1591. << "value: " << c.value << ", key: " << kv.first;
  1592. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1593. }
  1594. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1595. }
  1596. }
  1597. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1598. Server svr;
  1599. std::string filename;
  1600. std::string content;
  1601. svr.Post("/upload", [&](const Request &req, Response &) {
  1602. const auto &file = req.form.get_file("file");
  1603. filename = file.filename;
  1604. content = file.content;
  1605. });
  1606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1607. auto se = detail::scope_exit([&] {
  1608. svr.stop();
  1609. thread.join();
  1610. ASSERT_FALSE(svr.is_running());
  1611. });
  1612. svr.wait_until_ready();
  1613. std::string body = "--B\r\n"
  1614. "Content-Disposition: form-data; name=\"file\"; "
  1615. "filename=\"a.txt\"\r\n"
  1616. "Content-Type: text/plain\r\n"
  1617. "\r\n"
  1618. "hello\r\n"
  1619. "--B--\r\n";
  1620. Client cli(HOST, PORT);
  1621. auto res = cli.Post(
  1622. "/upload",
  1623. [&](size_t offset, DataSink &sink) {
  1624. if (offset < body.size()) {
  1625. sink.write(&body[offset], 1);
  1626. } else {
  1627. sink.done();
  1628. }
  1629. return true;
  1630. },
  1631. "multipart/form-data; boundary=B");
  1632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1633. EXPECT_EQ(StatusCode::OK_200, res->status);
  1634. EXPECT_EQ("a.txt", filename);
  1635. EXPECT_EQ("hello", content);
  1636. }
  1637. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1638. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1639. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1640. Server svr;
  1641. std::string field_value, file_name, file_filename;
  1642. bool has_field = false, has_file = false;
  1643. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1644. has_field = req.form.has_field("x=y");
  1645. field_value = req.form.get_field("x=y");
  1646. has_file = req.form.has_file("file1");
  1647. const auto &file = req.form.get_file("file1");
  1648. file_name = file.name;
  1649. file_filename = file.filename;
  1650. res.set_content("ok", "text/plain");
  1651. });
  1652. auto port = svr.bind_to_any_port(HOST);
  1653. thread t = thread([&] { svr.listen_after_bind(); });
  1654. auto se = detail::scope_exit([&] {
  1655. svr.stop();
  1656. t.join();
  1657. ASSERT_FALSE(svr.is_running());
  1658. });
  1659. svr.wait_until_ready();
  1660. UploadFormDataItems items = {
  1661. {"x=y", "field-value", "", ""},
  1662. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1663. };
  1664. Client cli(HOST, port);
  1665. auto res = cli.Post("/quoted", items);
  1666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1667. ASSERT_EQ(StatusCode::OK_200, res->status);
  1668. EXPECT_TRUE(has_field);
  1669. EXPECT_EQ("field-value", field_value);
  1670. EXPECT_TRUE(has_file);
  1671. EXPECT_EQ("file1", file_name);
  1672. EXPECT_EQ("a;b=report.pdf", file_filename);
  1673. }
  1674. TEST(GetHeaderValueTest, DefaultValue) {
  1675. Headers headers = {{"Dummy", "Dummy"}};
  1676. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1677. EXPECT_STREQ("text/plain", val);
  1678. }
  1679. TEST(GetHeaderValueTest, DefaultValueInt) {
  1680. Headers headers = {{"Dummy", "Dummy"}};
  1681. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1682. EXPECT_EQ(100ull, val);
  1683. }
  1684. TEST(GetHeaderValueTest, RegularValue) {
  1685. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1686. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1687. EXPECT_STREQ("text/html", val);
  1688. }
  1689. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1690. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1691. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1692. EXPECT_STREQ("text/html", val);
  1693. }
  1694. TEST(GetHeaderValueTest, SetContent) {
  1695. Response res;
  1696. res.set_content("html", "text/html");
  1697. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1698. res.set_content("text", "text/plain");
  1699. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1700. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1701. }
  1702. TEST(GetHeaderValueTest, RegularValueInt) {
  1703. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1704. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1705. EXPECT_EQ(100ull, val);
  1706. }
  1707. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1708. Headers headers = {{"Content-Length", "x"}};
  1709. auto is_invalid_value = false;
  1710. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1711. is_invalid_value);
  1712. EXPECT_EQ(0ull, val);
  1713. EXPECT_TRUE(is_invalid_value);
  1714. }
  1715. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1716. // An all-digit value that overflows size_t must be reported as invalid, not
  1717. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1718. // a large length to a small one on 32-bit builds, leaving the framing length
  1719. // wrong while is_invalid_value stayed false.
  1720. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1721. auto is_invalid_value = false;
  1722. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1723. is_invalid_value);
  1724. EXPECT_TRUE(is_invalid_value);
  1725. // A well-formed length is unaffected.
  1726. Headers ok = {{"Content-Length", "1234"}};
  1727. is_invalid_value = false;
  1728. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1729. is_invalid_value);
  1730. EXPECT_EQ(1234ull, val);
  1731. EXPECT_FALSE(is_invalid_value);
  1732. }
  1733. TEST(GetHeaderValueTest, Range) {
  1734. {
  1735. Headers headers = {make_range_header({{1, -1}})};
  1736. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1737. EXPECT_STREQ("bytes=1-", val);
  1738. }
  1739. {
  1740. Headers headers = {make_range_header({{-1, 1}})};
  1741. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1742. EXPECT_STREQ("bytes=-1", val);
  1743. }
  1744. {
  1745. Headers headers = {make_range_header({{1, 10}})};
  1746. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1747. EXPECT_STREQ("bytes=1-10", val);
  1748. }
  1749. {
  1750. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1751. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1752. EXPECT_STREQ("bytes=1-10, 100-", val);
  1753. }
  1754. {
  1755. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1756. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1757. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1758. }
  1759. {
  1760. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1761. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1762. EXPECT_STREQ("bytes=0-0, -1", val);
  1763. }
  1764. }
  1765. TEST(BearerTokenAuthTest, SchemeValidation) {
  1766. // A value shorter than "Bearer " must not throw from the fixed-length
  1767. // substr, and a non-Bearer scheme must not be reported as a token.
  1768. struct {
  1769. const char *value;
  1770. const char *expected;
  1771. } cases[] = {
  1772. {"x", ""},
  1773. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1774. {"Bearer abc123", "abc123"},
  1775. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1776. };
  1777. for (const auto &c : cases) {
  1778. Request req;
  1779. req.set_header("Authorization", c.value);
  1780. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1781. }
  1782. }
  1783. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1784. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1785. // to depend on the standard library (libstdc++ handed back duplicates in
  1786. // reverse insertion order, libc++ in insertion order).
  1787. Request req;
  1788. req.set_header("Accept-Encoding", "gzip");
  1789. req.set_header("Accept-Encoding", "deflate");
  1790. req.set_header("Accept-Encoding", "br");
  1791. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1792. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1793. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1794. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1795. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1796. }
  1797. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1798. Request req;
  1799. req.set_header("X-Test", "only");
  1800. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1801. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1802. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1803. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1804. }
  1805. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1806. Request req;
  1807. req.set_header("X-First", "1");
  1808. req.set_header("X-Test", "2");
  1809. req.params.emplace("first", "1");
  1810. req.params.emplace("test", "2");
  1811. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1812. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1813. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1814. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1815. // The second one is negative when read as a signed value
  1816. const auto max_id = (std::numeric_limits<size_t>::max)();
  1817. for (auto id : {max_id / 2, max_id}) {
  1818. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1819. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1820. EXPECT_EQ("", req.get_param_value("test", id));
  1821. EXPECT_EQ("", req.form.get_field("test", id));
  1822. EXPECT_EQ("", req.form.get_file("test", id).content);
  1823. }
  1824. }
  1825. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1826. Headers headers;
  1827. headers.emplace("Host", "example.com");
  1828. headers.emplace("Accept-Encoding", "gzip");
  1829. headers.emplace("User-Agent", "test");
  1830. headers.emplace("Accept-Encoding", "deflate");
  1831. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1832. "Accept-Encoding=deflate ",
  1833. entries_to_string(headers));
  1834. }
  1835. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1836. Headers headers = {{"Content-Type", "text/html"},
  1837. {"CONTENT-TYPE", "text/xml"}};
  1838. EXPECT_EQ(2U, headers.count("content-type"));
  1839. auto it = headers.find("content-type");
  1840. ASSERT_TRUE(it != headers.end());
  1841. EXPECT_EQ("text/html", it->second);
  1842. }
  1843. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1844. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1845. // drop only those fields and leave everything positioned between them.
  1846. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1847. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1848. auto rng = headers.equal_range("a");
  1849. headers.erase(rng.first, rng.second);
  1850. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1851. }
  1852. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1853. Headers headers = {
  1854. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1855. EXPECT_EQ(3U, headers.erase("A"));
  1856. EXPECT_EQ(0U, headers.count("A"));
  1857. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1858. }
  1859. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1860. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1861. headers.emplace_front("Host", "example.com");
  1862. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1863. entries_to_string(headers));
  1864. }
  1865. TEST(ParseHeaderValueTest, Range) {
  1866. {
  1867. Ranges ranges;
  1868. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1869. EXPECT_TRUE(ret);
  1870. EXPECT_EQ(1u, ranges.size());
  1871. EXPECT_EQ(1u, ranges[0].first);
  1872. EXPECT_EQ(-1, ranges[0].second);
  1873. }
  1874. {
  1875. Ranges ranges;
  1876. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1877. EXPECT_TRUE(ret);
  1878. EXPECT_EQ(1u, ranges.size());
  1879. EXPECT_EQ(-1, ranges[0].first);
  1880. EXPECT_EQ(1u, ranges[0].second);
  1881. }
  1882. {
  1883. Ranges ranges;
  1884. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1885. EXPECT_TRUE(ret);
  1886. EXPECT_EQ(1u, ranges.size());
  1887. EXPECT_EQ(1u, ranges[0].first);
  1888. EXPECT_EQ(10u, ranges[0].second);
  1889. }
  1890. {
  1891. Ranges ranges;
  1892. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1893. EXPECT_FALSE(ret);
  1894. }
  1895. {
  1896. Ranges ranges;
  1897. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1898. EXPECT_TRUE(ret);
  1899. EXPECT_EQ(2u, ranges.size());
  1900. EXPECT_EQ(1u, ranges[0].first);
  1901. EXPECT_EQ(10u, ranges[0].second);
  1902. EXPECT_EQ(100u, ranges[1].first);
  1903. EXPECT_EQ(-1, ranges[1].second);
  1904. }
  1905. {
  1906. Ranges ranges;
  1907. auto ret =
  1908. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1909. EXPECT_TRUE(ret);
  1910. EXPECT_EQ(3u, ranges.size());
  1911. EXPECT_EQ(1u, ranges[0].first);
  1912. EXPECT_EQ(10u, ranges[0].second);
  1913. EXPECT_EQ(100u, ranges[1].first);
  1914. EXPECT_EQ(200u, ranges[1].second);
  1915. EXPECT_EQ(300u, ranges[2].first);
  1916. EXPECT_EQ(400u, ranges[2].second);
  1917. }
  1918. {
  1919. Ranges ranges;
  1920. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1921. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1922. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1923. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1924. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1925. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1926. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1927. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1928. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1929. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1930. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1931. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1932. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1933. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1934. EXPECT_FALSE(
  1935. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1936. EXPECT_TRUE(ranges.empty());
  1937. }
  1938. {
  1939. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1940. // remainder of the representation, so it stays accepted.
  1941. Ranges ranges;
  1942. auto ret =
  1943. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1944. EXPECT_TRUE(ret);
  1945. ASSERT_EQ(1u, ranges.size());
  1946. EXPECT_EQ(0, ranges[0].first);
  1947. EXPECT_EQ(-1, ranges[0].second);
  1948. }
  1949. // RFC 9110 14.1: range unit names are case-insensitive.
  1950. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1951. Ranges ranges;
  1952. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1953. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1954. }
  1955. }
  1956. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1957. Request req;
  1958. req.set_header("Accept-Encoding", "gzip");
  1959. Response res;
  1960. res.set_header("Content-Type", "text/plain");
  1961. auto ret = detail::encoding_type(req, res);
  1962. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1963. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1964. #else
  1965. EXPECT_TRUE(ret == detail::EncodingType::None);
  1966. #endif
  1967. }
  1968. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1971. Response res;
  1972. res.set_header("Content-Type", "text/plain");
  1973. auto ret = detail::encoding_type(req, res);
  1974. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1975. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1976. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1980. #else
  1981. EXPECT_TRUE(ret == detail::EncodingType::None);
  1982. #endif
  1983. }
  1984. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1985. Request req;
  1986. req.set_header("Accept-Encoding",
  1987. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1988. Response res;
  1989. res.set_header("Content-Type", "text/plain");
  1990. auto ret = detail::encoding_type(req, res);
  1991. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1993. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1994. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1995. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2002. // All supported encodings rejected with q=0 should return None
  2003. Request req;
  2004. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2005. Response res;
  2006. res.set_header("Content-Type", "text/plain");
  2007. auto ret = detail::encoding_type(req, res);
  2008. EXPECT_TRUE(ret == detail::EncodingType::None);
  2009. }
  2010. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2011. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2012. Request req;
  2013. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2014. Response res;
  2015. res.set_header("Content-Type", "text/plain");
  2016. auto ret = detail::encoding_type(req, res);
  2017. EXPECT_TRUE(ret == detail::EncodingType::None);
  2018. }
  2019. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2020. Request req;
  2021. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2022. Response res;
  2023. res.set_header("Content-Type", "text/plain");
  2024. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2025. }
  2026. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2027. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2028. Request req;
  2029. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2030. Response res;
  2031. res.set_header("Content-Type", "text/plain");
  2032. auto ret = detail::encoding_type(req, res);
  2033. EXPECT_TRUE(ret == detail::EncodingType::None);
  2034. }
  2035. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2036. // RFC 7231: Accept-Encoding values are case-insensitive
  2037. Request req;
  2038. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2039. Response res;
  2040. res.set_header("Content-Type", "text/plain");
  2041. auto ret = detail::encoding_type(req, res);
  2042. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2044. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2046. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2048. #else
  2049. EXPECT_TRUE(ret == detail::EncodingType::None);
  2050. #endif
  2051. }
  2052. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2053. // q value should determine priority, not hardcoded order
  2054. Request req;
  2055. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2056. Response res;
  2057. res.set_header("Content-Type", "text/plain");
  2058. auto ret = detail::encoding_type(req, res);
  2059. // gzip has highest q=1.0, so it should be selected even though
  2060. // br and zstd are also supported
  2061. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2063. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2065. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(BufferStreamTest, read) {
  2072. detail::BufferStream strm1;
  2073. Stream &strm = strm1;
  2074. EXPECT_EQ(5, strm.write("hello"));
  2075. char buf[512];
  2076. EXPECT_EQ(2, strm.read(buf, 2));
  2077. EXPECT_EQ('h', buf[0]);
  2078. EXPECT_EQ('e', buf[1]);
  2079. EXPECT_EQ(2, strm.read(buf, 2));
  2080. EXPECT_EQ('l', buf[0]);
  2081. EXPECT_EQ('l', buf[1]);
  2082. EXPECT_EQ(1, strm.read(buf, 1));
  2083. EXPECT_EQ('o', buf[0]);
  2084. EXPECT_EQ(0, strm.read(buf, 1));
  2085. }
  2086. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2087. auto host = "www.httpwatch.com";
  2088. auto ip = hosted_at(host);
  2089. EXPECT_EQ("23.96.13.243", ip);
  2090. std::vector<std::string> addrs;
  2091. hosted_at(host, addrs);
  2092. EXPECT_EQ(1u, addrs.size());
  2093. }
  2094. #if 0 // It depends on each test environment...
  2095. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2096. auto host = "www.youtube.com";
  2097. std::vector<std::string> addrs;
  2098. hosted_at(host, addrs);
  2099. EXPECT_EQ(20u, addrs.size());
  2100. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2101. EXPECT_TRUE(it != addrs.end());
  2102. }
  2103. #endif
  2104. class ChunkedEncodingTest : public ::testing::Test {
  2105. protected:
  2106. ChunkedEncodingTest()
  2107. : cli_(HOST, PORT)
  2108. #ifdef CPPHTTPLIB_SSL_ENABLED
  2109. ,
  2110. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2111. #endif
  2112. {
  2113. cli_.set_connection_timeout(2);
  2114. #ifdef CPPHTTPLIB_SSL_ENABLED
  2115. cli_.enable_server_certificate_verification(false);
  2116. #endif
  2117. }
  2118. virtual void SetUp() {
  2119. read_file("./image.jpg", image_data_);
  2120. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!", "text/plain");
  2122. });
  2123. svr_.Get(
  2124. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2125. res.set_chunked_content_provider(
  2126. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2127. size_t remaining = image_data_.size() - offset;
  2128. if (remaining == 0) {
  2129. sink.done();
  2130. } else {
  2131. constexpr size_t CHUNK_SIZE = 1024;
  2132. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2133. sink.write(&image_data_[offset], send_size);
  2134. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2135. }
  2136. return true;
  2137. });
  2138. });
  2139. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2140. svr_.wait_until_ready();
  2141. }
  2142. virtual void TearDown() {
  2143. svr_.stop();
  2144. if (!request_threads_.empty()) {
  2145. std::this_thread::sleep_for(std::chrono::seconds(1));
  2146. for (auto &t : request_threads_) {
  2147. t.join();
  2148. }
  2149. }
  2150. t_.join();
  2151. }
  2152. #ifdef CPPHTTPLIB_SSL_ENABLED
  2153. SSLClient cli_;
  2154. SSLServer svr_;
  2155. #else
  2156. Client cli_;
  2157. Server svr_;
  2158. #endif
  2159. thread t_;
  2160. std::vector<thread> request_threads_;
  2161. std::string image_data_;
  2162. };
  2163. TEST_F(ChunkedEncodingTest, NormalGet) {
  2164. auto res = cli_.Get("/chunked");
  2165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2166. std::string out;
  2167. read_file("./image.jpg", out);
  2168. EXPECT_EQ(StatusCode::OK_200, res->status);
  2169. EXPECT_EQ(out, res->body);
  2170. }
  2171. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2172. std::string body;
  2173. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2174. body.append(data, data_length);
  2175. return true;
  2176. });
  2177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2178. std::string out;
  2179. read_file("./image.jpg", out);
  2180. EXPECT_EQ(StatusCode::OK_200, res->status);
  2181. EXPECT_EQ(out, body);
  2182. }
  2183. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2184. std::string body;
  2185. auto res = cli_.Get(
  2186. "/chunked",
  2187. [&](const Response &response) {
  2188. EXPECT_EQ(StatusCode::OK_200, response.status);
  2189. return true;
  2190. },
  2191. [&](const char *data, size_t data_length) {
  2192. body.append(data, data_length);
  2193. return true;
  2194. });
  2195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2196. std::string out;
  2197. read_file("./image.jpg", out);
  2198. EXPECT_EQ(StatusCode::OK_200, res->status);
  2199. EXPECT_EQ(out, body);
  2200. }
  2201. TEST(RangeTest, FromHTTPBin_Online) {
  2202. auto host = "httpbingo.org";
  2203. auto path = std::string{"/range/32"};
  2204. #ifdef CPPHTTPLIB_SSL_ENABLED
  2205. auto port = 443;
  2206. SSLClient cli(host, port);
  2207. #else
  2208. auto port = 80;
  2209. Client cli(host, port);
  2210. #endif
  2211. cli.set_connection_timeout(5);
  2212. {
  2213. auto res = cli.Get(path);
  2214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2215. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2216. EXPECT_EQ(StatusCode::OK_200, res->status);
  2217. }
  2218. {
  2219. Headers headers = {make_range_header({{1, -1}})};
  2220. auto res = cli.Get(path, headers);
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2224. }
  2225. {
  2226. Headers headers = {make_range_header({{1, 10}})};
  2227. auto res = cli.Get(path, headers);
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. EXPECT_EQ("bcdefghijk", res->body);
  2230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2231. }
  2232. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2233. // entire resource, while the original httpbin returned 200. Both are
  2234. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2235. {
  2236. Headers headers = {make_range_header({{0, 31}})};
  2237. auto res = cli.Get(path, headers);
  2238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2239. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2240. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2241. res->status == StatusCode::PartialContent_206);
  2242. }
  2243. {
  2244. Headers headers = {make_range_header({{0, -1}})};
  2245. auto res = cli.Get(path, headers);
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2248. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2249. res->status == StatusCode::PartialContent_206);
  2250. }
  2251. // go-httpbin returns 206 with clamped range for over-range requests,
  2252. // while the original httpbin returned 416. Both behaviors are observed
  2253. // in real servers, so we only verify the request succeeds.
  2254. {
  2255. Headers headers = {make_range_header({{0, 32}})};
  2256. auto res = cli.Get(path, headers);
  2257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2258. }
  2259. }
  2260. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2261. auto host = "unresolvableaddress.local";
  2262. auto path = std::string{"/"};
  2263. #ifdef CPPHTTPLIB_SSL_ENABLED
  2264. auto port = 443;
  2265. SSLClient cli(host, port);
  2266. #else
  2267. auto port = 80;
  2268. Client cli(host, port);
  2269. #endif
  2270. cli.set_connection_timeout(1);
  2271. {
  2272. auto res = cli.Get(path);
  2273. ASSERT_FALSE(res);
  2274. }
  2275. std::this_thread::sleep_for(std::chrono::seconds(8));
  2276. }
  2277. #if defined(__linux__) && defined(__GLIBC__) && \
  2278. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2279. // Forward declaration: in split builds split.py strips `inline` and moves the
  2280. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2281. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2282. // against the symbol in both header-only and split builds.
  2283. namespace httplib {
  2284. namespace detail {
  2285. int getaddrinfo_with_timeout(const char *node, const char *service,
  2286. const struct addrinfo *hints,
  2287. struct addrinfo **res, time_t timeout_sec);
  2288. } // namespace detail
  2289. } // namespace httplib
  2290. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2291. //
  2292. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2293. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2294. // gai_suspend() call hits the connection timeout the function calls
  2295. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2296. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2297. // still alive and still references the now-destroyed stack frame.
  2298. //
  2299. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2300. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2301. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2302. // and runs them in a container.
  2303. namespace {
  2304. bool should_run_issue_2431_tests() {
  2305. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2306. return v && *v && std::string(v) != "0";
  2307. }
  2308. std::string unique_unresolvable_host(int n) {
  2309. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2310. // glibc still asks the configured nameserver — which is exactly the path
  2311. // we want to exercise. A unique label per call avoids the resolver cache.
  2312. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2313. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2314. std::to_string(n) + ".invalid";
  2315. }
  2316. } // namespace
  2317. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2318. if (!should_run_issue_2431_tests()) {
  2319. GTEST_SKIP()
  2320. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2321. }
  2322. for (int i = 0; i < 8; ++i) {
  2323. struct addrinfo hints;
  2324. memset(&hints, 0, sizeof(hints));
  2325. hints.ai_family = AF_UNSPEC;
  2326. hints.ai_socktype = SOCK_STREAM;
  2327. auto host = unique_unresolvable_host(i);
  2328. struct addrinfo *result = nullptr;
  2329. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2330. &result, /*timeout_sec=*/1);
  2331. if (rc == 0 && result) { freeaddrinfo(result); }
  2332. }
  2333. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2334. // stack region they still believe holds their gaicb.
  2335. std::this_thread::sleep_for(std::chrono::seconds(3));
  2336. }
  2337. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2338. if (!should_run_issue_2431_tests()) {
  2339. GTEST_SKIP()
  2340. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2341. }
  2342. std::atomic<bool> stop{false};
  2343. std::vector<std::thread> threads;
  2344. for (int t = 0; t < 8; ++t) {
  2345. threads.emplace_back([t, &stop] {
  2346. int i = 0;
  2347. while (!stop.load(std::memory_order_relaxed)) {
  2348. struct addrinfo hints;
  2349. memset(&hints, 0, sizeof(hints));
  2350. hints.ai_family = AF_UNSPEC;
  2351. hints.ai_socktype = SOCK_STREAM;
  2352. auto host = unique_unresolvable_host(t * 100000 + i++);
  2353. struct addrinfo *result = nullptr;
  2354. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2355. &result, /*timeout_sec=*/1);
  2356. if (rc == 0 && result) { freeaddrinfo(result); }
  2357. }
  2358. });
  2359. }
  2360. std::this_thread::sleep_for(std::chrono::seconds(8));
  2361. stop.store(true, std::memory_order_relaxed);
  2362. for (auto &th : threads) {
  2363. th.join();
  2364. }
  2365. std::this_thread::sleep_for(std::chrono::seconds(3));
  2366. }
  2367. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2368. if (!should_run_issue_2431_tests()) {
  2369. GTEST_SKIP()
  2370. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2371. }
  2372. std::atomic<bool> stop{false};
  2373. std::vector<std::thread> threads;
  2374. for (int t = 0; t < 8; ++t) {
  2375. threads.emplace_back([t, &stop] {
  2376. int i = 0;
  2377. while (!stop.load(std::memory_order_relaxed)) {
  2378. auto host = unique_unresolvable_host(t * 100000 + i++);
  2379. Client cli(host, 80);
  2380. cli.set_connection_timeout(1, 0);
  2381. cli.set_read_timeout(1, 0);
  2382. cli.set_write_timeout(1, 0);
  2383. (void)cli.Get("/");
  2384. }
  2385. });
  2386. }
  2387. std::this_thread::sleep_for(std::chrono::seconds(8));
  2388. stop.store(true, std::memory_order_relaxed);
  2389. for (auto &th : threads) {
  2390. th.join();
  2391. }
  2392. std::this_thread::sleep_for(std::chrono::seconds(3));
  2393. }
  2394. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2395. TEST(ConnectionErrorTest, InvalidHost) {
  2396. auto host = "-abcde.com";
  2397. #ifdef CPPHTTPLIB_SSL_ENABLED
  2398. auto port = 443;
  2399. SSLClient cli(host, port);
  2400. #else
  2401. auto port = 80;
  2402. Client cli(host, port);
  2403. #endif
  2404. cli.set_connection_timeout(std::chrono::seconds(2));
  2405. auto res = cli.Get("/");
  2406. ASSERT_TRUE(!res);
  2407. EXPECT_EQ(Error::Connection, res.error());
  2408. }
  2409. TEST(ConnectionErrorTest, InvalidHost2) {
  2410. auto host = "httpcan.org/";
  2411. #ifdef CPPHTTPLIB_SSL_ENABLED
  2412. SSLClient cli(host);
  2413. #else
  2414. Client cli(host);
  2415. #endif
  2416. cli.set_connection_timeout(std::chrono::seconds(2));
  2417. auto res = cli.Get("/");
  2418. ASSERT_TRUE(!res);
  2419. EXPECT_EQ(Error::Connection, res.error());
  2420. }
  2421. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2422. auto host = "httpcan.org/";
  2423. #ifdef CPPHTTPLIB_SSL_ENABLED
  2424. SSLClient cli(host);
  2425. #else
  2426. Client cli(host);
  2427. #endif
  2428. cli.set_connection_timeout(std::chrono::seconds(2));
  2429. auto res = cli.Get("/");
  2430. ASSERT_TRUE(!res);
  2431. stringstream s;
  2432. s << "error code: " << res.error();
  2433. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2434. }
  2435. TEST(ConnectionErrorTest, InvalidPort) {
  2436. auto host = "localhost";
  2437. auto port = 44380;
  2438. #ifdef CPPHTTPLIB_SSL_ENABLED
  2439. SSLClient cli(host, port);
  2440. #else
  2441. Client cli(host, port);
  2442. #endif
  2443. cli.set_connection_timeout(std::chrono::seconds(2));
  2444. auto res = cli.Get("/");
  2445. ASSERT_TRUE(!res);
  2446. EXPECT_TRUE(Error::Connection == res.error() ||
  2447. Error::ConnectionTimeout == res.error());
  2448. }
  2449. TEST(ConnectionErrorTest, Timeout_Online) {
  2450. auto host = "google.com";
  2451. #ifdef CPPHTTPLIB_SSL_ENABLED
  2452. auto port = 44380;
  2453. SSLClient cli(host, port);
  2454. #else
  2455. auto port = 8080;
  2456. Client cli(host, port);
  2457. #endif
  2458. cli.set_connection_timeout(std::chrono::seconds(2));
  2459. // only probe one address type so that the error reason
  2460. // correlates to the timed-out IPv4, not the unsupported
  2461. // IPv6 connection attempt
  2462. cli.set_address_family(AF_INET);
  2463. auto res = cli.Get("/");
  2464. ASSERT_TRUE(!res);
  2465. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2466. }
  2467. TEST(CancelTest, NoCancel_Online) {
  2468. auto host = "httpbingo.org";
  2469. auto path = std::string{"/range/32"};
  2470. #ifdef CPPHTTPLIB_SSL_ENABLED
  2471. auto port = 443;
  2472. SSLClient cli(host, port);
  2473. #else
  2474. auto port = 80;
  2475. Client cli(host, port);
  2476. #endif
  2477. cli.set_connection_timeout(std::chrono::seconds(5));
  2478. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2480. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2481. EXPECT_EQ(StatusCode::OK_200, res->status);
  2482. }
  2483. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2484. // Use /bytes with a large payload so that the DownloadProgress callback
  2485. // (which only fires for Content-Length responses) is invoked before the
  2486. // entire body is received, giving cancellation a chance to fire.
  2487. auto host = "httpbingo.org";
  2488. auto path = std::string{"/bytes/524288"};
  2489. #ifdef CPPHTTPLIB_SSL_ENABLED
  2490. auto port = 443;
  2491. SSLClient cli(host, port);
  2492. #else
  2493. auto port = 80;
  2494. Client cli(host, port);
  2495. #endif
  2496. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2497. cli.set_connection_timeout(std::chrono::seconds(5));
  2498. ASSERT_TRUE(!res);
  2499. EXPECT_EQ(Error::Canceled, res.error());
  2500. }
  2501. TEST(CancelTest, WithCancelLargePayload_Online) {
  2502. auto host = "httpbingo.org";
  2503. auto path = std::string{"/bytes/524288"};
  2504. #ifdef CPPHTTPLIB_SSL_ENABLED
  2505. auto port = 443;
  2506. SSLClient cli(host, port);
  2507. #else
  2508. auto port = 80;
  2509. Client cli(host, port);
  2510. #endif
  2511. cli.set_connection_timeout(std::chrono::seconds(5));
  2512. uint32_t count = 0;
  2513. auto res =
  2514. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2515. ASSERT_TRUE(!res);
  2516. EXPECT_EQ(Error::Canceled, res.error());
  2517. }
  2518. TEST(CancelTest, NoCancelPost) {
  2519. Server svr;
  2520. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2521. res.set_content("Hello World!", "text/plain");
  2522. });
  2523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2524. auto se = detail::scope_exit([&] {
  2525. svr.stop();
  2526. thread.join();
  2527. ASSERT_FALSE(svr.is_running());
  2528. });
  2529. svr.wait_until_ready();
  2530. Client cli(HOST, PORT);
  2531. cli.set_connection_timeout(std::chrono::seconds(5));
  2532. auto res =
  2533. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2534. "application/json", [](uint64_t, uint64_t) { return true; });
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. EXPECT_EQ("Hello World!", res->body);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2540. Server svr;
  2541. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2542. res.set_content("Hello World!", "text/plain");
  2543. });
  2544. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2545. auto se = detail::scope_exit([&] {
  2546. svr.stop();
  2547. thread.join();
  2548. ASSERT_FALSE(svr.is_running());
  2549. });
  2550. svr.wait_until_ready();
  2551. Client cli(HOST, PORT);
  2552. cli.set_connection_timeout(std::chrono::seconds(5));
  2553. auto res =
  2554. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2555. "application/json", [](uint64_t, uint64_t) { return false; });
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::Canceled, res.error());
  2558. }
  2559. TEST(CancelTest, WithCancelLargePayloadPost) {
  2560. Server svr;
  2561. svr.set_payload_max_length(200 * 1024 * 1024);
  2562. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2563. res.set_content(LARGE_DATA, "text/plain");
  2564. });
  2565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2566. auto se = detail::scope_exit([&] {
  2567. svr.stop();
  2568. thread.join();
  2569. ASSERT_FALSE(svr.is_running());
  2570. });
  2571. svr.wait_until_ready();
  2572. Client cli(HOST, PORT);
  2573. cli.set_payload_max_length(200 * 1024 * 1024);
  2574. cli.set_connection_timeout(std::chrono::seconds(5));
  2575. auto res =
  2576. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2577. "application/json", [](uint64_t, uint64_t) { return false; });
  2578. ASSERT_TRUE(!res);
  2579. EXPECT_EQ(Error::Canceled, res.error());
  2580. }
  2581. TEST(CancelTest, NoCancelPut) {
  2582. Server svr;
  2583. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2584. res.set_content("Hello World!", "text/plain");
  2585. });
  2586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2587. auto se = detail::scope_exit([&] {
  2588. svr.stop();
  2589. thread.join();
  2590. ASSERT_FALSE(svr.is_running());
  2591. });
  2592. svr.wait_until_ready();
  2593. Client cli(HOST, PORT);
  2594. cli.set_connection_timeout(std::chrono::seconds(5));
  2595. auto res =
  2596. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2597. "application/json", [](uint64_t, uint64_t) { return true; });
  2598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2599. EXPECT_EQ("Hello World!", res->body);
  2600. EXPECT_EQ(StatusCode::OK_200, res->status);
  2601. }
  2602. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2603. Server svr;
  2604. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2605. res.set_content("Hello World!", "text/plain");
  2606. });
  2607. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2608. auto se = detail::scope_exit([&] {
  2609. svr.stop();
  2610. thread.join();
  2611. ASSERT_FALSE(svr.is_running());
  2612. });
  2613. svr.wait_until_ready();
  2614. Client cli(HOST, PORT);
  2615. cli.set_connection_timeout(std::chrono::seconds(5));
  2616. auto res =
  2617. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2618. "application/json", [](uint64_t, uint64_t) { return false; });
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Canceled, res.error());
  2621. }
  2622. TEST(CancelTest, WithCancelLargePayloadPut) {
  2623. Server svr;
  2624. svr.set_payload_max_length(200 * 1024 * 1024);
  2625. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2626. res.set_content(LARGE_DATA, "text/plain");
  2627. });
  2628. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2629. auto se = detail::scope_exit([&] {
  2630. svr.stop();
  2631. thread.join();
  2632. ASSERT_FALSE(svr.is_running());
  2633. });
  2634. svr.wait_until_ready();
  2635. Client cli(HOST, PORT);
  2636. cli.set_payload_max_length(200 * 1024 * 1024);
  2637. cli.set_connection_timeout(std::chrono::seconds(5));
  2638. auto res =
  2639. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2640. "application/json", [](uint64_t, uint64_t) { return false; });
  2641. ASSERT_TRUE(!res);
  2642. EXPECT_EQ(Error::Canceled, res.error());
  2643. }
  2644. TEST(CancelTest, NoCancelPatch) {
  2645. Server svr;
  2646. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2647. res.set_content("Hello World!", "text/plain");
  2648. });
  2649. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2650. auto se = detail::scope_exit([&] {
  2651. svr.stop();
  2652. thread.join();
  2653. ASSERT_FALSE(svr.is_running());
  2654. });
  2655. svr.wait_until_ready();
  2656. Client cli(HOST, PORT);
  2657. cli.set_connection_timeout(std::chrono::seconds(5));
  2658. auto res =
  2659. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2660. "application/json", [](uint64_t, uint64_t) { return true; });
  2661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2662. EXPECT_EQ("Hello World!", res->body);
  2663. EXPECT_EQ(StatusCode::OK_200, res->status);
  2664. }
  2665. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2666. Server svr;
  2667. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2668. res.set_content("Hello World!", "text/plain");
  2669. });
  2670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2671. auto se = detail::scope_exit([&] {
  2672. svr.stop();
  2673. thread.join();
  2674. ASSERT_FALSE(svr.is_running());
  2675. });
  2676. svr.wait_until_ready();
  2677. Client cli(HOST, PORT);
  2678. cli.set_connection_timeout(std::chrono::seconds(5));
  2679. auto res =
  2680. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2681. "application/json", [](uint64_t, uint64_t) { return false; });
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::Canceled, res.error());
  2684. }
  2685. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2686. Server svr;
  2687. svr.set_payload_max_length(200 * 1024 * 1024);
  2688. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2689. res.set_content(LARGE_DATA, "text/plain");
  2690. });
  2691. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2692. auto se = detail::scope_exit([&] {
  2693. svr.stop();
  2694. thread.join();
  2695. ASSERT_FALSE(svr.is_running());
  2696. });
  2697. svr.wait_until_ready();
  2698. Client cli(HOST, PORT);
  2699. cli.set_payload_max_length(200 * 1024 * 1024);
  2700. cli.set_connection_timeout(std::chrono::seconds(5));
  2701. auto res =
  2702. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2703. "application/json", [](uint64_t, uint64_t) { return false; });
  2704. ASSERT_TRUE(!res);
  2705. EXPECT_EQ(Error::Canceled, res.error());
  2706. }
  2707. TEST(CancelTest, NoCancelDelete) {
  2708. Server svr;
  2709. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2710. res.set_content("Hello World!", "text/plain");
  2711. });
  2712. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2713. auto se = detail::scope_exit([&] {
  2714. svr.stop();
  2715. thread.join();
  2716. ASSERT_FALSE(svr.is_running());
  2717. });
  2718. svr.wait_until_ready();
  2719. Client cli(HOST, PORT);
  2720. cli.set_connection_timeout(std::chrono::seconds(5));
  2721. auto res =
  2722. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2723. "application/json", [](uint64_t, uint64_t) { return true; });
  2724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2725. EXPECT_EQ("Hello World!", res->body);
  2726. EXPECT_EQ(StatusCode::OK_200, res->status);
  2727. }
  2728. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2729. Server svr;
  2730. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2731. res.set_content("Hello World!", "text/plain");
  2732. });
  2733. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2734. auto se = detail::scope_exit([&] {
  2735. svr.stop();
  2736. thread.join();
  2737. ASSERT_FALSE(svr.is_running());
  2738. });
  2739. svr.wait_until_ready();
  2740. Client cli(HOST, PORT);
  2741. cli.set_connection_timeout(std::chrono::seconds(5));
  2742. auto res =
  2743. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2744. "application/json", [](uint64_t, uint64_t) { return false; });
  2745. ASSERT_TRUE(!res);
  2746. EXPECT_EQ(Error::Canceled, res.error());
  2747. }
  2748. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2749. Server svr;
  2750. svr.set_payload_max_length(200 * 1024 * 1024);
  2751. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2752. res.set_content(LARGE_DATA, "text/plain");
  2753. });
  2754. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(HOST, PORT);
  2762. cli.set_payload_max_length(200 * 1024 * 1024);
  2763. cli.set_connection_timeout(std::chrono::seconds(5));
  2764. auto res =
  2765. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2766. "application/json", [](uint64_t, uint64_t) { return false; });
  2767. ASSERT_TRUE(!res);
  2768. EXPECT_EQ(Error::Canceled, res.error());
  2769. }
  2770. static std::string remove_whitespace(const std::string &input) {
  2771. std::string output;
  2772. output.reserve(input.size());
  2773. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2774. [](unsigned char c) { return !std::isspace(c); });
  2775. return output;
  2776. }
  2777. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2778. auto host = "httpbingo.org";
  2779. auto path = std::string{"/basic-auth/hello/world"};
  2780. #ifdef CPPHTTPLIB_SSL_ENABLED
  2781. auto port = 443;
  2782. SSLClient cli(host, port);
  2783. #else
  2784. auto port = 80;
  2785. Client cli(host, port);
  2786. #endif
  2787. {
  2788. auto res = cli.Get(path);
  2789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2790. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2791. }
  2792. {
  2793. auto res = cli.Get(
  2794. path, Headers{make_basic_authentication_header("hello", "world")});
  2795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2796. auto body = remove_whitespace(res->body);
  2797. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2798. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2799. EXPECT_EQ(StatusCode::OK_200, res->status);
  2800. }
  2801. {
  2802. cli.set_basic_auth("hello", "world");
  2803. auto res = cli.Get(path);
  2804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2805. auto body = remove_whitespace(res->body);
  2806. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2807. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2808. EXPECT_EQ(StatusCode::OK_200, res->status);
  2809. }
  2810. {
  2811. cli.set_basic_auth("hello", "bad");
  2812. auto res = cli.Get(path);
  2813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2814. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2815. }
  2816. {
  2817. cli.set_basic_auth("bad", "world");
  2818. auto res = cli.Get(path);
  2819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2820. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2821. }
  2822. }
  2823. #ifdef CPPHTTPLIB_SSL_ENABLED
  2824. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2825. auto host = "httpbingo.org";
  2826. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2827. auto paths = std::vector<std::string>{
  2828. "/digest-auth/auth/hello/world/MD5",
  2829. "/digest-auth/auth/hello/world/SHA-256",
  2830. };
  2831. auto port = 443;
  2832. SSLClient cli(host, port);
  2833. {
  2834. auto res = cli.Get(unauth_path);
  2835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2836. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2837. }
  2838. {
  2839. cli.set_digest_auth("hello", "world");
  2840. for (const auto &path : paths) {
  2841. auto res = cli.Get(path.c_str());
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. auto body = remove_whitespace(res->body);
  2844. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2845. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2846. EXPECT_EQ(StatusCode::OK_200, res->status);
  2847. }
  2848. cli.set_digest_auth("hello", "bad");
  2849. for (const auto &path : paths) {
  2850. auto res = cli.Get(path.c_str());
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2853. }
  2854. }
  2855. }
  2856. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2857. // comma-separated list of challenges, and each challenge may itself carry a
  2858. // comma-separated auth-param list, so a server can legally offer Basic
  2859. // before Digest, either as two field lines or packed into one. Runs one 401
  2860. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2861. // value() joins them in receipt order) and checks that the retry carries a
  2862. // well-formed Digest Authorization header naming expected_realm.
  2863. static void
  2864. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2865. const std::string &expected_realm) {
  2866. std::atomic<int> hits{0};
  2867. Server svr;
  2868. svr.Get("/x", [&](const Request &req, Response &res) {
  2869. if (++hits == 1) {
  2870. res.status = StatusCode::Unauthorized_401;
  2871. for (const auto &challenge : challenges) {
  2872. res.set_header("WWW-Authenticate", challenge);
  2873. }
  2874. } else {
  2875. auto authorization = req.get_header_value("Authorization");
  2876. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2877. EXPECT_NE(std::string::npos,
  2878. authorization.find("realm=\"" + expected_realm + "\""));
  2879. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2880. res.set_content("ok", "text/plain");
  2881. }
  2882. });
  2883. auto port = svr.bind_to_any_port(HOST);
  2884. std::thread t([&]() { svr.listen_after_bind(); });
  2885. auto se = detail::scope_exit([&] {
  2886. svr.stop();
  2887. t.join();
  2888. });
  2889. svr.wait_until_ready();
  2890. Client cli(HOST, port);
  2891. cli.set_digest_auth("hello", "world");
  2892. auto res = cli.Get("/x");
  2893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2894. EXPECT_EQ(2, hits.load());
  2895. }
  2896. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2897. static const char *kDigestChallenge =
  2898. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2899. "algorithm=MD5";
  2900. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2901. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2902. "testrealm");
  2903. }
  2904. // Same challenge list with the schemes in the opposite order, to make sure
  2905. // the fix above didn't just special-case "Basic first".
  2906. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2907. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2908. "testrealm");
  2909. }
  2910. // A comma inside a quoted auth-param value must not be mistaken for the
  2911. // separator between two challenges (or two auth-params).
  2912. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2913. run_digest_challenge_list_test(
  2914. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2915. "algorithm=MD5"},
  2916. "test,realm");
  2917. }
  2918. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2919. // make_digest_authentication_header() dereferences both unconditionally, so
  2920. // a server sending a challenge missing either one must not be treated as
  2921. // usable -- doing so used to crash the client with std::out_of_range.
  2922. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2923. Server svr;
  2924. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2925. res.status = StatusCode::Unauthorized_401;
  2926. res.set_header("WWW-Authenticate", challenge);
  2927. });
  2928. auto port = svr.bind_to_any_port(HOST);
  2929. std::thread t([&]() { svr.listen_after_bind(); });
  2930. auto se = detail::scope_exit([&] {
  2931. svr.stop();
  2932. t.join();
  2933. });
  2934. svr.wait_until_ready();
  2935. Client cli(HOST, port);
  2936. cli.set_digest_auth("hello", "world");
  2937. auto res = cli.Get("/x");
  2938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2939. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2940. }
  2941. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2942. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2943. }
  2944. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2945. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2946. }
  2947. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2948. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2949. }
  2950. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2951. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2952. // when storing the values, so the header builder has to re-escape them (and
  2953. // keep algorithm a bare token); otherwise the value breaks out of its
  2954. // quoted-string and injects extra auth-params into the client's Authorization.
  2955. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2956. std::atomic<int> hits{0};
  2957. std::string authorization;
  2958. Server svr;
  2959. svr.Get("/x", [&](const Request &req, Response &res) {
  2960. if (++hits == 1) {
  2961. res.status = StatusCode::Unauthorized_401;
  2962. // On the wire the quotes embedded in the values are backslash-escaped.
  2963. res.set_header("WWW-Authenticate",
  2964. "Digest realm=\"testrealm\", "
  2965. "nonce=\"n\\\"; injected=\\\"x\", "
  2966. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2967. } else {
  2968. authorization = req.get_header_value("Authorization");
  2969. res.set_content("ok", "text/plain");
  2970. }
  2971. });
  2972. auto port = svr.bind_to_any_port(HOST);
  2973. std::thread t([&]() { svr.listen_after_bind(); });
  2974. auto se = detail::scope_exit([&] {
  2975. svr.stop();
  2976. t.join();
  2977. });
  2978. svr.wait_until_ready();
  2979. Client cli(HOST, port);
  2980. cli.set_digest_auth("hello", "world");
  2981. auto res = cli.Get("/x");
  2982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2983. EXPECT_EQ(2, hits.load());
  2984. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2985. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2986. // inside its quoted-string rather than starting an "injected" auth-param.
  2987. EXPECT_NE(std::string::npos,
  2988. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2989. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2990. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2991. }
  2992. #endif
  2993. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2994. auto host = "google.com";
  2995. auto another_host = "example.com";
  2996. auto wrong_ip = "0.0.0.0";
  2997. #ifdef CPPHTTPLIB_SSL_ENABLED
  2998. SSLClient cli(host);
  2999. #else
  3000. Client cli(host);
  3001. #endif
  3002. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3003. auto res = cli.Get("/");
  3004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3005. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3006. }
  3007. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3008. auto host = "google.com";
  3009. auto wrong_ip = "0.0.0.0";
  3010. #ifdef CPPHTTPLIB_SSL_ENABLED
  3011. SSLClient cli(host);
  3012. #else
  3013. Client cli(host);
  3014. #endif
  3015. cli.set_hostname_addr_map({{host, wrong_ip}});
  3016. auto res = cli.Get("/");
  3017. ASSERT_TRUE(!res);
  3018. EXPECT_EQ(Error::Connection, res.error());
  3019. }
  3020. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3021. // A mapped value that is not an IP literal must be resolved. "localhost"
  3022. // resolves from the hosts file, so this test needs no external DNS.
  3023. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3024. auto host = "target.invalid";
  3025. Server svr;
  3026. std::string received_host;
  3027. svr.Get("/hi", [&](const Request &req, Response &res) {
  3028. received_host = req.get_header_value("Host");
  3029. res.set_content("Hello World!", "text/plain");
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. thread.join();
  3036. ASSERT_FALSE(svr.is_running());
  3037. });
  3038. svr.wait_until_ready();
  3039. Client cli(host, port);
  3040. cli.set_hostname_addr_map({{host, HOST}});
  3041. auto res = cli.Get("/hi");
  3042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3043. EXPECT_EQ(StatusCode::OK_200, res->status);
  3044. // The mapping only redirects the connection; the identity stays host_.
  3045. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3046. }
  3047. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3048. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3049. auto host = "target.invalid";
  3050. Server svr;
  3051. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3052. res.set_content("Hello World!", "text/plain");
  3053. });
  3054. auto port = svr.bind_to_any_port("127.0.0.1");
  3055. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3056. auto se = detail::scope_exit([&] {
  3057. svr.stop();
  3058. thread.join();
  3059. ASSERT_FALSE(svr.is_running());
  3060. });
  3061. svr.wait_until_ready();
  3062. Client cli(host, port);
  3063. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3064. auto res = cli.Get("/hi");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::OK_200, res->status);
  3067. }
  3068. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3069. // An empty mapped value must leave host_ as the connection target. Without
  3070. // that guard the empty value would become the host argument, getaddrinfo
  3071. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3072. // loopback - silently connecting somewhere the caller never asked for.
  3073. // The server listens on loopback, so such a fallback would succeed and is
  3074. // therefore observable as a failure of this test.
  3075. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3076. Server svr;
  3077. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3078. res.set_content("Hello World!", "text/plain");
  3079. });
  3080. auto port = svr.bind_to_any_port(HOST);
  3081. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3082. auto se = detail::scope_exit([&] {
  3083. svr.stop();
  3084. thread.join();
  3085. ASSERT_FALSE(svr.is_running());
  3086. });
  3087. svr.wait_until_ready();
  3088. Client cli(blackhole, port);
  3089. cli.set_hostname_addr_map({{blackhole, ""}});
  3090. cli.set_connection_timeout(1);
  3091. auto res = cli.Get("/hi");
  3092. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3093. }
  3094. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3095. auto host = "httpbingo.org";
  3096. auto path = std::string{"/absolute-redirect/3"};
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_follow_location(true);
  3103. auto res = cli.Get(path);
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. EXPECT_EQ(StatusCode::OK_200, res->status);
  3106. }
  3107. TEST(RedirectTest, Redirect_Online) {
  3108. auto host = "httpbingo.org";
  3109. auto path = std::string{"/redirect/3"};
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(host);
  3112. #else
  3113. Client cli(host);
  3114. #endif
  3115. cli.set_follow_location(true);
  3116. auto res = cli.Get(path);
  3117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3118. EXPECT_EQ(StatusCode::OK_200, res->status);
  3119. }
  3120. TEST(RelativeRedirectTest, Redirect_Online) {
  3121. auto host = "httpbingo.org";
  3122. auto path = std::string{"/relative-redirect/3"};
  3123. #ifdef CPPHTTPLIB_SSL_ENABLED
  3124. SSLClient cli(host);
  3125. #else
  3126. Client cli(host);
  3127. #endif
  3128. cli.set_follow_location(true);
  3129. auto res = cli.Get(path);
  3130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. }
  3133. TEST(TooManyRedirectTest, Redirect_Online) {
  3134. auto host = "httpbingo.org";
  3135. auto path = std::string{"/redirect/21"};
  3136. #ifdef CPPHTTPLIB_SSL_ENABLED
  3137. SSLClient cli(host);
  3138. #else
  3139. Client cli(host);
  3140. #endif
  3141. cli.set_follow_location(true);
  3142. auto res = cli.Get(path);
  3143. ASSERT_TRUE(!res);
  3144. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3145. }
  3146. #ifdef CPPHTTPLIB_SSL_ENABLED
  3147. TEST(YahooRedirectTest, Redirect_Online) {
  3148. Client cli("yahoo.com");
  3149. auto res = cli.Get("/");
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3152. cli.set_follow_location(true);
  3153. res = cli.Get("/");
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3157. }
  3158. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3159. #define REDIR_HOST "httpbingo.org"
  3160. #define REDIR_PATH "/redirect-to"
  3161. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3162. SSLClient cli(REDIR_HOST);
  3163. cli.set_follow_location(true);
  3164. auto res =
  3165. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. }
  3169. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3170. SSLClient cli(REDIR_HOST);
  3171. cli.set_follow_location(true);
  3172. Params params;
  3173. params.emplace("url", "http://example.com");
  3174. params.emplace("status_code", "302");
  3175. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. }
  3179. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3180. SSLClient cli(REDIR_HOST);
  3181. cli.set_follow_location(true);
  3182. Params params;
  3183. params.emplace("url", "http://example.com");
  3184. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3186. EXPECT_EQ(StatusCode::OK_200, res->status);
  3187. }
  3188. TEST(UrlWithSpace, Redirect_Online) {
  3189. SSLClient cli("edge.forgecdn.net");
  3190. cli.set_follow_location(true);
  3191. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3193. EXPECT_EQ(StatusCode::OK_200, res->status);
  3194. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3195. }
  3196. #endif
  3197. #if !defined(_WIN32) && !defined(_WIN64)
  3198. TEST(ReceiveSignals, Signal) {
  3199. auto setupSignalHandlers = []() {
  3200. struct sigaction act;
  3201. sigemptyset(&act.sa_mask);
  3202. act.sa_flags = SA_SIGINFO;
  3203. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3204. switch (sig) {
  3205. case SIGINT:
  3206. default: break;
  3207. }
  3208. };
  3209. ::sigaction(SIGINT, &act, nullptr);
  3210. };
  3211. Server svr;
  3212. int port = 0;
  3213. auto thread = std::thread([&]() {
  3214. setupSignalHandlers();
  3215. port = svr.bind_to_any_port(HOST);
  3216. svr.listen_after_bind();
  3217. });
  3218. auto se = detail::scope_exit([&] {
  3219. svr.stop();
  3220. thread.join();
  3221. ASSERT_FALSE(svr.is_running());
  3222. });
  3223. svr.wait_until_ready();
  3224. ASSERT_TRUE(svr.is_running());
  3225. pthread_kill(thread.native_handle(), SIGINT);
  3226. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3227. ASSERT_TRUE(svr.is_running());
  3228. }
  3229. #endif
  3230. TEST(RedirectToDifferentPort, Redirect) {
  3231. Server svr1;
  3232. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3233. res.set_content("Hello World!", "text/plain");
  3234. });
  3235. int svr1_port = 0;
  3236. auto thread1 = std::thread([&]() {
  3237. svr1_port = svr1.bind_to_any_port(HOST);
  3238. svr1.listen_after_bind();
  3239. });
  3240. Server svr2;
  3241. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3242. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3243. });
  3244. int svr2_port = 0;
  3245. auto thread2 = std::thread([&]() {
  3246. svr2_port = svr2.bind_to_any_port(HOST);
  3247. svr2.listen_after_bind();
  3248. });
  3249. auto se = detail::scope_exit([&] {
  3250. svr2.stop();
  3251. thread2.join();
  3252. svr1.stop();
  3253. thread1.join();
  3254. ASSERT_FALSE(svr2.is_running());
  3255. ASSERT_FALSE(svr1.is_running());
  3256. });
  3257. svr1.wait_until_ready();
  3258. svr2.wait_until_ready();
  3259. Client cli("localhost", svr2_port);
  3260. cli.set_follow_location(true);
  3261. auto res = cli.Get("/2");
  3262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3263. EXPECT_EQ(StatusCode::OK_200, res->status);
  3264. EXPECT_EQ("Hello World!", res->body);
  3265. }
  3266. // GET /redir on one server redirects to /target on another port, so the
  3267. // client follows it with a new client.
  3268. static Result
  3269. GetThroughRedirectToDifferentPort(Server::Handler target,
  3270. const std::function<void(Client &)> &setup,
  3271. const Headers &headers = Headers()) {
  3272. Server target_svr;
  3273. target_svr.Get("/target", target);
  3274. int target_port = 0;
  3275. auto target_thread = std::thread([&]() {
  3276. target_port = target_svr.bind_to_any_port(HOST);
  3277. target_svr.listen_after_bind();
  3278. });
  3279. Server origin_svr;
  3280. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3281. res.set_redirect(
  3282. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3283. });
  3284. int origin_port = 0;
  3285. auto origin_thread = std::thread([&]() {
  3286. origin_port = origin_svr.bind_to_any_port(HOST);
  3287. origin_svr.listen_after_bind();
  3288. });
  3289. auto se = detail::scope_exit([&] {
  3290. origin_svr.stop();
  3291. origin_thread.join();
  3292. target_svr.stop();
  3293. target_thread.join();
  3294. });
  3295. target_svr.wait_until_ready();
  3296. origin_svr.wait_until_ready();
  3297. Client cli("localhost", origin_port);
  3298. cli.set_follow_location(true);
  3299. setup(cli);
  3300. return cli.Get("/redir", headers);
  3301. }
  3302. static void
  3303. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3304. std::string captured_authorization;
  3305. auto result = GetThroughRedirectToDifferentPort(
  3306. [&](const Request &req, Response &res) {
  3307. captured_authorization = req.get_header_value("Authorization");
  3308. res.set_content("OK", "text/plain");
  3309. },
  3310. set_auth);
  3311. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3312. EXPECT_EQ(StatusCode::OK_200, result->status);
  3313. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3314. EXPECT_TRUE(captured_authorization.empty());
  3315. }
  3316. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3317. TestDoNotForwardCredentialsOnRedirect(
  3318. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3319. }
  3320. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3321. TestDoNotForwardCredentialsOnRedirect(
  3322. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3323. }
  3324. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3325. std::string captured_cookie;
  3326. auto result = GetThroughRedirectToDifferentPort(
  3327. [&](const Request &req, Response &res) {
  3328. captured_cookie = req.get_header_value("Cookie");
  3329. res.set_content("OK", "text/plain");
  3330. },
  3331. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3332. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3333. EXPECT_EQ(StatusCode::OK_200, result->status);
  3334. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3335. EXPECT_TRUE(captured_cookie.empty());
  3336. }
  3337. TEST(RedirectToSamePort, ForwardCookie) {
  3338. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3339. // header so that ordinary session flows keep working.
  3340. Server svr;
  3341. std::string captured_cookie;
  3342. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3343. res.set_redirect("/target", 302);
  3344. });
  3345. svr.Get("/target", [&](const Request &req, Response &res) {
  3346. captured_cookie = req.get_header_value("Cookie");
  3347. res.set_content("OK", "text/plain");
  3348. });
  3349. auto port = svr.bind_to_any_port(HOST);
  3350. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3351. auto se = detail::scope_exit([&] {
  3352. svr.stop();
  3353. thread.join();
  3354. ASSERT_FALSE(svr.is_running());
  3355. });
  3356. svr.wait_until_ready();
  3357. Client cli(HOST, port);
  3358. cli.set_follow_location(true);
  3359. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3360. auto res = cli.Get("/redir", headers);
  3361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3362. EXPECT_EQ(StatusCode::OK_200, res->status);
  3363. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3364. }
  3365. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3366. std::string authorization;
  3367. std::string trace_id;
  3368. auto result = GetThroughRedirectToDifferentPort(
  3369. [&](const Request &req, Response &res) {
  3370. authorization = req.get_header_value("Authorization");
  3371. trace_id = req.get_header_value("X-Trace-Id");
  3372. res.set_content("OK", "text/plain");
  3373. },
  3374. [](Client &cli) {
  3375. cli.set_default_headers(
  3376. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3377. });
  3378. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3379. EXPECT_EQ(StatusCode::OK_200, result->status);
  3380. // Like a header given with the request, a default one goes along unless it
  3381. // carries credentials (RFC 9110 15.4).
  3382. EXPECT_TRUE(authorization.empty());
  3383. EXPECT_EQ("42", trace_id);
  3384. }
  3385. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3386. auto result = GetThroughRedirectToDifferentPort(
  3387. [](const Request &, Response &res) {
  3388. res.set_content(std::string(2048, 'x'), "text/plain");
  3389. },
  3390. [](Client &cli) { cli.set_payload_max_length(1024); });
  3391. EXPECT_FALSE(result);
  3392. }
  3393. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3394. auto result = GetThroughRedirectToDifferentPort(
  3395. [](const Request &req, Response &res) {
  3396. // Answer after a second, or once the client gives up.
  3397. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3398. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3399. }
  3400. res.set_content("late", "text/plain");
  3401. },
  3402. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3403. ASSERT_FALSE(result);
  3404. EXPECT_EQ(Error::Read, result.error());
  3405. }
  3406. #ifdef CPPHTTPLIB_SSL_ENABLED
  3407. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [](const Request &, Response &res) {
  3410. res.status = StatusCode::Unauthorized_401;
  3411. res.set_header("WWW-Authenticate",
  3412. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3413. },
  3414. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3415. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3416. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3417. }
  3418. #endif
  3419. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3420. Server svr;
  3421. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3422. // Port number that overflows int — should not crash
  3423. res.set_redirect("http://localhost:99999999999999999999/target");
  3424. });
  3425. auto port = svr.bind_to_any_port(HOST);
  3426. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3427. auto se = detail::scope_exit([&] {
  3428. svr.stop();
  3429. thread.join();
  3430. ASSERT_FALSE(svr.is_running());
  3431. });
  3432. svr.wait_until_ready();
  3433. Client cli(HOST, port);
  3434. cli.set_follow_location(true);
  3435. auto res = cli.Get("/redir");
  3436. // Should fail gracefully, not crash (no valid response due to bad port)
  3437. EXPECT_FALSE(res);
  3438. }
  3439. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3440. Server svr;
  3441. auto port = svr.bind_to_any_port(HOST);
  3442. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3443. // The server's own port followed by junk must not be followed
  3444. res.set_redirect("http://" + std::string(HOST) + ":" +
  3445. std::to_string(port) + "junk/target");
  3446. });
  3447. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3448. res.set_content("target", "text/plain");
  3449. });
  3450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. Client cli(HOST, port);
  3458. cli.set_follow_location(true);
  3459. auto res = cli.Get("/redir");
  3460. EXPECT_FALSE(res);
  3461. }
  3462. TEST(RedirectFromPageWithContent, Redirect) {
  3463. Server svr;
  3464. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3465. res.set_content("___", "text/plain");
  3466. res.set_redirect("/2");
  3467. });
  3468. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3469. res.set_content("Hello World!", "text/plain");
  3470. });
  3471. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3472. auto se = detail::scope_exit([&] {
  3473. svr.stop();
  3474. th.join();
  3475. ASSERT_FALSE(svr.is_running());
  3476. });
  3477. svr.wait_until_ready();
  3478. {
  3479. Client cli("localhost", PORT);
  3480. cli.set_follow_location(true);
  3481. std::string body;
  3482. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3483. body.append(data, data_length);
  3484. return true;
  3485. });
  3486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3487. EXPECT_EQ(StatusCode::OK_200, res->status);
  3488. EXPECT_EQ("Hello World!", body);
  3489. }
  3490. {
  3491. Client cli("localhost", PORT);
  3492. std::string body;
  3493. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3494. body.append(data, data_length);
  3495. return true;
  3496. });
  3497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3498. EXPECT_EQ(StatusCode::Found_302, res->status);
  3499. EXPECT_EQ("___", body);
  3500. }
  3501. }
  3502. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3503. Server svr;
  3504. auto port_str = std::to_string(PORT);
  3505. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3506. auto expected_host = "[::1]:" + port_str;
  3507. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3508. res.set_content("___", "text/plain");
  3509. // res.set_redirect("/2");
  3510. res.set_redirect(redirect_url);
  3511. });
  3512. svr.Get("/2", [&](const Request &req, Response &res) {
  3513. auto host_header = req.headers.find("Host");
  3514. ASSERT_TRUE(host_header != req.headers.end());
  3515. EXPECT_EQ(expected_host, host_header->second);
  3516. res.set_content("Hello World!", "text/plain");
  3517. });
  3518. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3519. auto se = detail::scope_exit([&] {
  3520. svr.stop();
  3521. th.join();
  3522. ASSERT_FALSE(svr.is_running());
  3523. });
  3524. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3525. // actually starts anything, so the condition !svr.is_running() will
  3526. // always remain true, and the loop never stops.
  3527. // This basically counts how many milliseconds have passed since the
  3528. // call to svr.listen(), and if after 5 seconds nothing started yet
  3529. // aborts the test.
  3530. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3531. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3532. ASSERT_LT(milliseconds, 5000U);
  3533. }
  3534. {
  3535. Client cli("::1", PORT);
  3536. cli.set_follow_location(true);
  3537. std::string body;
  3538. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3539. body.append(data, data_length);
  3540. return true;
  3541. });
  3542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3543. EXPECT_EQ(StatusCode::OK_200, res->status);
  3544. EXPECT_EQ("Hello World!", body);
  3545. }
  3546. {
  3547. Client cli("::1", PORT);
  3548. std::string body;
  3549. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3550. body.append(data, data_length);
  3551. return true;
  3552. });
  3553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3554. EXPECT_EQ(StatusCode::Found_302, res->status);
  3555. EXPECT_EQ("___", body);
  3556. }
  3557. }
  3558. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3559. Server svr;
  3560. svr.Get("/foo", [](const Request &req, Response &res) {
  3561. auto a = req.params.find("a");
  3562. if (a != req.params.end()) {
  3563. res.set_content((*a).second, "text/plain");
  3564. res.status = StatusCode::OK_200;
  3565. } else {
  3566. res.status = StatusCode::BadRequest_400;
  3567. }
  3568. });
  3569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3570. auto se = detail::scope_exit([&] {
  3571. svr.stop();
  3572. thread.join();
  3573. ASSERT_FALSE(svr.is_running());
  3574. });
  3575. svr.wait_until_ready();
  3576. {
  3577. Client cli(HOST, PORT);
  3578. cli.set_path_encode(false);
  3579. auto res = cli.Get("/foo?a=explicitly+encoded");
  3580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3581. EXPECT_EQ(StatusCode::OK_200, res->status);
  3582. // This expects it back with a space, as the `+` won't have been
  3583. // url-encoded, and server-side the params get decoded turning `+`
  3584. // into spaces.
  3585. EXPECT_EQ("explicitly encoded", res->body);
  3586. }
  3587. }
  3588. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3589. // When path encoding is disabled the client must transmit the supplied
  3590. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3591. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3592. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3593. // than a space (0x20). Assert on the raw wire target to catch this.
  3594. Server svr;
  3595. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3596. svr.Get("/foo", [&](const Request &req, Response &res) {
  3597. EXPECT_EQ(expected_target, req.target);
  3598. res.status = StatusCode::OK_200;
  3599. });
  3600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3601. auto se = detail::scope_exit([&] {
  3602. svr.stop();
  3603. thread.join();
  3604. ASSERT_FALSE(svr.is_running());
  3605. });
  3606. svr.wait_until_ready();
  3607. {
  3608. Client cli(HOST, PORT);
  3609. cli.set_path_encode(false);
  3610. auto res = cli.Get(expected_target.c_str());
  3611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3612. EXPECT_EQ(StatusCode::OK_200, res->status);
  3613. }
  3614. }
  3615. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3616. // `open_stream()` used to skip the path encoding that the buffered send
  3617. // path applies, so the same `path` produced different bytes in the request
  3618. // line depending on which API was used. Assert the two agree.
  3619. Server svr;
  3620. std::string target;
  3621. svr.Get(".*", [&](const Request &req, Response &res) {
  3622. target = req.target;
  3623. res.status = StatusCode::OK_200;
  3624. });
  3625. auto port = svr.bind_to_any_port(HOST);
  3626. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. thread.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. struct {
  3634. const char *path;
  3635. const char *expected;
  3636. } cases[] = {
  3637. {"/a b?x=1", "/a%20b?x=1"},
  3638. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3639. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3640. };
  3641. for (const auto &c : cases) {
  3642. Client cli(HOST, port);
  3643. target.clear();
  3644. auto res = cli.Get(c.path);
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3647. auto buffered_target = target;
  3648. target.clear();
  3649. auto handle = cli.open_stream("GET", c.path);
  3650. EXPECT_TRUE(handle.is_valid())
  3651. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3652. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3653. }
  3654. }
  3655. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3656. // The `set_path_encode(false)` contract — transmit the supplied target
  3657. // verbatim — must hold for the streaming API too.
  3658. Server svr;
  3659. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3660. std::string target;
  3661. svr.Get("/foo", [&](const Request &req, Response &res) {
  3662. target = req.target;
  3663. res.status = StatusCode::OK_200;
  3664. });
  3665. auto port = svr.bind_to_any_port(HOST);
  3666. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3667. auto se = detail::scope_exit([&] {
  3668. svr.stop();
  3669. thread.join();
  3670. ASSERT_FALSE(svr.is_running());
  3671. });
  3672. svr.wait_until_ready();
  3673. {
  3674. Client cli(HOST, port);
  3675. cli.set_path_encode(false);
  3676. auto handle = cli.open_stream("GET", expected_target);
  3677. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3678. EXPECT_EQ(expected_target, target);
  3679. }
  3680. }
  3681. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3682. // With path encoding enabled a CR/LF in the target is percent-encoded
  3683. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3684. // write_request_line still backstops `set_path_encode(false)`, which is
  3685. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3686. Server svr;
  3687. // Captured before routing: the decoded path contains a newline, which a
  3688. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3689. std::string target;
  3690. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3691. target = req.target;
  3692. res.status = StatusCode::OK_200;
  3693. return Server::HandlerResponse::Handled;
  3694. });
  3695. auto port = svr.bind_to_any_port(HOST);
  3696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. {
  3704. Client cli(HOST, port);
  3705. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3706. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3707. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3708. }
  3709. }
  3710. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3711. // Every control character is percent-encoded, not just CR/LF, so the target
  3712. // passes the request-target check in write_request_line.
  3713. Server svr;
  3714. std::string target;
  3715. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3716. target = req.target;
  3717. res.status = StatusCode::OK_200;
  3718. return Server::HandlerResponse::Handled;
  3719. });
  3720. auto port = svr.bind_to_any_port(HOST);
  3721. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. Client cli(HOST, port);
  3730. auto res = cli.Get("/a\tb\x1b\x7f");
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ("/a%09b%1B%7F", target);
  3733. }
  3734. }
  3735. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3736. // Nothing may reach the wire: a raw CR/LF target would split the request
  3737. // line and inject headers.
  3738. Server svr;
  3739. // Pre-routing so that "not called" means nothing reached the server at all,
  3740. // rather than merely failing to match a handler pattern.
  3741. auto handler_called = false;
  3742. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3743. handler_called = true;
  3744. res.status = StatusCode::OK_200;
  3745. return Server::HandlerResponse::Handled;
  3746. });
  3747. auto port = svr.bind_to_any_port(HOST);
  3748. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli(HOST, port);
  3757. cli.set_path_encode(false);
  3758. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3759. EXPECT_FALSE(handle.is_valid());
  3760. EXPECT_EQ(Error::Write, handle.error);
  3761. EXPECT_FALSE(handler_called);
  3762. }
  3763. }
  3764. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3765. // Which of the two branches runs is decided by whether the query component
  3766. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3767. // an empty query and must still fall back to building one from
  3768. // `req.params`, while a non-empty query must win over `req.params`.
  3769. Server svr;
  3770. std::string target;
  3771. svr.Get("/foo", [&](const Request &req, Response &res) {
  3772. target = req.target;
  3773. res.status = StatusCode::OK_200;
  3774. });
  3775. auto port = svr.bind_to_any_port(HOST);
  3776. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. // Trailing `?` -> empty query component -> `req.params` is used.
  3785. Client cli(HOST, port);
  3786. Request req;
  3787. req.method = "GET";
  3788. req.path = "/foo?";
  3789. req.params.emplace("a", "1");
  3790. target.clear();
  3791. auto res = cli.send(req);
  3792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3793. EXPECT_EQ("/foo?a=1", target);
  3794. }
  3795. {
  3796. // Non-empty query in `req.path` -> `req.params` is not appended.
  3797. Client cli(HOST, port);
  3798. Request req;
  3799. req.method = "GET";
  3800. req.path = "/foo?b=2";
  3801. req.params.emplace("a", "1");
  3802. target.clear();
  3803. auto res = cli.send(req);
  3804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3805. EXPECT_EQ("/foo?b=2", target);
  3806. }
  3807. }
  3808. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3809. Server svr;
  3810. svr.Get("/", [](const Request &req, Response &) {
  3811. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3812. });
  3813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3814. auto se = detail::scope_exit([&] {
  3815. svr.stop();
  3816. thread.join();
  3817. ASSERT_FALSE(svr.is_running());
  3818. });
  3819. svr.wait_until_ready();
  3820. {
  3821. Client cli(HOST, PORT);
  3822. cli.set_path_encode(false);
  3823. auto res = cli.Get("/?something=%0A");
  3824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3825. EXPECT_EQ(StatusCode::OK_200, res->status);
  3826. }
  3827. }
  3828. TEST(BindServerTest, BindDualStack) {
  3829. Server svr;
  3830. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3831. res.set_content("Hello World!", "text/plain");
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. {
  3841. Client cli("127.0.0.1", PORT);
  3842. auto res = cli.Get("/1");
  3843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3844. EXPECT_EQ(StatusCode::OK_200, res->status);
  3845. EXPECT_EQ("Hello World!", res->body);
  3846. }
  3847. {
  3848. Client cli("::1", PORT);
  3849. auto res = cli.Get("/1");
  3850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3851. EXPECT_EQ(StatusCode::OK_200, res->status);
  3852. EXPECT_EQ("Hello World!", res->body);
  3853. }
  3854. }
  3855. TEST(BindServerTest, BindAndListenSeparately) {
  3856. Server svr;
  3857. int port = svr.bind_to_any_port("0.0.0.0");
  3858. ASSERT_TRUE(svr.is_valid());
  3859. ASSERT_TRUE(port > 0);
  3860. svr.stop();
  3861. }
  3862. // Reports whether anything is still listening on a loopback port. A plain
  3863. // connect() is used instead of a Client request because a socket left bound by
  3864. // mistake accepts the connection into its backlog and never answers, which
  3865. // would hang the test instead of failing it.
  3866. static bool is_loopback_port_accepting(int port) {
  3867. sockaddr_in addr{};
  3868. addr.sin_family = AF_INET;
  3869. addr.sin_port = htons(static_cast<uint16_t>(port));
  3870. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3871. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3872. EXPECT_NE(sock, INVALID_SOCKET);
  3873. if (sock == INVALID_SOCKET) { return false; }
  3874. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3875. static_cast<socklen_t>(sizeof(addr)));
  3876. detail::close_socket(sock);
  3877. return ret == 0;
  3878. }
  3879. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3880. Server svr;
  3881. auto port = svr.bind_to_any_port("127.0.0.1");
  3882. ASSERT_TRUE(port > 0);
  3883. svr.stop();
  3884. // bind_to_any_port() already called listen(2), so until stop() closed the
  3885. // descriptor the port kept accepting connections into the backlog. ASSERT
  3886. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3887. // below blocks forever in the accept loop.
  3888. ASSERT_FALSE(is_loopback_port_accepting(port));
  3889. // Nothing is left to accept on, so listen_after_bind() must report failure
  3890. // instead of returning success without ever serving.
  3891. EXPECT_FALSE(svr.listen_after_bind());
  3892. // The failed listen marks the server decommissioned, so a waiter returns
  3893. // instead of spinning forever.
  3894. svr.wait_until_ready();
  3895. }
  3896. #ifdef CPPHTTPLIB_SSL_ENABLED
  3897. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3899. CLIENT_CA_CERT_DIR);
  3900. int port = svr.bind_to_any_port("0.0.0.0");
  3901. ASSERT_TRUE(svr.is_valid());
  3902. ASSERT_TRUE(port > 0);
  3903. svr.stop();
  3904. }
  3905. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3906. // or a rejected CustomRoute() registration would not stop the server binding.
  3907. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3909. CLIENT_CA_CERT_DIR);
  3910. ASSERT_TRUE(svr.is_valid());
  3911. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3912. EXPECT_FALSE(svr.is_valid());
  3913. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3914. }
  3915. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3916. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3917. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3918. int port = svr.bind_to_any_port("0.0.0.0");
  3919. ASSERT_TRUE(svr.is_valid());
  3920. ASSERT_TRUE(port > 0);
  3921. svr.stop();
  3922. }
  3923. TEST(BindServerTest, UpdateCertsPem) {
  3924. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3925. int port = svr.bind_to_any_port("0.0.0.0");
  3926. ASSERT_TRUE(svr.is_valid());
  3927. ASSERT_TRUE(port > 0);
  3928. // Read PEM files
  3929. std::string cert_pem, key_pem, ca_pem;
  3930. read_file(SERVER_CERT_FILE, cert_pem);
  3931. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3932. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3933. // Update server certificates using PEM API
  3934. ASSERT_TRUE(
  3935. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3936. ASSERT_TRUE(svr.is_valid());
  3937. svr.stop();
  3938. }
  3939. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3940. // Start server with client CA (enables client auth)
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3942. ASSERT_TRUE(svr.is_valid());
  3943. bool handler_called = false;
  3944. svr.Get("/test", [&](const Request &req, Response &res) {
  3945. handler_called = true;
  3946. // Verify client certificate is present
  3947. auto cert = req.peer_cert();
  3948. EXPECT_TRUE(static_cast<bool>(cert));
  3949. res.set_content("ok", "text/plain");
  3950. });
  3951. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3952. auto se = detail::scope_exit([&] {
  3953. svr.stop();
  3954. t.join();
  3955. ASSERT_FALSE(svr.is_running());
  3956. });
  3957. svr.wait_until_ready();
  3958. // Read PEM files
  3959. std::string cert_pem, key_pem, ca_pem;
  3960. read_file(SERVER_CERT_FILE, cert_pem);
  3961. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3962. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3963. // Update server certificates and client CA using PEM API while server running
  3964. ASSERT_TRUE(
  3965. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3966. // Connect with client certificate
  3967. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3968. cli.enable_server_certificate_verification(false);
  3969. cli.set_connection_timeout(30);
  3970. auto res = cli.Get("/test");
  3971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3972. ASSERT_EQ(StatusCode::OK_200, res->status);
  3973. ASSERT_TRUE(handler_called);
  3974. EXPECT_EQ("ok", res->body);
  3975. }
  3976. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3978. ASSERT_TRUE(svr.is_valid());
  3979. svr.Get("/test", [](const Request &, Response &res) {
  3980. res.set_content("ok", "text/plain");
  3981. });
  3982. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3983. auto se = detail::scope_exit([&] {
  3984. svr.stop();
  3985. t.join();
  3986. ASSERT_FALSE(svr.is_running());
  3987. });
  3988. svr.wait_until_ready();
  3989. // A connection that sends no ClientHello keeps its handshake in progress,
  3990. // once the server has had a moment to start it.
  3991. auto error = Error::Success;
  3992. auto sock = detail::create_client_socket(
  3993. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3994. /*connection_timeout_sec=*/5, 0,
  3995. /*read_timeout_sec=*/5, 0,
  3996. /*write_timeout_sec=*/5, 0, std::string(), error);
  3997. ASSERT_NE(INVALID_SOCKET, sock);
  3998. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3999. std::string cert_pem, key_pem;
  4000. read_file(SERVER_CERT_FILE, cert_pem);
  4001. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4002. auto update = std::async(std::launch::async, [&]() {
  4003. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4004. });
  4005. EXPECT_EQ(std::future_status::timeout,
  4006. update.wait_for(std::chrono::milliseconds(200)));
  4007. detail::close_socket(sock);
  4008. EXPECT_TRUE(update.get());
  4009. SSLClient cli(HOST, PORT);
  4010. cli.enable_server_certificate_verification(false);
  4011. auto res = cli.Get("/test");
  4012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4013. EXPECT_EQ(StatusCode::OK_200, res->status);
  4014. }
  4015. #endif
  4016. TEST(ErrorHandlerTest, ContentLength) {
  4017. Server svr;
  4018. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4019. res.status = StatusCode::OK_200;
  4020. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4021. "text/html"); // <= Content-Length still 13
  4022. });
  4023. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4024. res.set_content("Hello World!\n", "text/plain");
  4025. res.status = 524;
  4026. });
  4027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4028. auto se = detail::scope_exit([&] {
  4029. svr.stop();
  4030. thread.join();
  4031. ASSERT_FALSE(svr.is_running());
  4032. });
  4033. svr.wait_until_ready();
  4034. {
  4035. Client cli(HOST, PORT);
  4036. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4038. EXPECT_EQ(StatusCode::OK_200, res->status);
  4039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4042. }
  4043. }
  4044. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4045. TEST(ExceptionTest, WithoutExceptionHandler) {
  4046. Server svr;
  4047. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4048. throw std::runtime_error("exception...");
  4049. });
  4050. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4051. throw std::runtime_error("exception\r\n...");
  4052. });
  4053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4054. auto se = detail::scope_exit([&] {
  4055. svr.stop();
  4056. listen_thread.join();
  4057. ASSERT_FALSE(svr.is_running());
  4058. });
  4059. svr.wait_until_ready();
  4060. Client cli("localhost", PORT);
  4061. {
  4062. auto res = cli.Get("/exception");
  4063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4064. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4065. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4066. }
  4067. {
  4068. auto res = cli.Get("/unknown");
  4069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4070. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4071. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4072. }
  4073. }
  4074. TEST(ExceptionTest, WithExceptionHandler) {
  4075. Server svr;
  4076. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4077. std::exception_ptr ep) {
  4078. EXPECT_FALSE(ep == nullptr);
  4079. try {
  4080. std::rethrow_exception(ep);
  4081. } catch (std::exception &e) {
  4082. EXPECT_EQ("abc", std::string(e.what()));
  4083. } catch (...) {}
  4084. res.status = StatusCode::InternalServerError_500;
  4085. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4086. "text/html"); // <= Content-Length still 13 at this point
  4087. });
  4088. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4089. res.set_content("Hello World!\n", "text/plain");
  4090. throw std::runtime_error("abc");
  4091. });
  4092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4093. auto se = detail::scope_exit([&] {
  4094. svr.stop();
  4095. thread.join();
  4096. ASSERT_FALSE(svr.is_running());
  4097. });
  4098. svr.wait_until_ready();
  4099. for (size_t i = 0; i < 10; i++) {
  4100. Client cli(HOST, PORT);
  4101. for (size_t j = 0; j < 100; j++) {
  4102. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4104. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4105. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4106. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4107. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4108. }
  4109. cli.set_keep_alive(true);
  4110. for (size_t j = 0; j < 100; j++) {
  4111. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4113. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4114. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4115. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4116. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4117. }
  4118. }
  4119. }
  4120. TEST(ExceptionTest, AndErrorHandler) {
  4121. Server svr;
  4122. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4123. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4124. });
  4125. svr.set_exception_handler(
  4126. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4127. EXPECT_FALSE(ep == nullptr);
  4128. try {
  4129. std::rethrow_exception(ep);
  4130. } catch (std::exception &e) {
  4131. res.set_content(e.what(), "text/html");
  4132. } catch (...) {}
  4133. res.status = StatusCode::InternalServerError_500;
  4134. });
  4135. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4136. throw std::runtime_error("EXCEPTION");
  4137. });
  4138. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4139. res.set_content("ERROR", "text/html");
  4140. res.status = StatusCode::InternalServerError_500;
  4141. });
  4142. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4143. auto se = detail::scope_exit([&] {
  4144. svr.stop();
  4145. thread.join();
  4146. ASSERT_FALSE(svr.is_running());
  4147. });
  4148. svr.wait_until_ready();
  4149. Client cli(HOST, PORT);
  4150. {
  4151. auto res = cli.Get("/exception");
  4152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4153. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4154. EXPECT_EQ("EXCEPTION", res->body);
  4155. }
  4156. {
  4157. auto res = cli.Get("/error");
  4158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4159. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4160. EXPECT_EQ("ERROR", res->body);
  4161. }
  4162. {
  4163. auto res = cli.Get("/invalid");
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4166. EXPECT_EQ("NOT_FOUND", res->body);
  4167. }
  4168. }
  4169. #endif
  4170. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4171. // process_request() wraps only routing() in a try/catch, so an exception from
  4172. // any other user callback used to unwind into the task queue - which does not
  4173. // catch - and terminate the process. Each test below runs the server on a
  4174. // single worker thread: a guard that catches the exception but still loses the
  4175. // thread would otherwise be hidden by a spare worker serving the follow-up
  4176. // request. Note that a regression here aborts the whole test binary rather
  4177. // than failing one test.
  4178. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4179. Server svr;
  4180. svr.new_task_queue = [] { return new ThreadPool(1); };
  4181. std::atomic<int> reported{0};
  4182. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4183. if (err == Error::UserCallbackException) { reported++; }
  4184. });
  4185. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4186. res.set_content_provider(
  4187. 1024, "text/plain",
  4188. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4189. sink.write("hello", 5);
  4190. throw std::runtime_error("from the content provider");
  4191. });
  4192. });
  4193. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4194. res.set_content("ok", "text/plain");
  4195. });
  4196. auto port = svr.bind_to_any_port(HOST);
  4197. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4198. auto se = detail::scope_exit([&] {
  4199. svr.stop();
  4200. listen_thread.join();
  4201. ASSERT_FALSE(svr.is_running());
  4202. });
  4203. svr.wait_until_ready();
  4204. {
  4205. Client cli(HOST, port);
  4206. cli.set_read_timeout(5, 0);
  4207. EXPECT_FALSE(cli.Get("/throw"));
  4208. }
  4209. EXPECT_TRUE(svr.is_running());
  4210. EXPECT_EQ(1, reported.load());
  4211. // A request on a fresh connection is still served.
  4212. {
  4213. Client cli(HOST, port);
  4214. auto res = cli.Get("/ok");
  4215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4216. EXPECT_EQ(StatusCode::OK_200, res->status);
  4217. EXPECT_EQ("ok", res->body);
  4218. }
  4219. }
  4220. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4221. Server svr;
  4222. svr.new_task_queue = [] { return new ThreadPool(1); };
  4223. std::atomic<bool> should_throw{true};
  4224. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4225. res.set_content("hi", "text/plain");
  4226. });
  4227. svr.set_post_routing_handler(
  4228. [&](const Request & /*req*/, Response & /*res*/) {
  4229. if (should_throw) {
  4230. throw std::runtime_error("from the post-routing handler");
  4231. }
  4232. });
  4233. auto port = svr.bind_to_any_port(HOST);
  4234. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4235. auto se = detail::scope_exit([&] {
  4236. svr.stop();
  4237. listen_thread.join();
  4238. ASSERT_FALSE(svr.is_running());
  4239. });
  4240. svr.wait_until_ready();
  4241. {
  4242. Client cli(HOST, port);
  4243. cli.set_read_timeout(5, 0);
  4244. EXPECT_FALSE(cli.Get("/hi"));
  4245. }
  4246. EXPECT_TRUE(svr.is_running());
  4247. should_throw = false;
  4248. {
  4249. Client cli(HOST, port);
  4250. auto res = cli.Get("/hi");
  4251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4252. EXPECT_EQ(StatusCode::OK_200, res->status);
  4253. EXPECT_EQ("hi", res->body);
  4254. }
  4255. }
  4256. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4257. // The guard reports the caught exception through the error logger, which is
  4258. // a user callback too. A logger that throws has to be contained as well, or
  4259. // the process would terminate from inside the catch.
  4260. Server svr;
  4261. svr.new_task_queue = [] { return new ThreadPool(1); };
  4262. std::atomic<int> reported{0};
  4263. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4264. if (err == Error::UserCallbackException) {
  4265. reported++;
  4266. throw std::runtime_error("from the error logger");
  4267. }
  4268. });
  4269. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4270. res.set_content_provider(
  4271. 1024, "text/plain",
  4272. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4273. sink.write("hello", 5);
  4274. throw std::runtime_error("from the content provider");
  4275. });
  4276. });
  4277. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4278. res.set_content("ok", "text/plain");
  4279. });
  4280. auto port = svr.bind_to_any_port(HOST);
  4281. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4282. auto se = detail::scope_exit([&] {
  4283. svr.stop();
  4284. listen_thread.join();
  4285. ASSERT_FALSE(svr.is_running());
  4286. });
  4287. svr.wait_until_ready();
  4288. {
  4289. Client cli(HOST, port);
  4290. cli.set_read_timeout(5, 0);
  4291. EXPECT_FALSE(cli.Get("/throw"));
  4292. }
  4293. EXPECT_TRUE(svr.is_running());
  4294. EXPECT_EQ(1, reported.load());
  4295. {
  4296. Client cli(HOST, port);
  4297. auto res = cli.Get("/ok");
  4298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4299. EXPECT_EQ(StatusCode::OK_200, res->status);
  4300. EXPECT_EQ("ok", res->body);
  4301. }
  4302. }
  4303. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4304. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4305. // so the exception unwinds through the ws::WebSocket object on its way to
  4306. // the guard. None of the HTTP cases above cross that.
  4307. Server svr;
  4308. svr.new_task_queue = [] { return new ThreadPool(1); };
  4309. std::atomic<int> reported{0};
  4310. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4311. if (err == Error::UserCallbackException) { reported++; }
  4312. });
  4313. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4314. throw std::runtime_error("from the WebSocket handler");
  4315. });
  4316. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4317. res.set_content("ok", "text/plain");
  4318. });
  4319. auto port = svr.bind_to_any_port(HOST);
  4320. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. listen_thread.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. svr.wait_until_ready();
  4327. {
  4328. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4329. "/ws");
  4330. auto res = client.connect();
  4331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4332. // The server dropped the connection instead of dying.
  4333. std::string msg;
  4334. EXPECT_FALSE(client.read(msg));
  4335. client.close();
  4336. }
  4337. EXPECT_TRUE(svr.is_running());
  4338. EXPECT_EQ(1, reported.load());
  4339. {
  4340. Client cli(HOST, port);
  4341. auto res = cli.Get("/ok");
  4342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. EXPECT_EQ("ok", res->body);
  4345. }
  4346. }
  4347. #ifdef CPPHTTPLIB_SSL_ENABLED
  4348. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4349. // SSLServer::process_and_close_socket() is a separate overload with its own
  4350. // guard, so it is exercised on its own.
  4351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4352. ASSERT_TRUE(svr.is_valid());
  4353. svr.new_task_queue = [] { return new ThreadPool(1); };
  4354. std::atomic<int> reported{0};
  4355. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4356. if (err == Error::UserCallbackException) { reported++; }
  4357. });
  4358. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4359. res.set_content_provider(
  4360. 1024, "text/plain",
  4361. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4362. sink.write("hello", 5);
  4363. throw std::runtime_error("from the content provider");
  4364. });
  4365. });
  4366. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4367. res.set_content("ok", "text/plain");
  4368. });
  4369. auto port = svr.bind_to_any_port(HOST);
  4370. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4371. auto se = detail::scope_exit([&] {
  4372. svr.stop();
  4373. listen_thread.join();
  4374. ASSERT_FALSE(svr.is_running());
  4375. });
  4376. svr.wait_until_ready();
  4377. {
  4378. SSLClient cli(HOST, port);
  4379. cli.enable_server_certificate_verification(false);
  4380. cli.set_read_timeout(5, 0);
  4381. EXPECT_FALSE(cli.Get("/throw"));
  4382. }
  4383. EXPECT_TRUE(svr.is_running());
  4384. EXPECT_EQ(1, reported.load());
  4385. {
  4386. SSLClient cli(HOST, port);
  4387. cli.enable_server_certificate_verification(false);
  4388. auto res = cli.Get("/ok");
  4389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. EXPECT_EQ("ok", res->body);
  4392. }
  4393. }
  4394. #endif
  4395. #endif
  4396. TEST(NoContentTest, ContentLength) {
  4397. Server svr;
  4398. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4399. res.status = StatusCode::NoContent_204;
  4400. });
  4401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4402. auto se = detail::scope_exit([&] {
  4403. svr.stop();
  4404. thread.join();
  4405. ASSERT_FALSE(svr.is_running());
  4406. });
  4407. svr.wait_until_ready();
  4408. {
  4409. Client cli(HOST, PORT);
  4410. auto res = cli.Get("/hi");
  4411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4412. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4413. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4414. }
  4415. }
  4416. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4417. #ifdef CPPHTTPLIB_SSL_ENABLED
  4418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4419. ASSERT_TRUE(svr.is_valid());
  4420. #else
  4421. Server svr;
  4422. #endif
  4423. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4424. if (req.path == "/routing_handler") {
  4425. res.set_header("PRE_ROUTING", "on");
  4426. res.set_content("Routing Handler", "text/plain");
  4427. return httplib::Server::HandlerResponse::Handled;
  4428. }
  4429. return httplib::Server::HandlerResponse::Unhandled;
  4430. });
  4431. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4432. res.set_content("Error", "text/html");
  4433. });
  4434. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4435. if (req.path == "/routing_handler") {
  4436. res.set_header("POST_ROUTING", "on");
  4437. }
  4438. });
  4439. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4440. res.set_content("Hello World!\n", "text/plain");
  4441. });
  4442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4443. auto se = detail::scope_exit([&] {
  4444. svr.stop();
  4445. thread.join();
  4446. ASSERT_FALSE(svr.is_running());
  4447. });
  4448. svr.wait_until_ready();
  4449. {
  4450. #ifdef CPPHTTPLIB_SSL_ENABLED
  4451. SSLClient cli(HOST, PORT);
  4452. cli.enable_server_certificate_verification(false);
  4453. #else
  4454. Client cli(HOST, PORT);
  4455. #endif
  4456. auto res = cli.Get("/routing_handler");
  4457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4458. EXPECT_EQ(StatusCode::OK_200, res->status);
  4459. EXPECT_EQ("Routing Handler", res->body);
  4460. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4461. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4462. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4463. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4464. }
  4465. {
  4466. #ifdef CPPHTTPLIB_SSL_ENABLED
  4467. SSLClient cli(HOST, PORT);
  4468. cli.enable_server_certificate_verification(false);
  4469. #else
  4470. Client cli(HOST, PORT);
  4471. #endif
  4472. auto res = cli.Get("/hi");
  4473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ("Hello World!\n", res->body);
  4476. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4477. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4478. }
  4479. {
  4480. #ifdef CPPHTTPLIB_SSL_ENABLED
  4481. SSLClient cli(HOST, PORT);
  4482. cli.enable_server_certificate_verification(false);
  4483. #else
  4484. Client cli(HOST, PORT);
  4485. #endif
  4486. auto res = cli.Get("/aaa");
  4487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4489. EXPECT_EQ("Error", res->body);
  4490. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4491. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4492. }
  4493. }
  4494. TEST(RequestHandlerTest, PreRequestHandler) {
  4495. auto route_path = "/user/:user";
  4496. Server svr;
  4497. svr.Get("/hi", [](const Request &, Response &res) {
  4498. res.set_content("hi", "text/plain");
  4499. });
  4500. svr.Get(route_path, [](const Request &req, Response &res) {
  4501. res.set_content(req.path_params.at("user"), "text/plain");
  4502. });
  4503. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4504. if (req.matched_route == route_path) {
  4505. auto user = req.path_params.at("user");
  4506. if (user != "john") {
  4507. res.status = StatusCode::Forbidden_403;
  4508. res.set_content("error", "text/html");
  4509. return Server::HandlerResponse::Handled;
  4510. }
  4511. }
  4512. return Server::HandlerResponse::Unhandled;
  4513. });
  4514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4515. auto se = detail::scope_exit([&] {
  4516. svr.stop();
  4517. thread.join();
  4518. ASSERT_FALSE(svr.is_running());
  4519. });
  4520. svr.wait_until_ready();
  4521. Client cli(HOST, PORT);
  4522. {
  4523. auto res = cli.Get("/hi");
  4524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4525. EXPECT_EQ(StatusCode::OK_200, res->status);
  4526. EXPECT_EQ("hi", res->body);
  4527. }
  4528. {
  4529. auto res = cli.Get("/user/john");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("john", res->body);
  4533. }
  4534. {
  4535. auto res = cli.Get("/user/invalid-user");
  4536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4537. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4538. EXPECT_EQ("error", res->body);
  4539. }
  4540. }
  4541. // The pre-request handler must run before the request body is read, so a
  4542. // rejected request never forces the server to buffer a (potentially large)
  4543. // body. Here the posted body is larger than the payload limit: if the body
  4544. // were read first the server would answer 413, but because the pre-request
  4545. // handler runs first it answers 403 and the body is never read.
  4546. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4547. Server svr;
  4548. svr.set_payload_max_length(8);
  4549. auto handler_ran = false;
  4550. svr.Post("/reject", [&](const Request &req, Response &res) {
  4551. handler_ran = true;
  4552. res.set_content(req.body, "text/plain");
  4553. });
  4554. svr.Post("/accept", [](const Request &req, Response &res) {
  4555. res.set_content(req.body, "text/plain");
  4556. });
  4557. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4558. if (req.matched_route == "/reject") {
  4559. res.status = StatusCode::Forbidden_403;
  4560. res.set_content("denied", "text/plain");
  4561. return Server::HandlerResponse::Handled;
  4562. }
  4563. return Server::HandlerResponse::Unhandled;
  4564. });
  4565. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4566. auto se = detail::scope_exit([&] {
  4567. svr.stop();
  4568. thread.join();
  4569. ASSERT_FALSE(svr.is_running());
  4570. });
  4571. svr.wait_until_ready();
  4572. Client cli(HOST, PORT);
  4573. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4574. // rejects with 403 before the body is read, so 413 is never reached.
  4575. {
  4576. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4579. EXPECT_EQ("denied", res->body);
  4580. EXPECT_FALSE(handler_ran);
  4581. }
  4582. // An approved route still reads the body and enforces the payload limit.
  4583. {
  4584. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4587. }
  4588. }
  4589. TEST(UserDataTest, BasicOperations) {
  4590. httplib::UserData ud;
  4591. // Initially empty
  4592. EXPECT_FALSE(ud.has("key"));
  4593. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4594. // set and get
  4595. ud.set("key", 42);
  4596. EXPECT_TRUE(ud.has("key"));
  4597. auto *p = ud.get<int>("key");
  4598. ASSERT_NE(nullptr, p);
  4599. EXPECT_EQ(42, *p);
  4600. // Type mismatch → nullptr
  4601. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4602. // Overwrite with different type
  4603. ud.set("key", std::string("hello"));
  4604. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4605. auto *s = ud.get<std::string>("key");
  4606. ASSERT_NE(nullptr, s);
  4607. EXPECT_EQ("hello", *s);
  4608. // erase
  4609. ud.erase("key");
  4610. EXPECT_FALSE(ud.has("key"));
  4611. // clear
  4612. ud.set("a", 1);
  4613. ud.set("b", 2);
  4614. ud.clear();
  4615. EXPECT_FALSE(ud.has("a"));
  4616. EXPECT_FALSE(ud.has("b"));
  4617. }
  4618. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4619. struct AuthCtx {
  4620. std::string user_id;
  4621. };
  4622. Server svr;
  4623. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4624. res.user_data.set("auth", AuthCtx{"alice"});
  4625. return Server::HandlerResponse::Unhandled;
  4626. });
  4627. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4628. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4629. ASSERT_NE(nullptr, ctx);
  4630. res.set_content("Hello " + ctx->user_id, "text/plain");
  4631. });
  4632. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4633. auto se = detail::scope_exit([&] {
  4634. svr.stop();
  4635. thread.join();
  4636. ASSERT_FALSE(svr.is_running());
  4637. });
  4638. svr.wait_until_ready();
  4639. Client cli(HOST, PORT);
  4640. auto res = cli.Get("/me");
  4641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4642. EXPECT_EQ(StatusCode::OK_200, res->status);
  4643. EXPECT_EQ("Hello alice", res->body);
  4644. }
  4645. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4646. struct RoleCtx {
  4647. std::string role;
  4648. };
  4649. Server svr;
  4650. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4651. res.user_data.set("role", RoleCtx{"admin"});
  4652. return Server::HandlerResponse::Unhandled;
  4653. });
  4654. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4655. auto *ctx = res.user_data.get<RoleCtx>("role");
  4656. ASSERT_NE(nullptr, ctx);
  4657. res.set_content(ctx->role, "text/plain");
  4658. });
  4659. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. thread.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. Client cli(HOST, PORT);
  4667. auto res = cli.Get("/role");
  4668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4669. EXPECT_EQ(StatusCode::OK_200, res->status);
  4670. EXPECT_EQ("admin", res->body);
  4671. }
  4672. TEST(InvalidFormatTest, StatusCode) {
  4673. Server svr;
  4674. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4675. res.set_content("Hello World!\n", "text/plain");
  4676. res.status = 9999; // Status should be a three-digit code...
  4677. });
  4678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4679. auto se = detail::scope_exit([&] {
  4680. svr.stop();
  4681. thread.join();
  4682. ASSERT_FALSE(svr.is_running());
  4683. });
  4684. svr.wait_until_ready();
  4685. {
  4686. Client cli(HOST, PORT);
  4687. auto res = cli.Get("/hi");
  4688. ASSERT_FALSE(res);
  4689. }
  4690. }
  4691. TEST(URLFragmentTest, WithFragment) {
  4692. Server svr;
  4693. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4694. EXPECT_TRUE(req.target == "/hi");
  4695. });
  4696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4697. auto se = detail::scope_exit([&] {
  4698. svr.stop();
  4699. thread.join();
  4700. ASSERT_FALSE(svr.is_running());
  4701. });
  4702. svr.wait_until_ready();
  4703. {
  4704. Client cli(HOST, PORT);
  4705. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4706. EXPECT_TRUE(res);
  4707. EXPECT_EQ(StatusCode::OK_200, res->status);
  4708. res = cli.Get("/hi%23key1=val1=key2=val2");
  4709. EXPECT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4711. }
  4712. }
  4713. TEST(HeaderWriter, SetHeaderWriter) {
  4714. Server svr;
  4715. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4716. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4717. return detail::write_headers(strm, hdrs);
  4718. });
  4719. svr.Get("/hi", [](const Request &req, Response &res) {
  4720. auto it = req.headers.find("CustomClientHeader");
  4721. EXPECT_TRUE(it != req.headers.end());
  4722. EXPECT_EQ(it->second, "CustomClientValue");
  4723. res.set_content("Hello World!\n", "text/plain");
  4724. });
  4725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4726. auto se = detail::scope_exit([&] {
  4727. svr.stop();
  4728. thread.join();
  4729. ASSERT_FALSE(svr.is_running());
  4730. });
  4731. svr.wait_until_ready();
  4732. {
  4733. Client cli(HOST, PORT);
  4734. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4735. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4736. return detail::write_headers(strm, hdrs);
  4737. });
  4738. auto res = cli.Get("/hi");
  4739. EXPECT_TRUE(res);
  4740. EXPECT_EQ(StatusCode::OK_200, res->status);
  4741. auto it = res->headers.find("CustomServerHeader");
  4742. EXPECT_TRUE(it != res->headers.end());
  4743. EXPECT_EQ(it->second, "CustomServerValue");
  4744. }
  4745. }
  4746. class ServerTest : public ::testing::Test {
  4747. protected:
  4748. ServerTest()
  4749. : cli_(HOST, PORT)
  4750. #ifdef CPPHTTPLIB_SSL_ENABLED
  4751. ,
  4752. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4753. #endif
  4754. {
  4755. #ifdef CPPHTTPLIB_SSL_ENABLED
  4756. cli_.enable_server_certificate_verification(false);
  4757. #endif
  4758. // Allow LARGE_DATA (100MB) responses
  4759. cli_.set_payload_max_length(200 * 1024 * 1024);
  4760. }
  4761. virtual void SetUp() {
  4762. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4763. svr_.set_payload_max_length(200 * 1024 * 1024);
  4764. svr_.set_mount_point("/", "./www");
  4765. svr_.set_mount_point("/mount", "./www2");
  4766. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4767. svr_.Get("/hi",
  4768. [&](const Request & /*req*/, Response &res) {
  4769. res.set_content("Hello World!", "text/plain");
  4770. })
  4771. .Get("/file_content",
  4772. [&](const Request & /*req*/, Response &res) {
  4773. res.set_file_content("./www/dir/test.html");
  4774. })
  4775. .Get("/file_content_with_content_type",
  4776. [&](const Request & /*req*/, Response &res) {
  4777. res.set_file_content("./www/file", "text/plain");
  4778. })
  4779. .Get("/invalid_file_content",
  4780. [&](const Request & /*req*/, Response &res) {
  4781. res.set_file_content("./www/dir/invalid_file_path");
  4782. })
  4783. .Get("/http_response_splitting",
  4784. [&](const Request & /*req*/, Response &res) {
  4785. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4786. EXPECT_EQ(0U, res.headers.size());
  4787. EXPECT_FALSE(res.has_header("a"));
  4788. res.set_header("a", "1\nSet-Cookie: a=1");
  4789. EXPECT_EQ(0U, res.headers.size());
  4790. EXPECT_FALSE(res.has_header("a"));
  4791. res.set_header("a", "1\rSet-Cookie: a=1");
  4792. EXPECT_EQ(0U, res.headers.size());
  4793. EXPECT_FALSE(res.has_header("a"));
  4794. res.set_header("a\r\nb", "0");
  4795. EXPECT_EQ(0U, res.headers.size());
  4796. EXPECT_FALSE(res.has_header("a"));
  4797. res.set_header("a\rb", "0");
  4798. EXPECT_EQ(0U, res.headers.size());
  4799. EXPECT_FALSE(res.has_header("a"));
  4800. res.set_header("a\nb", "0");
  4801. EXPECT_EQ(0U, res.headers.size());
  4802. EXPECT_FALSE(res.has_header("a"));
  4803. res.set_redirect("1\r\nSet-Cookie: a=1");
  4804. EXPECT_EQ(0U, res.headers.size());
  4805. EXPECT_FALSE(res.has_header("Location"));
  4806. })
  4807. .Get("/slow",
  4808. [&](const Request & /*req*/, Response &res) {
  4809. std::this_thread::sleep_for(std::chrono::seconds(4));
  4810. res.set_content("slow", "text/plain");
  4811. })
  4812. #if 0
  4813. .Post("/slowpost",
  4814. [&](const Request & /*req*/, Response &res) {
  4815. std::this_thread::sleep_for(std::chrono::seconds(2));
  4816. res.set_content("slow", "text/plain");
  4817. })
  4818. #endif
  4819. .Get("/remote_addr",
  4820. [&](const Request &req, Response &res) {
  4821. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4822. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4823. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4824. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4825. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4826. #endif
  4827. res.set_content(req.remote_addr, "text/plain");
  4828. })
  4829. .Get("/local_addr",
  4830. [&](const Request &req, Response &res) {
  4831. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4832. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4833. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4834. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4835. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4836. #endif
  4837. auto local_addr = req.local_addr;
  4838. auto local_port = std::to_string(req.local_port);
  4839. res.set_content(local_addr.append(":").append(local_port),
  4840. "text/plain");
  4841. })
  4842. .Get("/endwith%",
  4843. [&](const Request & /*req*/, Response &res) {
  4844. res.set_content("Hello World!", "text/plain");
  4845. })
  4846. .Get("/a\\+\\+b",
  4847. [&](const Request &req, Response &res) {
  4848. ASSERT_TRUE(req.has_param("a +b"));
  4849. auto val = req.get_param_value("a +b");
  4850. res.set_content(val, "text/plain");
  4851. })
  4852. .Get("/", [&](const Request & /*req*/,
  4853. Response &res) { res.set_redirect("/hi"); })
  4854. .Post("/1",
  4855. [](const Request & /*req*/, Response &res) {
  4856. res.set_redirect("/2", StatusCode::SeeOther_303);
  4857. })
  4858. .Get("/2",
  4859. [](const Request & /*req*/, Response &res) {
  4860. res.set_content("redirected.", "text/plain");
  4861. res.status = StatusCode::OK_200;
  4862. })
  4863. .Post("/person",
  4864. [&](const Request &req, Response &res) {
  4865. if (req.has_param("name") && req.has_param("note")) {
  4866. persons_[req.get_param_value("name")] =
  4867. req.get_param_value("note");
  4868. } else {
  4869. res.status = StatusCode::BadRequest_400;
  4870. }
  4871. })
  4872. .Put("/person",
  4873. [&](const Request &req, Response &res) {
  4874. if (req.has_param("name") && req.has_param("note")) {
  4875. persons_[req.get_param_value("name")] =
  4876. req.get_param_value("note");
  4877. } else {
  4878. res.status = StatusCode::BadRequest_400;
  4879. }
  4880. })
  4881. .Get("/person/(.*)",
  4882. [&](const Request &req, Response &res) {
  4883. string name = req.matches[1];
  4884. if (persons_.find(name) != persons_.end()) {
  4885. auto note = persons_[name];
  4886. res.set_content(note, "text/plain");
  4887. } else {
  4888. res.status = StatusCode::NotFound_404;
  4889. }
  4890. })
  4891. .Delete("/person",
  4892. [&](const Request &req, Response &res) {
  4893. if (req.has_param("name")) {
  4894. string name = req.get_param_value("name");
  4895. if (persons_.find(name) != persons_.end()) {
  4896. persons_.erase(name);
  4897. res.set_content("DELETED", "text/plain");
  4898. } else {
  4899. res.status = StatusCode::NotFound_404;
  4900. }
  4901. } else {
  4902. res.status = StatusCode::BadRequest_400;
  4903. }
  4904. })
  4905. .Post("/x-www-form-urlencoded-json",
  4906. [&](const Request &req, Response &res) {
  4907. auto json = req.get_param_value("json");
  4908. ASSERT_EQ(JSON_DATA, json);
  4909. res.set_content(json, "appliation/json");
  4910. res.status = StatusCode::OK_200;
  4911. })
  4912. .Get("/streamed-chunked",
  4913. [&](const Request & /*req*/, Response &res) {
  4914. res.set_chunked_content_provider(
  4915. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4916. sink.os << "123";
  4917. sink.os << "456";
  4918. sink.os << "789";
  4919. sink.done();
  4920. return true;
  4921. });
  4922. })
  4923. .Get("/streamed-chunked-with-prohibited-trailer",
  4924. [&](const Request & /*req*/, Response &res) {
  4925. auto i = new int(0);
  4926. // Declare both a prohibited trailer (Content-Length) and an
  4927. // allowed one
  4928. res.set_header("Trailer", "Content-Length, X-Allowed");
  4929. res.set_chunked_content_provider(
  4930. "text/plain",
  4931. [i](size_t /*offset*/, DataSink &sink) {
  4932. switch (*i) {
  4933. case 0: sink.os << "123"; break;
  4934. case 1: sink.os << "456"; break;
  4935. case 2: sink.os << "789"; break;
  4936. case 3: {
  4937. sink.done_with_trailer(
  4938. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4939. } break;
  4940. }
  4941. (*i)++;
  4942. return true;
  4943. },
  4944. [i](bool success) {
  4945. EXPECT_TRUE(success);
  4946. delete i;
  4947. });
  4948. })
  4949. .Get("/streamed-chunked2",
  4950. [&](const Request & /*req*/, Response &res) {
  4951. auto i = new int(0);
  4952. res.set_chunked_content_provider(
  4953. "text/plain",
  4954. [i](size_t /*offset*/, DataSink &sink) {
  4955. switch (*i) {
  4956. case 0: sink.os << "123"; break;
  4957. case 1: sink.os << "456"; break;
  4958. case 2: sink.os << "789"; break;
  4959. case 3: sink.done(); break;
  4960. }
  4961. (*i)++;
  4962. return true;
  4963. },
  4964. [i](bool success) {
  4965. EXPECT_TRUE(success);
  4966. delete i;
  4967. });
  4968. })
  4969. .Get("/streamed-chunked-with-trailer",
  4970. [&](const Request & /*req*/, Response &res) {
  4971. auto i = new int(0);
  4972. res.set_header("Trailer", "Dummy1, Dummy2");
  4973. res.set_chunked_content_provider(
  4974. "text/plain",
  4975. [i](size_t /*offset*/, DataSink &sink) {
  4976. switch (*i) {
  4977. case 0: sink.os << "123"; break;
  4978. case 1: sink.os << "456"; break;
  4979. case 2: sink.os << "789"; break;
  4980. case 3: {
  4981. sink.done_with_trailer(
  4982. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4983. } break;
  4984. }
  4985. (*i)++;
  4986. return true;
  4987. },
  4988. [i](bool success) {
  4989. EXPECT_TRUE(success);
  4990. delete i;
  4991. });
  4992. })
  4993. .Get("/streamed",
  4994. [&](const Request & /*req*/, Response &res) {
  4995. res.set_content_provider(
  4996. 6, "text/plain",
  4997. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4998. sink.os << (offset < 3 ? "a" : "b");
  4999. return true;
  5000. });
  5001. })
  5002. .Get("/streamed-without-length",
  5003. [&](const Request & /*req*/, Response &res) {
  5004. auto data = new std::string("abcdefg");
  5005. res.set_content_provider(
  5006. "text/plain",
  5007. [data](size_t offset, DataSink &sink) {
  5008. if (offset < data->size()) {
  5009. sink.os << data->substr(offset);
  5010. }
  5011. sink.done();
  5012. return true;
  5013. },
  5014. [data](bool success) {
  5015. EXPECT_TRUE(success);
  5016. delete data;
  5017. });
  5018. })
  5019. .Get("/streamed-with-range",
  5020. [&](const Request &req, Response &res) {
  5021. auto data = new std::string("abcdefg");
  5022. // An explicit status keeps the server from picking the 206 it
  5023. // would otherwise choose for a ranged request, so the response
  5024. // is not a partial representation.
  5025. auto status = req.get_param_value("status");
  5026. if (status == "200") {
  5027. res.status = StatusCode::OK_200;
  5028. } else if (status == "403") {
  5029. res.status = StatusCode::Forbidden_403;
  5030. }
  5031. res.set_content_provider(
  5032. data->size(), "text/plain",
  5033. [data](size_t offset, size_t length, DataSink &sink) {
  5034. size_t DATA_CHUNK_SIZE = 4;
  5035. const auto &d = *data;
  5036. auto out_len =
  5037. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5038. auto ret =
  5039. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5040. EXPECT_TRUE(ret);
  5041. return true;
  5042. },
  5043. [data, &req](bool success) {
  5044. EXPECT_EQ(success, !req.has_param("error"));
  5045. delete data;
  5046. });
  5047. })
  5048. .Get("/streamed-cancel",
  5049. [&](const Request & /*req*/, Response &res) {
  5050. res.set_content_provider(
  5051. size_t(-1), "text/plain",
  5052. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5053. sink.os << "data_chunk";
  5054. return true;
  5055. });
  5056. })
  5057. .Get("/regex-with-delimiter",
  5058. [&](const Request &req, Response & /*res*/) {
  5059. ASSERT_TRUE(req.has_param("key"));
  5060. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5061. })
  5062. .Get("/with-range",
  5063. [&](const Request & /*req*/, Response &res) {
  5064. res.set_content("abcdefg", "text/plain");
  5065. })
  5066. .Get("/test-start-time",
  5067. [&](const Request &req, Response & /*res*/) {
  5068. EXPECT_NE(req.start_time_,
  5069. std::chrono::steady_clock::time_point::min());
  5070. })
  5071. .Get("/with-range-customized-response",
  5072. [&](const Request & /*req*/, Response &res) {
  5073. res.status = StatusCode::BadRequest_400;
  5074. res.set_content(JSON_DATA, "application/json");
  5075. })
  5076. .Post("/chunked",
  5077. [&](const Request &req, Response & /*res*/) {
  5078. EXPECT_EQ(req.body, "dechunked post body");
  5079. })
  5080. .Post("/large-chunked",
  5081. [&](const Request &req, Response & /*res*/) {
  5082. std::string expected(6 * 30 * 1024u, 'a');
  5083. EXPECT_EQ(req.body, expected);
  5084. })
  5085. .Post("/multipart",
  5086. [&](const Request &req, Response & /*res*/) {
  5087. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5088. req.form.get_field_count("text2") +
  5089. req.form.get_field_count("file3") +
  5090. req.form.get_field_count("file4"));
  5091. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5092. req.form.get_file_count("file2"));
  5093. ASSERT_TRUE(!req.form.has_file("???"));
  5094. ASSERT_TRUE(!req.form.has_field("???"));
  5095. ASSERT_TRUE(req.body.empty());
  5096. {
  5097. const auto &text = req.form.get_field("text1");
  5098. EXPECT_EQ("text default", text);
  5099. }
  5100. {
  5101. const auto &text = req.form.get_field("text2");
  5102. EXPECT_EQ("aωb", text);
  5103. }
  5104. {
  5105. const auto &file = req.form.get_file("file1");
  5106. EXPECT_EQ("hello.txt", file.filename);
  5107. EXPECT_EQ("text/plain", file.content_type);
  5108. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5109. }
  5110. {
  5111. const auto &file = req.form.get_file("file2");
  5112. EXPECT_EQ("world.json", file.filename);
  5113. EXPECT_EQ("application/json", file.content_type);
  5114. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5115. }
  5116. {
  5117. const auto &text = req.form.get_field("file3");
  5118. EXPECT_EQ(0u, text.size());
  5119. }
  5120. {
  5121. const auto &text = req.form.get_field("file4");
  5122. EXPECT_EQ(0u, text.size());
  5123. }
  5124. })
  5125. .Post("/multipart/multi_file_values",
  5126. [&](const Request &req, Response & /*res*/) {
  5127. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5128. req.form.get_field_count("multi_text1"));
  5129. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5130. ASSERT_TRUE(!req.form.has_file("???"));
  5131. ASSERT_TRUE(!req.form.has_field("???"));
  5132. ASSERT_TRUE(req.body.empty());
  5133. {
  5134. const auto &text = req.form.get_field("text");
  5135. EXPECT_EQ("default text", text);
  5136. }
  5137. {
  5138. const auto &text1_values = req.form.get_fields("multi_text1");
  5139. EXPECT_EQ(2u, text1_values.size());
  5140. EXPECT_EQ("aaaaa", text1_values[0]);
  5141. EXPECT_EQ("bbbbb", text1_values[1]);
  5142. }
  5143. {
  5144. const auto &file1_values = req.form.get_files("multi_file1");
  5145. EXPECT_EQ(2u, file1_values.size());
  5146. auto file1 = file1_values[0];
  5147. EXPECT_EQ(file1.filename, "hello.txt");
  5148. EXPECT_EQ(file1.content_type, "text/plain");
  5149. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5150. auto file2 = file1_values[1];
  5151. EXPECT_EQ(file2.filename, "world.json");
  5152. EXPECT_EQ(file2.content_type, "application/json");
  5153. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5154. }
  5155. })
  5156. .Post("/empty",
  5157. [&](const Request &req, Response &res) {
  5158. EXPECT_EQ(req.body, "");
  5159. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5160. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5161. res.set_content("empty", "text/plain");
  5162. })
  5163. .Post("/empty-no-content-type",
  5164. [&](const Request &req, Response &res) {
  5165. EXPECT_EQ(req.body, "");
  5166. EXPECT_FALSE(req.has_header("Content-Type"));
  5167. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5168. res.set_content("empty-no-content-type", "text/plain");
  5169. })
  5170. .Post("/path-only",
  5171. [&](const Request &req, Response &res) {
  5172. EXPECT_EQ(req.body, "");
  5173. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5174. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5175. res.set_content("path-only", "text/plain");
  5176. })
  5177. .Post("/path-headers-only",
  5178. [&](const Request &req, Response &res) {
  5179. EXPECT_EQ(req.body, "");
  5180. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5181. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5182. EXPECT_EQ("world", req.get_header_value("hello"));
  5183. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5184. res.set_content("path-headers-only", "text/plain");
  5185. })
  5186. .Post("/post-large",
  5187. [&](const Request &req, Response &res) {
  5188. EXPECT_EQ(req.body, LARGE_DATA);
  5189. res.set_content(req.body, "text/plain");
  5190. })
  5191. .Post("/post-loopback",
  5192. [&](const Request &, Response &res,
  5193. ContentReader const &content_reader) {
  5194. std::string body;
  5195. content_reader([&](const char *data, size_t data_length) {
  5196. body.append(data, data_length);
  5197. return true;
  5198. });
  5199. res.set_content(body, "text/plain");
  5200. })
  5201. .Put("/put-loopback",
  5202. [&](const Request &, Response &res,
  5203. ContentReader const &content_reader) {
  5204. std::string body;
  5205. content_reader([&](const char *data, size_t data_length) {
  5206. body.append(data, data_length);
  5207. return true;
  5208. });
  5209. res.set_content(body, "text/plain");
  5210. })
  5211. .Patch("/patch-loopback",
  5212. [&](const Request &, Response &res,
  5213. ContentReader const &content_reader) {
  5214. std::string body;
  5215. content_reader([&](const char *data, size_t data_length) {
  5216. body.append(data, data_length);
  5217. return true;
  5218. });
  5219. res.set_content(body, "text/plain");
  5220. })
  5221. .Put("/empty-no-content-type",
  5222. [&](const Request &req, Response &res) {
  5223. EXPECT_EQ(req.body, "");
  5224. EXPECT_FALSE(req.has_header("Content-Type"));
  5225. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5226. res.set_content("empty-no-content-type", "text/plain");
  5227. })
  5228. .Put("/put",
  5229. [&](const Request &req, Response &res) {
  5230. EXPECT_EQ(req.body, "PUT");
  5231. res.set_content(req.body, "text/plain");
  5232. })
  5233. .Put("/put-large",
  5234. [&](const Request &req, Response &res) {
  5235. EXPECT_EQ(req.body, LARGE_DATA);
  5236. res.set_content(req.body, "text/plain");
  5237. })
  5238. .Patch("/patch",
  5239. [&](const Request &req, Response &res) {
  5240. EXPECT_EQ(req.body, "PATCH");
  5241. res.set_content(req.body, "text/plain");
  5242. })
  5243. .Delete("/delete",
  5244. [&](const Request & /*req*/, Response &res) {
  5245. res.set_content("DELETE", "text/plain");
  5246. })
  5247. .Delete("/delete-body",
  5248. [&](const Request &req, Response &res) {
  5249. EXPECT_EQ(req.body, "content");
  5250. res.set_content(req.body, "text/plain");
  5251. })
  5252. .Options(R"(\*)",
  5253. [&](const Request & /*req*/, Response &res) {
  5254. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5255. })
  5256. .CustomRoute("PROPFIND", "/dav/:id",
  5257. [&](const Request &req, Response &res) {
  5258. res.set_header("x-body-size",
  5259. std::to_string(req.body.size()));
  5260. res.set_header("x-matched-route", req.matched_route);
  5261. res.set_header("x-dav-id", req.path_params.at("id"));
  5262. res.status = StatusCode::MultiStatus_207;
  5263. res.set_content(req.body, "application/xml");
  5264. })
  5265. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5266. [&](const Request &req, Response &res) {
  5267. res.set_header("x-dav-match", req.matches[1]);
  5268. res.status = StatusCode::MultiStatus_207;
  5269. })
  5270. .CustomRoute("MKCOL", "/dav-mkcol",
  5271. [&](const Request &req, Response &res) {
  5272. EXPECT_TRUE(req.body.empty());
  5273. res.status = StatusCode::Created_201;
  5274. })
  5275. .CustomRoute(
  5276. "REPORT", "/dav-report",
  5277. [&](const Request & /*req*/, Response &res,
  5278. const ContentReader &content_reader) {
  5279. std::string body;
  5280. content_reader([&](const char *data, size_t data_length) {
  5281. body.append(data, data_length);
  5282. return true;
  5283. });
  5284. res.set_header("x-body-size", std::to_string(body.size()));
  5285. res.status = StatusCode::MultiStatus_207;
  5286. res.set_content(body, "application/xml");
  5287. })
  5288. .Get("/request-target",
  5289. [&](const Request &req, Response & /*res*/) {
  5290. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5291. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5292. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5293. })
  5294. .Get("/long-query-value",
  5295. [&](const Request &req, Response & /*res*/) {
  5296. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5297. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5298. })
  5299. .Get("/too-long-query-value",
  5300. [&](const Request &req, Response & /*res*/) {
  5301. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5302. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5303. })
  5304. .Get("/array-param",
  5305. [&](const Request &req, Response & /*res*/) {
  5306. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5307. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5308. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5309. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5310. })
  5311. .Get("/array-param-values",
  5312. [&](const Request &req, Response & /*res*/) {
  5313. auto values = req.get_param_values("array");
  5314. EXPECT_EQ(3u, values.size());
  5315. EXPECT_EQ("value1", values[0]);
  5316. EXPECT_EQ("value2", values[1]);
  5317. EXPECT_EQ("value3", values[2]);
  5318. auto empty = req.get_param_values("nonexistent");
  5319. EXPECT_TRUE(empty.empty());
  5320. })
  5321. .Post("/validate-no-multiple-headers",
  5322. [&](const Request &req, Response & /*res*/) {
  5323. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5324. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5325. })
  5326. .Post("/content_receiver",
  5327. [&](const Request &req, Response &res,
  5328. const ContentReader &content_reader) {
  5329. if (req.is_multipart_form_data()) {
  5330. std::vector<FormData> items;
  5331. content_reader(
  5332. [&](const FormData &file) {
  5333. items.push_back(file);
  5334. return true;
  5335. },
  5336. [&](const char *data, size_t data_length) {
  5337. items.back().content.append(data, data_length);
  5338. return true;
  5339. });
  5340. EXPECT_EQ(5u, items.size());
  5341. {
  5342. const auto &file = get_file_value(items, "text1");
  5343. EXPECT_TRUE(file.filename.empty());
  5344. EXPECT_EQ("text default", file.content);
  5345. }
  5346. {
  5347. const auto &file = get_file_value(items, "text2");
  5348. EXPECT_TRUE(file.filename.empty());
  5349. EXPECT_EQ("aωb", file.content);
  5350. }
  5351. {
  5352. const auto &file = get_file_value(items, "file1");
  5353. EXPECT_EQ("hello.txt", file.filename);
  5354. EXPECT_EQ("text/plain", file.content_type);
  5355. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5356. }
  5357. {
  5358. const auto &file = get_file_value(items, "file2");
  5359. EXPECT_EQ("world.json", file.filename);
  5360. EXPECT_EQ("application/json", file.content_type);
  5361. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5362. }
  5363. {
  5364. const auto &file = get_file_value(items, "file3");
  5365. EXPECT_TRUE(file.filename.empty());
  5366. EXPECT_EQ("application/octet-stream", file.content_type);
  5367. EXPECT_EQ(0u, file.content.size());
  5368. }
  5369. } else {
  5370. std::string body;
  5371. content_reader([&](const char *data, size_t data_length) {
  5372. EXPECT_EQ(7U, data_length);
  5373. body.append(data, data_length);
  5374. return true;
  5375. });
  5376. EXPECT_EQ(body, "content");
  5377. res.set_content(body, "text/plain");
  5378. }
  5379. })
  5380. .Put("/content_receiver",
  5381. [&](const Request & /*req*/, Response &res,
  5382. const ContentReader &content_reader) {
  5383. std::string body;
  5384. content_reader([&](const char *data, size_t data_length) {
  5385. body.append(data, data_length);
  5386. return true;
  5387. });
  5388. EXPECT_EQ(body, "content");
  5389. res.set_content(body, "text/plain");
  5390. })
  5391. .Patch("/content_receiver",
  5392. [&](const Request & /*req*/, Response &res,
  5393. const ContentReader &content_reader) {
  5394. std::string body;
  5395. content_reader([&](const char *data, size_t data_length) {
  5396. body.append(data, data_length);
  5397. return true;
  5398. });
  5399. EXPECT_EQ(body, "content");
  5400. res.set_content(body, "text/plain");
  5401. })
  5402. .Post("/query-string-and-body",
  5403. [&](const Request &req, Response & /*res*/) {
  5404. ASSERT_TRUE(req.has_param("key"));
  5405. EXPECT_EQ(req.get_param_value("key"), "value");
  5406. EXPECT_EQ(req.body, "content");
  5407. })
  5408. .Get("/last-request",
  5409. [&](const Request &req, Response & /*res*/) {
  5410. EXPECT_EQ("close", req.get_header_value("Connection"));
  5411. })
  5412. .Get(R"(/redirect/(\d+))",
  5413. [&](const Request &req, Response &res) {
  5414. auto num = std::stoi(req.matches[1]) + 1;
  5415. std::string url = "/redirect/" + std::to_string(num);
  5416. res.set_redirect(url);
  5417. })
  5418. .Post("/binary",
  5419. [&](const Request &req, Response &res) {
  5420. EXPECT_EQ(4U, req.body.size());
  5421. EXPECT_EQ("application/octet-stream",
  5422. req.get_header_value("Content-Type"));
  5423. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5424. res.set_content(req.body, "application/octet-stream");
  5425. })
  5426. .Put("/binary",
  5427. [&](const Request &req, Response &res) {
  5428. EXPECT_EQ(4U, req.body.size());
  5429. EXPECT_EQ("application/octet-stream",
  5430. req.get_header_value("Content-Type"));
  5431. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5432. res.set_content(req.body, "application/octet-stream");
  5433. })
  5434. .Patch("/binary",
  5435. [&](const Request &req, Response &res) {
  5436. EXPECT_EQ(4U, req.body.size());
  5437. EXPECT_EQ("application/octet-stream",
  5438. req.get_header_value("Content-Type"));
  5439. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5440. res.set_content(req.body, "application/octet-stream");
  5441. })
  5442. .Delete("/binary",
  5443. [&](const Request &req, Response &res) {
  5444. EXPECT_EQ(4U, req.body.size());
  5445. EXPECT_EQ("application/octet-stream",
  5446. req.get_header_value("Content-Type"));
  5447. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5448. res.set_content(req.body, "application/octet-stream");
  5449. })
  5450. .Get("/issue1772",
  5451. [&](const Request & /*req*/, Response &res) {
  5452. res.status = 401;
  5453. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5454. })
  5455. .Delete("/issue609",
  5456. [](const httplib::Request &, httplib::Response &res,
  5457. const httplib::ContentReader &) {
  5458. res.set_content("ok", "text/plain");
  5459. })
  5460. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5461. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5462. .Get("/compress",
  5463. [&](const Request & /*req*/, Response &res) {
  5464. res.set_content(
  5465. "12345678901234567890123456789012345678901234567890123456789"
  5466. "01234567890123456789012345678901234567890",
  5467. "text/plain");
  5468. })
  5469. .Get("/compress-with-charset",
  5470. [&](const Request & /*req*/, Response &res) {
  5471. res.set_content(
  5472. "12345678901234567890123456789012345678901234567890123456789"
  5473. "01234567890123456789012345678901234567890",
  5474. "application/json; charset=utf-8");
  5475. })
  5476. .Get("/nocompress",
  5477. [&](const Request & /*req*/, Response &res) {
  5478. res.set_content(
  5479. "12345678901234567890123456789012345678901234567890123456789"
  5480. "01234567890123456789012345678901234567890",
  5481. "application/octet-stream");
  5482. })
  5483. .Post("/compress-multipart",
  5484. [&](const Request &req, Response & /*res*/) {
  5485. EXPECT_EQ(2u, req.form.fields.size());
  5486. ASSERT_TRUE(!req.form.has_field("???"));
  5487. {
  5488. const auto &text = req.form.get_field("key1");
  5489. EXPECT_EQ("test", text);
  5490. }
  5491. {
  5492. const auto &text = req.form.get_field("key2");
  5493. EXPECT_EQ("--abcdefg123", text);
  5494. }
  5495. })
  5496. #endif
  5497. ;
  5498. persons_["john"] = "programmer";
  5499. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5500. svr_.wait_until_ready();
  5501. }
  5502. virtual void TearDown() {
  5503. svr_.stop();
  5504. if (!request_threads_.empty()) {
  5505. std::this_thread::sleep_for(std::chrono::seconds(1));
  5506. for (auto &t : request_threads_) {
  5507. t.join();
  5508. }
  5509. }
  5510. t_.join();
  5511. }
  5512. map<string, string> persons_;
  5513. #ifdef CPPHTTPLIB_SSL_ENABLED
  5514. SSLClient cli_;
  5515. SSLServer svr_;
  5516. #else
  5517. Client cli_;
  5518. Server svr_;
  5519. #endif
  5520. thread t_;
  5521. std::vector<thread> request_threads_;
  5522. };
  5523. TEST_F(ServerTest, GetMethod200) {
  5524. auto res = cli_.Get("/hi");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("HTTP/1.1", res->version);
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("OK", res->reason);
  5529. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5530. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5531. EXPECT_EQ("Hello World!", res->body);
  5532. }
  5533. TEST_F(ServerTest, GetEmptyFile) {
  5534. auto res = cli_.Get("/empty_file");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. EXPECT_EQ(StatusCode::OK_200, res->status);
  5537. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5538. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5539. EXPECT_EQ("", res->body);
  5540. }
  5541. TEST_F(ServerTest, GetFileContent) {
  5542. auto res = cli_.Get("/file_content");
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ(StatusCode::OK_200, res->status);
  5545. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5547. EXPECT_EQ("test.html", res->body);
  5548. }
  5549. TEST_F(ServerTest, GetFileContentWithRange) {
  5550. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5553. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5554. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5555. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5556. EXPECT_EQ("est", res->body);
  5557. }
  5558. TEST_F(ServerTest, GetFileContentWithContentType) {
  5559. auto res = cli_.Get("/file_content_with_content_type");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5563. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5564. EXPECT_EQ("file\n", res->body);
  5565. }
  5566. TEST_F(ServerTest, GetInvalidFileContent) {
  5567. auto res = cli_.Get("/invalid_file_content");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. }
  5571. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5572. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ("HTTP/1.1", res->version);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5577. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5578. EXPECT_EQ("Hello World!", res->body);
  5579. }
  5580. TEST_F(ServerTest, GetMethod302) {
  5581. auto res = cli_.Get("/");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::Found_302, res->status);
  5584. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5585. }
  5586. TEST_F(ServerTest, GetMethod302Redirect) {
  5587. cli_.set_follow_location(true);
  5588. auto res = cli_.Get("/");
  5589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5590. EXPECT_EQ(StatusCode::OK_200, res->status);
  5591. EXPECT_EQ("Hello World!", res->body);
  5592. EXPECT_EQ("/hi", res->location);
  5593. }
  5594. TEST_F(ServerTest, GetMethod404) {
  5595. auto res = cli_.Get("/invalid");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5598. }
  5599. TEST_F(ServerTest, HeadMethod200) {
  5600. auto res = cli_.Head("/hi");
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::OK_200, res->status);
  5603. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5604. EXPECT_TRUE(res->body.empty());
  5605. }
  5606. TEST_F(ServerTest, HeadMethod200Static) {
  5607. auto res = cli_.Head("/mount/dir/index.html");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5612. EXPECT_TRUE(res->body.empty());
  5613. }
  5614. TEST_F(ServerTest, HeadMethod404) {
  5615. auto res = cli_.Head("/invalid");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5618. EXPECT_TRUE(res->body.empty());
  5619. }
  5620. TEST_F(ServerTest, GetMethodPersonJohn) {
  5621. auto res = cli_.Get("/person/john");
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5625. EXPECT_EQ("programmer", res->body);
  5626. }
  5627. TEST_F(ServerTest, PostMethod1) {
  5628. auto res = cli_.Get("/person/john1");
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5631. res = cli_.Post("/person", "name=john1&note=coder",
  5632. "application/x-www-form-urlencoded");
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. ASSERT_EQ(StatusCode::OK_200, res->status);
  5635. res = cli_.Get("/person/john1");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5639. ASSERT_EQ("coder", res->body);
  5640. }
  5641. TEST_F(ServerTest, PostMethod2) {
  5642. auto res = cli_.Get("/person/john2");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5645. Params params;
  5646. params.emplace("name", "john2");
  5647. params.emplace("note", "coder");
  5648. res = cli_.Post("/person", params);
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. ASSERT_EQ(StatusCode::OK_200, res->status);
  5651. res = cli_.Get("/person/john2");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. ASSERT_EQ(StatusCode::OK_200, res->status);
  5654. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5655. ASSERT_EQ("coder", res->body);
  5656. }
  5657. TEST_F(ServerTest, PutMethod3) {
  5658. auto res = cli_.Get("/person/john3");
  5659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5660. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5661. Params params;
  5662. params.emplace("name", "john3");
  5663. params.emplace("note", "coder");
  5664. res = cli_.Put("/person", params);
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. ASSERT_EQ(StatusCode::OK_200, res->status);
  5667. res = cli_.Get("/person/john3");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. ASSERT_EQ(StatusCode::OK_200, res->status);
  5670. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5671. ASSERT_EQ("coder", res->body);
  5672. }
  5673. TEST_F(ServerTest, DeleteMethod1) {
  5674. auto res = cli_.Get("/person/john4");
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5677. Params params;
  5678. params.emplace("name", "john4");
  5679. params.emplace("note", "coder");
  5680. res = cli_.Post("/person", params);
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. ASSERT_EQ(StatusCode::OK_200, res->status);
  5683. res = cli_.Get("/person/john4");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. ASSERT_EQ(StatusCode::OK_200, res->status);
  5686. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5687. ASSERT_EQ("coder", res->body);
  5688. Params delete_params;
  5689. delete_params.emplace("name", "john4");
  5690. res = cli_.Delete("/person", delete_params);
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. ASSERT_EQ(StatusCode::OK_200, res->status);
  5693. ASSERT_EQ("DELETED", res->body);
  5694. res = cli_.Get("/person/john4");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5697. }
  5698. TEST_F(ServerTest, DeleteMethod2) {
  5699. auto res = cli_.Get("/person/john5");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5702. Params params;
  5703. params.emplace("name", "john5");
  5704. params.emplace("note", "developer");
  5705. res = cli_.Post("/person", params);
  5706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5707. ASSERT_EQ(StatusCode::OK_200, res->status);
  5708. res = cli_.Get("/person/john5");
  5709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5710. ASSERT_EQ(StatusCode::OK_200, res->status);
  5711. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5712. ASSERT_EQ("developer", res->body);
  5713. Params delete_params;
  5714. delete_params.emplace("name", "john5");
  5715. Headers headers;
  5716. headers.emplace("Custom-Header", "test-value");
  5717. res = cli_.Delete("/person", headers, delete_params);
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. ASSERT_EQ(StatusCode::OK_200, res->status);
  5720. ASSERT_EQ("DELETED", res->body);
  5721. res = cli_.Get("/person/john5");
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5724. }
  5725. TEST_F(ServerTest, DeleteMethod3) {
  5726. auto res = cli_.Get("/person/john6");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5729. Params params;
  5730. params.emplace("name", "john6");
  5731. params.emplace("note", "tester");
  5732. res = cli_.Post("/person", params);
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. ASSERT_EQ(StatusCode::OK_200, res->status);
  5735. res = cli_.Get("/person/john6");
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. ASSERT_EQ(StatusCode::OK_200, res->status);
  5738. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5739. ASSERT_EQ("tester", res->body);
  5740. Params delete_params;
  5741. delete_params.emplace("name", "john6");
  5742. Headers headers;
  5743. headers.emplace("Custom-Header", "test-value");
  5744. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("DELETED", res->body);
  5748. res = cli_.Get("/person/john6");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5751. }
  5752. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5753. Params params;
  5754. params.emplace("json", JSON_DATA);
  5755. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::OK_200, res->status);
  5758. ASSERT_EQ(JSON_DATA, res->body);
  5759. }
  5760. TEST_F(ServerTest, PostEmptyContent) {
  5761. auto res = cli_.Post("/empty", "", "text/plain");
  5762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5763. ASSERT_EQ(StatusCode::OK_200, res->status);
  5764. ASSERT_EQ("empty", res->body);
  5765. }
  5766. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5767. auto res = cli_.Post("/empty-no-content-type");
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. ASSERT_EQ(StatusCode::OK_200, res->status);
  5770. ASSERT_EQ("empty-no-content-type", res->body);
  5771. }
  5772. TEST_F(ServerTest, PostPathOnly) {
  5773. auto res = cli_.Post("/path-only");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. ASSERT_EQ(StatusCode::OK_200, res->status);
  5776. ASSERT_EQ("path-only", res->body);
  5777. }
  5778. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5779. auto res = cli_.Post("/path-headers-only",
  5780. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. ASSERT_EQ(StatusCode::OK_200, res->status);
  5783. ASSERT_EQ("path-headers-only", res->body);
  5784. }
  5785. TEST_F(ServerTest, PostLarge) {
  5786. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5788. ASSERT_EQ(StatusCode::OK_200, res->status);
  5789. EXPECT_EQ(LARGE_DATA, res->body);
  5790. }
  5791. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5792. auto res = cli_.Put("/empty-no-content-type");
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. ASSERT_EQ("empty-no-content-type", res->body);
  5796. }
  5797. TEST_F(ServerTest, GetMethodDir) {
  5798. auto res = cli_.Get("/dir/");
  5799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5800. EXPECT_EQ(StatusCode::OK_200, res->status);
  5801. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5802. auto body = R"(<html>
  5803. <head>
  5804. </head>
  5805. <body>
  5806. <a href="/dir/test.html">Test</a>
  5807. <a href="/hi">hi</a>
  5808. </body>
  5809. </html>
  5810. )";
  5811. EXPECT_EQ(body, res->body);
  5812. }
  5813. TEST_F(ServerTest, GetMethodDirTest) {
  5814. auto res = cli_.Get("/dir/test.html");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::OK_200, res->status);
  5817. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5818. EXPECT_EQ("test.html", res->body);
  5819. }
  5820. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5821. auto res = cli_.Get("/dir/../dir/test.html");
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. EXPECT_EQ(StatusCode::OK_200, res->status);
  5824. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5825. EXPECT_EQ("test.html", res->body);
  5826. }
  5827. TEST_F(ServerTest, GetMethodInvalidPath) {
  5828. auto res = cli_.Get("/dir/../test.html");
  5829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5831. }
  5832. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5833. auto res = cli_.Get("/../www/dir/test.html");
  5834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5836. }
  5837. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5838. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5841. }
  5842. TEST_F(ServerTest, GetMethodDirMountTest) {
  5843. auto res = cli_.Get("/mount/dir/test.html");
  5844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5845. EXPECT_EQ(StatusCode::OK_200, res->status);
  5846. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5847. EXPECT_EQ("test.html", res->body);
  5848. }
  5849. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5850. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5852. EXPECT_EQ(StatusCode::OK_200, res->status);
  5853. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5854. EXPECT_EQ("test.html", res->body);
  5855. }
  5856. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5857. auto res = cli_.Get("/mount/dir/../test.html");
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5860. }
  5861. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5862. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5865. }
  5866. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5867. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5870. }
  5871. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5872. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5875. }
  5876. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5877. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5880. }
  5881. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5882. auto res = cli_.Get("/mount/dir");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5885. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5886. }
  5887. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5888. auto res = cli_.Get("//dir");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5891. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5892. }
  5893. TEST_F(ServerTest, PostMethod303) {
  5894. auto res = cli_.Post("/1", "body", "text/plain");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5897. EXPECT_EQ("/2", res->get_header_value("Location"));
  5898. }
  5899. TEST_F(ServerTest, PostMethod303Redirect) {
  5900. cli_.set_follow_location(true);
  5901. auto res = cli_.Post("/1", "body", "text/plain");
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ("redirected.", res->body);
  5905. EXPECT_EQ("/2", res->location);
  5906. }
  5907. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5908. auto res = cli_.Get("/dir/test.abcde");
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5912. EXPECT_EQ("abcde", res->body);
  5913. }
  5914. TEST_F(ServerTest, StaticFileRange) {
  5915. auto res =
  5916. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5919. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5920. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5921. EXPECT_EQ(true, res->has_header("Content-Range"));
  5922. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5923. EXPECT_EQ(std::string("cd"), res->body);
  5924. }
  5925. TEST_F(ServerTest, StaticFileRanges) {
  5926. auto res = cli_.Get("/dir/test.abcde",
  5927. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5930. EXPECT_TRUE(
  5931. res->get_header_value("Content-Type")
  5932. .find(
  5933. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5934. 0);
  5935. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5936. }
  5937. TEST_F(ServerTest, StaticFileRangeHead) {
  5938. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5941. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5942. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5943. EXPECT_EQ(true, res->has_header("Content-Range"));
  5944. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5945. }
  5946. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5947. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5951. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5952. EXPECT_EQ(true, res->has_header("Content-Range"));
  5953. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5954. res->get_header_value("Content-Range"));
  5955. EXPECT_EQ("LAST\n", res->body);
  5956. }
  5957. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5958. auto res =
  5959. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5963. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5964. EXPECT_EQ(true, res->has_header("Content-Range"));
  5965. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5966. }
  5967. TEST_F(ServerTest, StaticFileBigFile) {
  5968. auto res = cli_.Get("/dir/1MB.txt");
  5969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5970. EXPECT_EQ(StatusCode::OK_200, res->status);
  5971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5972. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5973. }
  5974. TEST_F(ServerTest, InvalidBaseDirMount) {
  5975. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5976. }
  5977. TEST_F(ServerTest, Binary) {
  5978. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5979. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5980. "application/octet-stream");
  5981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5982. ASSERT_EQ(StatusCode::OK_200, res->status);
  5983. ASSERT_EQ(4U, res->body.size());
  5984. res = cli_.Put("/binary", binary.data(), binary.size(),
  5985. "application/octet-stream");
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. ASSERT_EQ(StatusCode::OK_200, res->status);
  5988. ASSERT_EQ(4U, res->body.size());
  5989. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5990. "application/octet-stream");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. ASSERT_EQ(StatusCode::OK_200, res->status);
  5993. ASSERT_EQ(4U, res->body.size());
  5994. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5995. "application/octet-stream");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. ASSERT_EQ(4U, res->body.size());
  5999. }
  6000. TEST_F(ServerTest, BinaryString) {
  6001. auto binary = std::string("\x00\x01\x02\x03", 4);
  6002. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6004. ASSERT_EQ(StatusCode::OK_200, res->status);
  6005. ASSERT_EQ(4U, res->body.size());
  6006. res = cli_.Put("/binary", binary, "application/octet-stream");
  6007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6008. ASSERT_EQ(StatusCode::OK_200, res->status);
  6009. ASSERT_EQ(4U, res->body.size());
  6010. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. ASSERT_EQ(StatusCode::OK_200, res->status);
  6013. ASSERT_EQ(4U, res->body.size());
  6014. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. ASSERT_EQ(StatusCode::OK_200, res->status);
  6017. ASSERT_EQ(4U, res->body.size());
  6018. }
  6019. TEST_F(ServerTest, EmptyRequest) {
  6020. auto res = cli_.Get("");
  6021. ASSERT_TRUE(!res);
  6022. EXPECT_EQ(Error::Connection, res.error());
  6023. }
  6024. TEST_F(ServerTest, LongRequest) {
  6025. std::string request;
  6026. for (size_t i = 0; i < 545; i++) {
  6027. request += "/TooLongRequest";
  6028. }
  6029. request += "OK";
  6030. auto res = cli_.Get(request.c_str());
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6033. }
  6034. TEST_F(ServerTest, TooLongRequest) {
  6035. std::string request;
  6036. for (size_t i = 0; i < 546; i++) {
  6037. request += "/TooLongRequest";
  6038. }
  6039. request += "_NG";
  6040. auto start = std::chrono::high_resolution_clock::now();
  6041. cli_.set_keep_alive(true);
  6042. auto res = cli_.Get(request.c_str());
  6043. auto end = std::chrono::high_resolution_clock::now();
  6044. auto elapsed =
  6045. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6046. .count();
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6049. EXPECT_LE(elapsed, 1000);
  6050. EXPECT_EQ("close", res->get_header_value("Connection"));
  6051. EXPECT_FALSE(cli_.is_socket_open());
  6052. }
  6053. TEST_F(ServerTest, AlmostTooLongRequest) {
  6054. // test for #2046 - URI length check shouldn't include other content on req
  6055. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6056. // leading /, space, HTTP/1.1)
  6057. std::string request =
  6058. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6059. auto res = cli_.Get(request.c_str());
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6062. }
  6063. TEST_F(ServerTest, LongHeader) {
  6064. Request req;
  6065. req.method = "GET";
  6066. req.path = "/hi";
  6067. std::string host_and_port;
  6068. host_and_port += HOST;
  6069. host_and_port += ":";
  6070. host_and_port += std::to_string(PORT);
  6071. req.headers.emplace("Host", host_and_port.c_str());
  6072. req.headers.emplace("Accept", "*/*");
  6073. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6074. req.headers.emplace(
  6075. "Header-Name",
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6104. "@@@@@@@@@@@@@@@@");
  6105. auto res = std::make_shared<Response>();
  6106. auto error = Error::Success;
  6107. auto ret = cli_.send(req, *res, error);
  6108. ASSERT_TRUE(ret);
  6109. EXPECT_EQ(StatusCode::OK_200, res->status);
  6110. }
  6111. TEST_F(ServerTest, LongQueryValue) {
  6112. auto start = std::chrono::high_resolution_clock::now();
  6113. cli_.set_keep_alive(true);
  6114. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6115. auto end = std::chrono::high_resolution_clock::now();
  6116. auto elapsed =
  6117. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6118. .count();
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6121. EXPECT_LE(elapsed, 1000);
  6122. EXPECT_EQ("close", res->get_header_value("Connection"));
  6123. EXPECT_FALSE(cli_.is_socket_open());
  6124. }
  6125. TEST_F(ServerTest, TooLongQueryValue) {
  6126. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6127. ASSERT_FALSE(res);
  6128. EXPECT_EQ(Error::Read, res.error());
  6129. }
  6130. TEST_F(ServerTest, TooLongHeader) {
  6131. Request req;
  6132. req.method = "GET";
  6133. req.path = "/hi";
  6134. std::string host_and_port;
  6135. host_and_port += HOST;
  6136. host_and_port += ":";
  6137. host_and_port += std::to_string(PORT);
  6138. req.headers.emplace("Host", host_and_port.c_str());
  6139. req.headers.emplace("Accept", "*/*");
  6140. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6141. req.headers.emplace(
  6142. "Header-Name",
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6169. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6171. "@@@@@@@@@@@@@@@@@");
  6172. auto res = std::make_shared<Response>();
  6173. auto error = Error::Success;
  6174. auto ret = cli_.send(req, *res, error);
  6175. ASSERT_TRUE(ret);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. }
  6178. TEST_F(ServerTest, HeaderCountAtLimit) {
  6179. // Test with headers just under the 100 limit
  6180. httplib::Headers headers;
  6181. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6182. // This should keep us just under the 100 header limit
  6183. for (int i = 0; i < 95; i++) {
  6184. std::string name = "X-Test-Header-" + std::to_string(i);
  6185. std::string value = "value" + std::to_string(i);
  6186. headers.emplace(name, value);
  6187. }
  6188. // This should work fine as we're under the limit
  6189. auto res = cli_.Get("/hi", headers);
  6190. EXPECT_TRUE(res);
  6191. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6192. }
  6193. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6194. // Test with many headers to exceed the 100 limit
  6195. httplib::Headers headers;
  6196. // Add 150 headers to definitely exceed the 100 limit
  6197. for (int i = 0; i < 150; i++) {
  6198. std::string name = "X-Test-Header-" + std::to_string(i);
  6199. std::string value = "value" + std::to_string(i);
  6200. headers.emplace(name, value);
  6201. }
  6202. // This should fail due to exceeding header count limit
  6203. cli_.set_keep_alive(true);
  6204. auto res = cli_.Get("/hi", headers);
  6205. // The server should respond with 400 Bad Request
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6208. EXPECT_EQ("close", res->get_header_value("Connection"));
  6209. EXPECT_FALSE(cli_.is_socket_open());
  6210. }
  6211. TEST_F(ServerTest, PercentEncoding) {
  6212. auto res = cli_.Get("/e%6edwith%");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. }
  6216. TEST_F(ServerTest, PercentEncodingUnicode) {
  6217. auto res = cli_.Get("/e%u006edwith%");
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::OK_200, res->status);
  6220. }
  6221. TEST_F(ServerTest, InvalidPercentEncoding) {
  6222. auto res = cli_.Get("/%endwith%");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6225. }
  6226. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6227. auto res = cli_.Get("/%uendwith%");
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6230. }
  6231. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6232. auto res = cli_.Get("/hello?aaa=bbb%");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6235. }
  6236. TEST_F(ServerTest, PlusSignEncoding) {
  6237. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. EXPECT_EQ("a +b", res->body);
  6241. }
  6242. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6243. // This test simulates a potential DoS attack using many headers
  6244. // to verify our security fix prevents memory exhaustion
  6245. httplib::Headers attack_headers;
  6246. // Attempt to add many headers like an attacker would (200 headers to far
  6247. // exceed limit)
  6248. for (int i = 0; i < 200; i++) {
  6249. std::string name = "X-Attack-Header-" + std::to_string(i);
  6250. std::string value = "attack_payload_" + std::to_string(i);
  6251. attack_headers.emplace(name, value);
  6252. }
  6253. // Try to POST with excessive headers
  6254. cli_.set_keep_alive(true);
  6255. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6256. // Should either fail or return 400 Bad Request due to security limit
  6257. if (res) {
  6258. // If we get a response, it should be 400 Bad Request
  6259. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6260. EXPECT_EQ("close", res->get_header_value("Connection"));
  6261. }
  6262. EXPECT_FALSE(cli_.is_socket_open());
  6263. }
  6264. TEST_F(ServerTest, MultipartFormData) {
  6265. UploadFormDataItems items = {
  6266. {"text1", "text default", "", ""},
  6267. {"text2", "aωb", "", ""},
  6268. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6269. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6270. {"file3", "", "", "application/octet-stream"},
  6271. {"file4", "", "", " application/json tmp-string "}};
  6272. auto res = cli_.Post("/multipart", items);
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. }
  6276. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6277. UploadFormDataItems items = {
  6278. {"text", "default text", "", ""},
  6279. {"multi_text1", "aaaaa", "", ""},
  6280. {"multi_text1", "bbbbb", "", ""},
  6281. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6282. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6283. "application/json"},
  6284. };
  6285. auto res = cli_.Post("/multipart/multi_file_values", items);
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. }
  6289. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6290. auto res = cli_.Get("/hi");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. EXPECT_EQ(StatusCode::OK_200, res->status);
  6293. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6294. EXPECT_EQ("Hello World!", res->body);
  6295. }
  6296. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6297. Request req;
  6298. req.method = "POST";
  6299. req.path = "/chunked";
  6300. std::string host_and_port;
  6301. host_and_port += HOST;
  6302. host_and_port += ":";
  6303. host_and_port += std::to_string(PORT);
  6304. req.headers.emplace("Host", host_and_port.c_str());
  6305. req.headers.emplace("Accept", "*/*");
  6306. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6307. req.headers.emplace("Content-Type", "text/plain");
  6308. req.headers.emplace("Content-Length", "0");
  6309. req.headers.emplace(
  6310. "Transfer-Encoding",
  6311. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6312. // Client does not chunk, so make a chunked body manually.
  6313. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6314. auto res = std::make_shared<Response>();
  6315. auto error = Error::Success;
  6316. auto ret = cli_.send(req, *res, error);
  6317. ASSERT_TRUE(ret);
  6318. EXPECT_EQ(StatusCode::OK_200, res->status);
  6319. }
  6320. template <typename ClientT>
  6321. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6322. int expected_status) {
  6323. Request req;
  6324. req.method = "POST";
  6325. req.path = "/chunked";
  6326. std::string host_and_port;
  6327. host_and_port += HOST;
  6328. host_and_port += ":";
  6329. host_and_port += std::to_string(PORT);
  6330. req.headers.emplace("Host", host_and_port.c_str());
  6331. req.headers.emplace("Content-Length", "0");
  6332. req.headers.emplace("Transfer-Encoding", "chunked");
  6333. req.body = body;
  6334. auto res = std::make_shared<Response>();
  6335. auto error = Error::Success;
  6336. ASSERT_TRUE(cli.send(req, *res, error));
  6337. EXPECT_EQ(expected_status, res->status);
  6338. }
  6339. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6340. // rather than treat them as valid lengths.
  6341. template <typename ClientT>
  6342. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6343. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6344. }
  6345. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6346. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6347. }
  6348. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6349. expect_chunked_body_rejected(
  6350. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6351. }
  6352. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6353. // chunk-size line carries no CR, LF or other control character ahead of its
  6354. // terminator. Such a line must be refused rather than read as extension text.
  6355. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6356. expect_chunked_body_rejected(
  6357. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6358. }
  6359. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6360. expect_chunked_body_rejected(
  6361. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6362. }
  6363. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6364. expect_chunked_body_rejected(
  6365. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6366. }
  6367. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6368. // The literal stays split: a hex escape consumes every hex digit that
  6369. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6370. expect_chunked_body_rejected(
  6371. cli_, "4;a\x01"
  6372. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6373. }
  6374. TEST_F(ServerTest, AcceptsChunkExtension) {
  6375. expect_chunked_body_status(cli_,
  6376. "4;name=value\r\ndech\r\n"
  6377. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6378. "0;last\r\n\r\n",
  6379. StatusCode::OK_200);
  6380. }
  6381. TEST_F(ServerTest, GetStreamed2) {
  6382. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6385. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6386. EXPECT_EQ(true, res->has_header("Content-Range"));
  6387. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6388. EXPECT_EQ(std::string("ab"), res->body);
  6389. }
  6390. TEST_F(ServerTest, GetStreamed) {
  6391. auto res = cli_.Get("/streamed");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6395. EXPECT_EQ(std::string("aaabbb"), res->body);
  6396. }
  6397. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6398. auto res = cli_.Get("/streamed-without-length",
  6399. Headers{make_range_header({{0, -1}})});
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::OK_200, res->status);
  6402. EXPECT_EQ(false, res->has_header("Content-Length"));
  6403. EXPECT_EQ(false, res->has_header("Content-Range"));
  6404. EXPECT_EQ(std::string("abcdefg"), res->body);
  6405. }
  6406. TEST_F(ServerTest, GetStreamedWithRange1) {
  6407. auto res =
  6408. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6411. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6412. EXPECT_EQ(true, res->has_header("Content-Range"));
  6413. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6414. EXPECT_EQ(std::string("def"), res->body);
  6415. }
  6416. TEST_F(ServerTest, GetStreamedWithRange2) {
  6417. auto res =
  6418. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6421. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6422. EXPECT_EQ(true, res->has_header("Content-Range"));
  6423. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6424. EXPECT_EQ(std::string("bcdefg"), res->body);
  6425. }
  6426. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6427. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6430. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6431. EXPECT_EQ(true, res->has_header("Content-Range"));
  6432. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6433. EXPECT_EQ(std::string("efg"), res->body);
  6434. }
  6435. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6436. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6437. // the entire representation.
  6438. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6439. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6442. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6443. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6444. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6445. }
  6446. }
  6447. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6448. auto res =
  6449. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6452. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6453. EXPECT_EQ(false, res->has_header("Content-Range"));
  6454. EXPECT_EQ(0U, res->body.size());
  6455. }
  6456. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6457. // Only a 206 is served as a partial representation. Under any other status
  6458. // `apply_ranges()` reported the full content length, so the body must match
  6459. // that header, and the content provider must never be asked for an offset
  6460. // outside the representation.
  6461. auto check = [&](int status, const char *range) {
  6462. auto path =
  6463. std::string("/streamed-with-range?status=") + std::to_string(status);
  6464. auto ctx = path + " Range: " + range;
  6465. auto res = cli_.Get(path, Headers{{"Range", range}});
  6466. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6467. EXPECT_EQ(status, res->status) << ctx;
  6468. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6470. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6471. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6472. };
  6473. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6474. check(403, "bytes=3-5");
  6475. // The offset is far past the representation.
  6476. check(403, "bytes=100000-100200");
  6477. // `first_pos` is still -1 here, and the bounds asserts in
  6478. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6479. check(403, "bytes=-3");
  6480. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6481. // multipart branch would have written one that is empty.
  6482. check(403, "bytes=1-2, 4-5");
  6483. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6484. // covers the whole representation.
  6485. check(200, "bytes=3-5");
  6486. check(200, "bytes=1-2, 4-5");
  6487. }
  6488. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6489. auto res =
  6490. cli_.Get("/streamed-with-range",
  6491. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6492. "92233720368547758079223372036854775807"}});
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6495. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6496. EXPECT_EQ(false, res->has_header("Content-Range"));
  6497. EXPECT_EQ(0U, res->body.size());
  6498. }
  6499. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6500. auto res = cli_.Get(
  6501. "/with-range",
  6502. Headers{{"Range",
  6503. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6504. {"Accept-Encoding", ""}});
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6507. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6508. EXPECT_EQ(true, res->has_header("Content-Range"));
  6509. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6510. EXPECT_EQ(std::string("abcdefg"), res->body);
  6511. }
  6512. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6513. auto res = cli_.Get("/with-range", Headers{
  6514. {"Range", "bytes=0-"},
  6515. {"Accept-Encoding", ""},
  6516. });
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6519. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6520. EXPECT_EQ(true, res->has_header("Content-Range"));
  6521. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6522. EXPECT_EQ(std::string("abcdefg"), res->body);
  6523. }
  6524. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6525. auto res = cli_.Get("/streamed-with-range",
  6526. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6528. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6529. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6530. EXPECT_EQ(false, res->has_header("Content-Range"));
  6531. EXPECT_EQ(267U, res->body.size());
  6532. // Check that both range contents are present
  6533. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6534. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6535. // Check that Content-Range headers are present for both ranges
  6536. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6537. std::string::npos);
  6538. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6539. std::string::npos);
  6540. }
  6541. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6542. Ranges ranges;
  6543. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6544. ranges.emplace_back(0, -1);
  6545. }
  6546. auto res = cli_.Get("/streamed-with-range?error",
  6547. Headers{{make_range_header(ranges)}});
  6548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6549. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6550. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6551. EXPECT_EQ(false, res->has_header("Content-Range"));
  6552. EXPECT_EQ(0U, res->body.size());
  6553. }
  6554. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6555. auto res = cli_.Get("/streamed-with-range",
  6556. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6558. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6559. EXPECT_EQ(5U, res->body.size());
  6560. // Check that overlapping ranges are coalesced into a single range
  6561. EXPECT_EQ("bcdef", res->body);
  6562. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6563. // Should be single range, not multipart
  6564. EXPECT_TRUE(res->has_header("Content-Range"));
  6565. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6566. }
  6567. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6568. auto res = cli_.Get("/streamed-with-range",
  6569. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6572. EXPECT_EQ(268U, res->body.size());
  6573. // Check that both range contents are present
  6574. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6575. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6576. // Check that Content-Range headers are present for both ranges
  6577. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6578. std::string::npos);
  6579. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6580. std::string::npos);
  6581. }
  6582. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6583. auto res = cli_.Get("/streamed-with-range",
  6584. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6587. EXPECT_EQ(269U, res->body.size());
  6588. // Check that both duplicate range contents are present
  6589. size_t first_abc = res->body.find("abc\r\n");
  6590. EXPECT_TRUE(first_abc != std::string::npos);
  6591. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6592. EXPECT_TRUE(second_abc != std::string::npos);
  6593. // Check that Content-Range headers are present for both ranges
  6594. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6595. EXPECT_TRUE(first_range != std::string::npos);
  6596. size_t second_range =
  6597. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6598. EXPECT_TRUE(second_range != std::string::npos);
  6599. }
  6600. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6601. auto res =
  6602. cli_.Get("/streamed-with-range?error",
  6603. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6605. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6606. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6607. EXPECT_EQ(false, res->has_header("Content-Range"));
  6608. EXPECT_EQ(0U, res->body.size());
  6609. }
  6610. TEST_F(ServerTest, GetStreamedEndless) {
  6611. uint64_t offset = 0;
  6612. auto res = cli_.Get("/streamed-cancel",
  6613. [&](const char * /*data*/, uint64_t data_length) {
  6614. if (offset < 100) {
  6615. offset += data_length;
  6616. return true;
  6617. }
  6618. return false;
  6619. });
  6620. ASSERT_TRUE(!res);
  6621. EXPECT_EQ(Error::Canceled, res.error());
  6622. }
  6623. TEST_F(ServerTest, ClientStop) {
  6624. std::atomic_size_t count{4};
  6625. std::vector<std::thread> threads;
  6626. for (auto i = count.load(); i != 0; --i) {
  6627. threads.emplace_back([&]() {
  6628. auto res = cli_.Get("/streamed-cancel",
  6629. [&](const char *, uint64_t) { return true; });
  6630. --count;
  6631. ASSERT_TRUE(!res);
  6632. EXPECT_TRUE(res.error() == Error::Canceled ||
  6633. res.error() == Error::Read || res.error() == Error::Write);
  6634. });
  6635. }
  6636. std::this_thread::sleep_for(std::chrono::seconds(2));
  6637. while (count != 0) {
  6638. cli_.stop();
  6639. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6640. }
  6641. for (auto &t : threads) {
  6642. t.join();
  6643. }
  6644. }
  6645. TEST_F(ServerTest, GetWithRange1) {
  6646. auto res = cli_.Get("/with-range", Headers{
  6647. make_range_header({{3, 5}}),
  6648. {"Accept-Encoding", ""},
  6649. });
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6652. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6653. EXPECT_EQ(true, res->has_header("Content-Range"));
  6654. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6655. EXPECT_EQ(std::string("def"), res->body);
  6656. }
  6657. TEST_F(ServerTest, GetWithRange2) {
  6658. auto res = cli_.Get("/with-range", Headers{
  6659. make_range_header({{1, -1}}),
  6660. {"Accept-Encoding", ""},
  6661. });
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6664. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6665. EXPECT_EQ(true, res->has_header("Content-Range"));
  6666. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6667. EXPECT_EQ(std::string("bcdefg"), res->body);
  6668. }
  6669. TEST_F(ServerTest, GetWithRange3) {
  6670. auto res = cli_.Get("/with-range", Headers{
  6671. make_range_header({{0, 0}}),
  6672. {"Accept-Encoding", ""},
  6673. });
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6676. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6677. EXPECT_EQ(true, res->has_header("Content-Range"));
  6678. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6679. EXPECT_EQ(std::string("a"), res->body);
  6680. }
  6681. TEST_F(ServerTest, GetWithRange4) {
  6682. auto res = cli_.Get("/with-range", Headers{
  6683. make_range_header({{-1, 2}}),
  6684. {"Accept-Encoding", ""},
  6685. });
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6688. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6689. EXPECT_EQ(true, res->has_header("Content-Range"));
  6690. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6691. EXPECT_EQ(std::string("fg"), res->body);
  6692. }
  6693. TEST_F(ServerTest, GetWithRange5) {
  6694. auto res = cli_.Get("/with-range", Headers{
  6695. make_range_header({{0, 5}}),
  6696. {"Accept-Encoding", ""},
  6697. });
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6700. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6701. EXPECT_EQ(true, res->has_header("Content-Range"));
  6702. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6703. EXPECT_EQ(std::string("abcdef"), res->body);
  6704. }
  6705. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6706. auto res =
  6707. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6710. }
  6711. TEST_F(ServerTest, GetWithRangeMultipart) {
  6712. auto res =
  6713. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6716. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6717. EXPECT_EQ(false, res->has_header("Content-Range"));
  6718. EXPECT_EQ(267U, res->body.size());
  6719. }
  6720. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6721. auto res = cli_.Get("/with-range",
  6722. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6725. }
  6726. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6727. auto res = cli_.Get("/with-range-customized-response",
  6728. Headers{{make_range_header({{1, 2}})}});
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6731. EXPECT_EQ(true, res->has_header("Content-Length"));
  6732. EXPECT_EQ(false, res->has_header("Content-Range"));
  6733. EXPECT_EQ(JSON_DATA, res->body);
  6734. }
  6735. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6736. auto res = cli_.Get("/with-range-customized-response",
  6737. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6740. EXPECT_EQ(true, res->has_header("Content-Length"));
  6741. EXPECT_EQ(false, res->has_header("Content-Range"));
  6742. EXPECT_EQ(JSON_DATA, res->body);
  6743. }
  6744. TEST_F(ServerTest, Issue1772) {
  6745. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6748. }
  6749. TEST_F(ServerTest, Issue609) {
  6750. auto res = cli_.Delete("/issue609");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. EXPECT_EQ(std::string("ok"), res->body);
  6754. }
  6755. TEST_F(ServerTest, GetStreamedChunked) {
  6756. auto res = cli_.Get("/streamed-chunked");
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. EXPECT_EQ(std::string("123456789"), res->body);
  6760. }
  6761. TEST_F(ServerTest, GetStreamedChunked2) {
  6762. auto res = cli_.Get("/streamed-chunked2");
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. EXPECT_EQ(StatusCode::OK_200, res->status);
  6765. EXPECT_EQ(std::string("123456789"), res->body);
  6766. }
  6767. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6768. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::OK_200, res->status);
  6771. EXPECT_EQ(std::string("123456789"), res->body);
  6772. EXPECT_TRUE(res->has_header("Trailer"));
  6773. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6774. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6775. // Trailers are now stored separately from headers (security fix)
  6776. EXPECT_EQ(2U, res->trailers.size());
  6777. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6778. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6779. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6780. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6781. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6782. // Verify trailers are NOT in headers (security verification)
  6783. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6784. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6785. }
  6786. TEST_F(ServerTest, LargeChunkedPost) {
  6787. Request req;
  6788. req.method = "POST";
  6789. req.path = "/large-chunked";
  6790. std::string host_and_port;
  6791. host_and_port += HOST;
  6792. host_and_port += ":";
  6793. host_and_port += std::to_string(PORT);
  6794. req.headers.emplace("Host", host_and_port.c_str());
  6795. req.headers.emplace("Accept", "*/*");
  6796. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6797. req.headers.emplace("Content-Type", "text/plain");
  6798. req.headers.emplace("Content-Length", "0");
  6799. req.headers.emplace("Transfer-Encoding", "chunked");
  6800. std::string long_string(30 * 1024u, 'a');
  6801. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6802. // Attempt to make a large enough post to exceed OS buffers, to test that
  6803. // the server handles short reads if the full chunk data isn't available.
  6804. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6805. auto res = std::make_shared<Response>();
  6806. auto error = Error::Success;
  6807. auto ret = cli_.send(req, *res, error);
  6808. ASSERT_TRUE(ret);
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. }
  6811. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6812. auto res = cli_.Get("/remote_addr");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6816. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6817. }
  6818. TEST_F(ServerTest, GetMethodLocalAddr) {
  6819. auto res = cli_.Get("/local_addr");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6823. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6824. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6825. }
  6826. TEST_F(ServerTest, HTTPResponseSplitting) {
  6827. auto res = cli_.Get("/http_response_splitting");
  6828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6829. EXPECT_EQ(StatusCode::OK_200, res->status);
  6830. }
  6831. TEST_F(ServerTest, SlowRequest) {
  6832. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6833. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6834. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6835. }
  6836. #if 0
  6837. TEST_F(ServerTest, SlowPost) {
  6838. char buffer[64 * 1024];
  6839. memset(buffer, 0x42, sizeof(buffer));
  6840. auto res = cli_.Post(
  6841. "/slowpost", 64 * 1024 * 1024,
  6842. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6843. auto ret = sink.write(buffer, sizeof(buffer));
  6844. EXPECT_TRUE(ret);
  6845. return true;
  6846. },
  6847. "text/plain");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::OK_200, res->status);
  6850. }
  6851. TEST_F(ServerTest, SlowPostFail) {
  6852. char buffer[64 * 1024];
  6853. memset(buffer, 0x42, sizeof(buffer));
  6854. cli_.set_write_timeout(std::chrono::seconds(0));
  6855. auto res = cli_.Post(
  6856. "/slowpost", 64 * 1024 * 1024,
  6857. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6858. sink.write(buffer, sizeof(buffer));
  6859. return true;
  6860. },
  6861. "text/plain");
  6862. ASSERT_TRUE(!res);
  6863. EXPECT_EQ(Error::Write, res.error());
  6864. }
  6865. #endif
  6866. TEST_F(ServerTest, Put) {
  6867. auto res = cli_.Put("/put", "PUT", "text/plain");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("PUT", res->body);
  6871. }
  6872. TEST_F(ServerTest, PutWithContentProvider) {
  6873. auto res = cli_.Put(
  6874. "/put", 3,
  6875. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6876. sink.os << "PUT";
  6877. return true;
  6878. },
  6879. "text/plain");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("PUT", res->body);
  6883. }
  6884. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6885. auto res = cli_.Post(
  6886. "/post", 42,
  6887. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6888. return false;
  6889. },
  6890. "text/plain");
  6891. ASSERT_TRUE(!res);
  6892. EXPECT_EQ(Error::Canceled, res.error());
  6893. }
  6894. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6895. auto res = cli_.Put(
  6896. "/put",
  6897. [](size_t /*offset*/, DataSink &sink) {
  6898. sink.os << "PUT";
  6899. sink.done();
  6900. return true;
  6901. },
  6902. "text/plain");
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ("PUT", res->body);
  6906. }
  6907. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6908. auto res = cli_.Post(
  6909. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6910. "text/plain");
  6911. ASSERT_TRUE(!res);
  6912. EXPECT_EQ(Error::Canceled, res.error());
  6913. }
  6914. TEST_F(ServerTest, PostLoopBack) {
  6915. std::string body;
  6916. auto res = cli_.Post(
  6917. "/post-loopback", 9,
  6918. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6919. EXPECT_EQ(9u, length);
  6920. sink.write("123", 3);
  6921. sink.write("456", 3);
  6922. sink.write("789", 3);
  6923. return true;
  6924. },
  6925. "text/plain",
  6926. [&body](const char *data, size_t data_length) {
  6927. body.append(data, data_length);
  6928. return true;
  6929. });
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::OK_200, res->status);
  6932. EXPECT_EQ("123456789", body);
  6933. }
  6934. TEST_F(ServerTest, PutLoopBack) {
  6935. std::string body;
  6936. auto res = cli_.Put(
  6937. "/put-loopback", 9,
  6938. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6939. EXPECT_EQ(9u, length);
  6940. sink.write("123", 3);
  6941. sink.write("456", 3);
  6942. sink.write("789", 3);
  6943. return true;
  6944. },
  6945. "text/plain",
  6946. [&body](const char *data, size_t data_length) {
  6947. body.append(data, data_length);
  6948. return true;
  6949. });
  6950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6951. EXPECT_EQ(StatusCode::OK_200, res->status);
  6952. EXPECT_EQ("123456789", body);
  6953. }
  6954. TEST_F(ServerTest, PatchLoopBack) {
  6955. std::string body;
  6956. auto res = cli_.Patch(
  6957. "/patch-loopback", 9,
  6958. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6959. EXPECT_EQ(9u, length);
  6960. sink.write("123", 3);
  6961. sink.write("456", 3);
  6962. sink.write("789", 3);
  6963. return true;
  6964. },
  6965. "text/plain",
  6966. [&body](const char *data, size_t data_length) {
  6967. body.append(data, data_length);
  6968. return true;
  6969. });
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. EXPECT_EQ(StatusCode::OK_200, res->status);
  6972. EXPECT_EQ("123456789", body);
  6973. }
  6974. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6975. std::string body;
  6976. auto res = cli_.Post(
  6977. "/post-loopback",
  6978. [](size_t /*offset*/, DataSink &sink) {
  6979. sink.write("123", 3);
  6980. sink.write("456", 3);
  6981. sink.write("789", 3);
  6982. sink.done();
  6983. return true;
  6984. },
  6985. "text/plain",
  6986. [&body](const char *data, size_t data_length) {
  6987. body.append(data, data_length);
  6988. return true;
  6989. });
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("123456789", body);
  6993. }
  6994. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6995. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6996. cli_.set_compress(true);
  6997. auto res = cli_.Put(
  6998. "/put", 3,
  6999. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7000. sink.os << "PUT";
  7001. return true;
  7002. },
  7003. "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("PUT", res->body);
  7007. }
  7008. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7009. cli_.set_compress(true);
  7010. auto res = cli_.Post(
  7011. "/post", 42,
  7012. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7013. return false;
  7014. },
  7015. "text/plain");
  7016. ASSERT_TRUE(!res);
  7017. EXPECT_EQ(Error::Canceled, res.error());
  7018. }
  7019. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7020. cli_.set_compress(true);
  7021. auto res = cli_.Put(
  7022. "/put",
  7023. [](size_t /*offset*/, DataSink &sink) {
  7024. sink.os << "PUT";
  7025. sink.done();
  7026. return true;
  7027. },
  7028. "text/plain");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::OK_200, res->status);
  7031. EXPECT_EQ("PUT", res->body);
  7032. }
  7033. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7034. cli_.set_compress(true);
  7035. auto res = cli_.Post(
  7036. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7037. "text/plain");
  7038. ASSERT_TRUE(!res);
  7039. EXPECT_EQ(Error::Canceled, res.error());
  7040. }
  7041. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7042. cli_.set_compress(true);
  7043. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::OK_200, res->status);
  7046. EXPECT_EQ(LARGE_DATA, res->body);
  7047. }
  7048. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7049. #ifdef CPPHTTPLIB_SSL_ENABLED
  7050. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7051. Client cli(s.c_str());
  7052. cli.enable_server_certificate_verification(false);
  7053. #else
  7054. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7055. Client cli(s.c_str());
  7056. #endif
  7057. cli.set_compress(true);
  7058. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::OK_200, res->status);
  7061. EXPECT_EQ(LARGE_DATA, res->body);
  7062. // The compressed size should be less than a 10th of the original. May vary
  7063. // depending on the zlib library.
  7064. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7065. static_cast<uint64_t>(10 * 1024 * 1024));
  7066. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7067. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7068. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7069. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7070. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7071. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7072. #endif
  7073. }
  7074. TEST_F(ServerTest, PutContentWithDeflate) {
  7075. cli_.set_compress(false);
  7076. Headers headers;
  7077. headers.emplace("Content-Encoding", "deflate");
  7078. // PUT in deflate format:
  7079. auto res = cli_.Put("/put", headers,
  7080. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. EXPECT_EQ("PUT", res->body);
  7084. }
  7085. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7086. Headers headers;
  7087. headers.emplace("Accept-Encoding", "gzip, deflate");
  7088. auto res = cli_.Get("/streamed-chunked", headers);
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::OK_200, res->status);
  7091. EXPECT_EQ(std::string("123456789"), res->body);
  7092. }
  7093. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7094. Headers headers;
  7095. headers.emplace("Accept-Encoding", "gzip, deflate");
  7096. auto res = cli_.Get("/streamed-chunked2", headers);
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::OK_200, res->status);
  7099. EXPECT_EQ(std::string("123456789"), res->body);
  7100. }
  7101. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7102. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::OK_200, res->status);
  7105. }
  7106. TEST(GzipDecompressor, ChunkedDecompression) {
  7107. std::string data;
  7108. for (size_t i = 0; i < 32 * 1024; ++i) {
  7109. data.push_back(static_cast<char>('a' + i % 26));
  7110. }
  7111. std::string compressed_data;
  7112. {
  7113. httplib::detail::gzip_compressor compressor;
  7114. bool result = compressor.compress(
  7115. data.data(), data.size(),
  7116. /*last=*/true,
  7117. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7118. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7119. compressed_data_size);
  7120. return true;
  7121. });
  7122. ASSERT_TRUE(result);
  7123. }
  7124. std::string decompressed_data;
  7125. {
  7126. httplib::detail::gzip_decompressor decompressor;
  7127. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7128. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7129. size_t chunk_size = 130;
  7130. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7131. chunk_begin += chunk_size) {
  7132. size_t current_chunk_size =
  7133. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7134. bool result = decompressor.decompress(
  7135. compressed_data.data() + chunk_begin, current_chunk_size,
  7136. [&](const char *decompressed_data_chunk,
  7137. size_t decompressed_data_chunk_size) {
  7138. decompressed_data.insert(decompressed_data.size(),
  7139. decompressed_data_chunk,
  7140. decompressed_data_chunk_size);
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(result);
  7144. }
  7145. }
  7146. ASSERT_EQ(data, decompressed_data);
  7147. }
  7148. TEST(GzipDecompressor, DeflateDecompression) {
  7149. std::string original_text = "Raw deflate without gzip";
  7150. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7151. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7152. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7153. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7154. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7155. std::string decompressed_data;
  7156. {
  7157. httplib::detail::gzip_decompressor decompressor;
  7158. bool result = decompressor.decompress(
  7159. compressed_data.data(), compressed_data.size(),
  7160. [&](const char *decompressed_data_chunk,
  7161. size_t decompressed_data_chunk_size) {
  7162. decompressed_data.insert(decompressed_data.size(),
  7163. decompressed_data_chunk,
  7164. decompressed_data_chunk_size);
  7165. return true;
  7166. });
  7167. ASSERT_TRUE(result);
  7168. }
  7169. ASSERT_EQ(original_text, decompressed_data);
  7170. }
  7171. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7172. std::string original_text = "Raw deflate without gzip";
  7173. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7174. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7175. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7176. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7177. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7178. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7179. std::string decompressed_data;
  7180. {
  7181. httplib::detail::gzip_decompressor decompressor;
  7182. bool result = decompressor.decompress(
  7183. compressed_data.data(), compressed_data.size(),
  7184. [&](const char *decompressed_data_chunk,
  7185. size_t decompressed_data_chunk_size) {
  7186. decompressed_data.insert(decompressed_data.size(),
  7187. decompressed_data_chunk,
  7188. decompressed_data_chunk_size);
  7189. return true;
  7190. });
  7191. ASSERT_TRUE(result);
  7192. }
  7193. ASSERT_EQ(original_text, decompressed_data);
  7194. }
  7195. #endif
  7196. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7197. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7198. Headers headers;
  7199. headers.emplace("Accept-Encoding", "br");
  7200. auto res = cli_.Get("/streamed-chunked", headers);
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::OK_200, res->status);
  7203. EXPECT_EQ(std::string("123456789"), res->body);
  7204. }
  7205. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7206. Headers headers;
  7207. headers.emplace("Accept-Encoding", "br");
  7208. auto res = cli_.Get("/streamed-chunked2", headers);
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. EXPECT_EQ(std::string("123456789"), res->body);
  7212. }
  7213. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7214. cli_.set_compress(true);
  7215. auto res = cli_.Put(
  7216. "/put", 3,
  7217. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7218. sink.os << "PUT";
  7219. return true;
  7220. },
  7221. "text/plain");
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. EXPECT_EQ("PUT", res->body);
  7225. }
  7226. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7227. cli_.set_compress(true);
  7228. auto res = cli_.Put(
  7229. "/put",
  7230. [](size_t /*offset*/, DataSink &sink) {
  7231. sink.os << "PUT";
  7232. sink.done();
  7233. return true;
  7234. },
  7235. "text/plain");
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::OK_200, res->status);
  7238. EXPECT_EQ("PUT", res->body);
  7239. }
  7240. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7241. cli_.set_compress(true);
  7242. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ(LARGE_DATA, res->body);
  7246. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7247. }
  7248. #endif
  7249. TEST_F(ServerTest, Patch) {
  7250. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7252. EXPECT_EQ(StatusCode::OK_200, res->status);
  7253. EXPECT_EQ("PATCH", res->body);
  7254. }
  7255. TEST_F(ServerTest, Delete) {
  7256. auto res = cli_.Delete("/delete");
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. EXPECT_EQ("DELETE", res->body);
  7260. }
  7261. TEST_F(ServerTest, DeleteContentReceiver) {
  7262. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("content", res->body);
  7266. }
  7267. TEST_F(ServerTest, Options) {
  7268. auto res = cli_.Options("*");
  7269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7270. EXPECT_EQ(StatusCode::OK_200, res->status);
  7271. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7272. EXPECT_TRUE(res->body.empty());
  7273. }
  7274. TEST_F(ServerTest, URL) {
  7275. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7277. EXPECT_EQ(StatusCode::OK_200, res->status);
  7278. }
  7279. TEST_F(ServerTest, ArrayParam) {
  7280. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7282. EXPECT_EQ(StatusCode::OK_200, res->status);
  7283. }
  7284. TEST_F(ServerTest, ArrayParamValues) {
  7285. auto res =
  7286. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. }
  7290. TEST_F(ServerTest, NoMultipleHeaders) {
  7291. Headers headers = {{"Content-Length", "5"}};
  7292. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7293. "text/plain");
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. }
  7297. TEST_F(ServerTest, PostContentReceiver) {
  7298. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. ASSERT_EQ(StatusCode::OK_200, res->status);
  7301. ASSERT_EQ("content", res->body);
  7302. }
  7303. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7304. UploadFormDataItems items = {
  7305. {"text1", "text default", "", ""},
  7306. {"text2", "aωb", "", ""},
  7307. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7308. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7309. {"file3", "", "", "application/octet-stream"},
  7310. };
  7311. auto res = cli_.Post("/content_receiver", items);
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. }
  7315. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7316. UploadFormDataItems items = {
  7317. {"text1", "text default", "", ""},
  7318. {"text2", "aωb", "", ""},
  7319. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7320. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7321. {"file3", "", "", "application/octet-stream"},
  7322. };
  7323. auto boundary = std::string("+++++");
  7324. std::string body;
  7325. for (const auto &item : items) {
  7326. body += "--" + boundary + "\r\n";
  7327. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7328. if (!item.filename.empty()) {
  7329. body += "; filename=\"" + item.filename + "\"";
  7330. }
  7331. body += "\r\n";
  7332. if (!item.content_type.empty()) {
  7333. body += "Content-Type: " + item.content_type + "\r\n";
  7334. }
  7335. body += "\r\n";
  7336. body += item.content + "\r\n";
  7337. }
  7338. body += "--" + boundary + "--\r\n";
  7339. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7340. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. }
  7344. TEST(MultipartFormDataTest, FieldEscaping) {
  7345. Server svr;
  7346. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7347. const ContentReader &content_reader) {
  7348. ASSERT_TRUE(req.is_multipart_form_data());
  7349. std::vector<FormData> received;
  7350. content_reader(
  7351. [&](const FormData &file) {
  7352. received.push_back(file);
  7353. return true;
  7354. },
  7355. [&](const char *data, size_t data_length) {
  7356. received.back().content.append(data, data_length);
  7357. return true;
  7358. });
  7359. // '"', CR and LF in names and filenames are escaped following the
  7360. // WHATWG HTML standard, so each part still parses as a single part
  7361. // with no injected headers. Content types get CR/LF escaped too,
  7362. // while '"' (legal there, e.g. quoted charset) is preserved.
  7363. ASSERT_EQ(4U, received.size());
  7364. EXPECT_EQ("na%22me", received[0].name);
  7365. EXPECT_EQ("quoted name", received[0].content);
  7366. EXPECT_EQ("file", received[1].name);
  7367. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7368. received[1].filename);
  7369. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7370. EXPECT_EQ("injected", received[1].content);
  7371. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7372. EXPECT_EQ("my%22file.txt", received[2].filename);
  7373. EXPECT_EQ("cr lf name", received[2].content);
  7374. EXPECT_EQ("typed", received[3].name);
  7375. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7376. received[3].content_type);
  7377. EXPECT_EQ("typed content", received[3].content);
  7378. });
  7379. auto port = svr.bind_to_any_port("localhost");
  7380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7381. auto se = detail::scope_exit([&] {
  7382. svr.stop();
  7383. t.join();
  7384. ASSERT_FALSE(svr.is_running());
  7385. });
  7386. svr.wait_until_ready();
  7387. Client cli("localhost", port);
  7388. UploadFormDataItems items = {
  7389. {"na\"me", "quoted name", "", ""},
  7390. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7391. "application/octet-stream"},
  7392. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7393. {"typed", "typed content", "",
  7394. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7395. };
  7396. auto res = cli.Post("/post", items);
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. }
  7400. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7401. const UploadFormDataItems items = {
  7402. {"name1", "Content 1", "", ""},
  7403. {"name2", "Content 2", "file2.txt", "text/plain"},
  7404. };
  7405. Server svr;
  7406. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7407. const ContentReader &content_reader) {
  7408. ASSERT_TRUE(req.is_multipart_form_data());
  7409. std::vector<FormData> received;
  7410. content_reader(
  7411. [&](const FormData &file) {
  7412. received.push_back(file);
  7413. return true;
  7414. },
  7415. [&](const char *data, size_t data_length) {
  7416. received.back().content.append(data, data_length);
  7417. return true;
  7418. });
  7419. ASSERT_EQ(2U, received.size());
  7420. EXPECT_EQ("name1", received[0].name);
  7421. EXPECT_EQ("Content 1", received[0].content);
  7422. EXPECT_EQ("name2", received[1].name);
  7423. EXPECT_EQ("Content 2", received[1].content);
  7424. EXPECT_EQ("file2.txt", received[1].filename);
  7425. EXPECT_EQ("text/plain", received[1].content_type);
  7426. });
  7427. auto port = svr.bind_to_any_port("localhost");
  7428. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7429. auto se = detail::scope_exit([&] {
  7430. svr.stop();
  7431. t.join();
  7432. ASSERT_FALSE(svr.is_running());
  7433. });
  7434. svr.wait_until_ready();
  7435. Client cli("localhost", port);
  7436. // Whole-body serialization with a generated boundary
  7437. {
  7438. MultipartFormDataWriter writer;
  7439. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7440. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7441. writer.content_type());
  7442. auto body = writer.serialize(items);
  7443. EXPECT_EQ(body.size(), writer.content_length(items));
  7444. auto res = cli.Post("/post", body, writer.content_type());
  7445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7446. EXPECT_EQ(StatusCode::OK_200, res->status);
  7447. }
  7448. // Per-part framing with a custom boundary via a content provider
  7449. {
  7450. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7451. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7452. MultipartFormDataWriter writer("custom-boundary_123");
  7453. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7454. std::string body;
  7455. for (const auto &item : items) {
  7456. body += writer.item_begin(item);
  7457. body += item.content;
  7458. body += MultipartFormDataWriter::item_end();
  7459. }
  7460. body += writer.finish();
  7461. EXPECT_EQ(body.size(), writer.content_length(items));
  7462. auto res = cli.Post(
  7463. "/post", body.size(),
  7464. [&](size_t offset, size_t length, DataSink &sink) {
  7465. sink.write(body.data() + offset, length);
  7466. return true;
  7467. },
  7468. writer.content_type());
  7469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. }
  7472. }
  7473. TEST_F(ServerTest, PostContentReceiverGzip) {
  7474. cli_.set_compress(true);
  7475. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7477. ASSERT_EQ(StatusCode::OK_200, res->status);
  7478. ASSERT_EQ("content", res->body);
  7479. }
  7480. TEST_F(ServerTest, PutContentReceiver) {
  7481. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7483. ASSERT_EQ(StatusCode::OK_200, res->status);
  7484. ASSERT_EQ("content", res->body);
  7485. }
  7486. TEST_F(ServerTest, PatchContentReceiver) {
  7487. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. ASSERT_EQ(StatusCode::OK_200, res->status);
  7490. ASSERT_EQ("content", res->body);
  7491. }
  7492. template <typename ClientType>
  7493. void TestWithHeadersAndContentReceiver(
  7494. ClientType &cli,
  7495. std::function<Result(ClientType &, const std::string &, const Headers &,
  7496. const std::string &, const std::string &,
  7497. ContentReceiver, DownloadProgress)>
  7498. request_func) {
  7499. Headers headers;
  7500. headers.emplace("X-Custom-Header", "test-value");
  7501. std::string received_body;
  7502. auto res = request_func(
  7503. cli, "/content_receiver", headers, "content", "application/json",
  7504. [&](const char *data, size_t data_length) {
  7505. received_body.append(data, data_length);
  7506. return true;
  7507. },
  7508. nullptr);
  7509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7510. EXPECT_EQ(StatusCode::OK_200, res->status);
  7511. EXPECT_EQ("content", received_body);
  7512. }
  7513. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7514. #ifdef CPPHTTPLIB_SSL_ENABLED
  7515. using ClientT = SSLClient;
  7516. #else
  7517. using ClientT = Client;
  7518. #endif
  7519. TestWithHeadersAndContentReceiver<ClientT>(
  7520. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7521. const std::string &body, const std::string &content_type,
  7522. ContentReceiver receiver, DownloadProgress progress) {
  7523. return cli.Post(path, headers, body, content_type, receiver, progress);
  7524. });
  7525. }
  7526. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7527. #ifdef CPPHTTPLIB_SSL_ENABLED
  7528. using ClientT = SSLClient;
  7529. #else
  7530. using ClientT = Client;
  7531. #endif
  7532. TestWithHeadersAndContentReceiver<ClientT>(
  7533. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7534. const std::string &body, const std::string &content_type,
  7535. ContentReceiver receiver, DownloadProgress progress) {
  7536. return cli.Put(path, headers, body, content_type, receiver, progress);
  7537. });
  7538. }
  7539. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7540. #ifdef CPPHTTPLIB_SSL_ENABLED
  7541. using ClientT = SSLClient;
  7542. #else
  7543. using ClientT = Client;
  7544. #endif
  7545. TestWithHeadersAndContentReceiver<ClientT>(
  7546. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7547. const std::string &body, const std::string &content_type,
  7548. ContentReceiver receiver, DownloadProgress progress) {
  7549. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7550. });
  7551. }
  7552. template <typename ClientType>
  7553. void TestWithHeadersAndContentReceiverWithProgress(
  7554. ClientType &cli,
  7555. std::function<Result(ClientType &, const std::string &, const Headers &,
  7556. const std::string &, const std::string &,
  7557. ContentReceiver, DownloadProgress)>
  7558. request_func) {
  7559. Headers headers;
  7560. headers.emplace("X-Test-Header", "progress-test");
  7561. std::string received_body;
  7562. auto progress_called = false;
  7563. auto res = request_func(
  7564. cli, "/content_receiver", headers, "content", "text/plain",
  7565. [&](const char *data, size_t data_length) {
  7566. received_body.append(data, data_length);
  7567. return true;
  7568. },
  7569. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7570. progress_called = true;
  7571. return true;
  7572. });
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ(StatusCode::OK_200, res->status);
  7575. EXPECT_EQ("content", received_body);
  7576. EXPECT_TRUE(progress_called);
  7577. }
  7578. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7579. #ifdef CPPHTTPLIB_SSL_ENABLED
  7580. using ClientT = SSLClient;
  7581. #else
  7582. using ClientT = Client;
  7583. #endif
  7584. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7585. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7586. const std::string &body, const std::string &content_type,
  7587. ContentReceiver receiver, DownloadProgress progress) {
  7588. return cli.Post(path, headers, body, content_type, receiver, progress);
  7589. });
  7590. }
  7591. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7592. #ifdef CPPHTTPLIB_SSL_ENABLED
  7593. using ClientT = SSLClient;
  7594. #else
  7595. using ClientT = Client;
  7596. #endif
  7597. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7598. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7599. const std::string &body, const std::string &content_type,
  7600. ContentReceiver receiver, DownloadProgress progress) {
  7601. return cli.Put(path, headers, body, content_type, receiver, progress);
  7602. });
  7603. }
  7604. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7605. #ifdef CPPHTTPLIB_SSL_ENABLED
  7606. using ClientT = SSLClient;
  7607. #else
  7608. using ClientT = Client;
  7609. #endif
  7610. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7611. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7612. const std::string &body, const std::string &content_type,
  7613. ContentReceiver receiver, DownloadProgress progress) {
  7614. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7615. });
  7616. }
  7617. template <typename ClientType>
  7618. void TestWithHeadersAndContentReceiverError(
  7619. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7620. const Headers &, const std::string &,
  7621. const std::string &, ContentReceiver)>
  7622. request_func) {
  7623. Headers headers;
  7624. headers.emplace("X-Error-Test", "true");
  7625. std::string received_body;
  7626. auto receiver_failed = false;
  7627. auto res =
  7628. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7629. [&](const char *data, size_t data_length) {
  7630. received_body.append(data, data_length);
  7631. receiver_failed = true;
  7632. return false;
  7633. });
  7634. ASSERT_FALSE(res);
  7635. EXPECT_TRUE(receiver_failed);
  7636. }
  7637. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7638. #ifdef CPPHTTPLIB_SSL_ENABLED
  7639. using ClientT = SSLClient;
  7640. #else
  7641. using ClientT = Client;
  7642. #endif
  7643. TestWithHeadersAndContentReceiverError<ClientT>(
  7644. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7645. const std::string &body, const std::string &content_type,
  7646. ContentReceiver receiver) {
  7647. return cli.Post(path, headers, body, content_type, receiver);
  7648. });
  7649. }
  7650. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7651. #ifdef CPPHTTPLIB_SSL_ENABLED
  7652. using ClientT = SSLClient;
  7653. #else
  7654. using ClientT = Client;
  7655. #endif
  7656. TestWithHeadersAndContentReceiverError<ClientT>(
  7657. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7658. const std::string &body, const std::string &content_type,
  7659. ContentReceiver receiver) {
  7660. return cli.Put(path, headers, body, content_type, receiver);
  7661. });
  7662. }
  7663. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7664. #ifdef CPPHTTPLIB_SSL_ENABLED
  7665. using ClientT = SSLClient;
  7666. #else
  7667. using ClientT = Client;
  7668. #endif
  7669. TestWithHeadersAndContentReceiverError<ClientT>(
  7670. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7671. const std::string &body, const std::string &content_type,
  7672. ContentReceiver receiver) {
  7673. return cli.Patch(path, headers, body, content_type, receiver);
  7674. });
  7675. }
  7676. TEST_F(ServerTest, PostQueryStringAndBody) {
  7677. auto res =
  7678. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. ASSERT_EQ(StatusCode::OK_200, res->status);
  7681. }
  7682. TEST_F(ServerTest, HTTP2Magic) {
  7683. Request req;
  7684. req.method = "PRI";
  7685. req.path = "*";
  7686. req.body = "SM";
  7687. auto res = std::make_shared<Response>();
  7688. auto error = Error::Success;
  7689. auto ret = cli_.send(req, *res, error);
  7690. ASSERT_TRUE(ret);
  7691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7692. }
  7693. TEST_F(ServerTest, KeepAlive) {
  7694. auto res = cli_.Get("/hi");
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ(StatusCode::OK_200, res->status);
  7697. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7698. EXPECT_EQ("Hello World!", res->body);
  7699. res = cli_.Get("/hi");
  7700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7701. EXPECT_EQ(StatusCode::OK_200, res->status);
  7702. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7703. EXPECT_EQ("Hello World!", res->body);
  7704. res = cli_.Get("/hi");
  7705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7706. EXPECT_EQ(StatusCode::OK_200, res->status);
  7707. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7708. EXPECT_EQ("Hello World!", res->body);
  7709. res = cli_.Get("/not-exist");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7712. res = cli_.Post("/empty", "", "text/plain");
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7716. EXPECT_EQ("empty", res->body);
  7717. EXPECT_EQ("close", res->get_header_value("Connection"));
  7718. res = cli_.Post(
  7719. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7720. "text/plain");
  7721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7724. EXPECT_EQ("empty", res->body);
  7725. cli_.set_keep_alive(false);
  7726. res = cli_.Get("/last-request");
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. EXPECT_EQ("close", res->get_header_value("Connection"));
  7730. }
  7731. TEST_F(ServerTest, TooManyRedirect) {
  7732. cli_.set_follow_location(true);
  7733. auto res = cli_.Get("/redirect/0");
  7734. ASSERT_TRUE(!res);
  7735. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7736. }
  7737. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7738. Request req;
  7739. req.method = "FOOBAR";
  7740. req.path = "/hi";
  7741. cli_.set_keep_alive(true);
  7742. auto res = cli_.send(req);
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7745. EXPECT_EQ("close", res->get_header_value("Connection"));
  7746. EXPECT_FALSE(cli_.is_socket_open());
  7747. }
  7748. TEST_F(ServerTest, CustomRouteReadsBody) {
  7749. const std::string xml =
  7750. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7751. Request req;
  7752. req.method = "PROPFIND";
  7753. req.path = "/dav/dir";
  7754. req.set_header("Depth", "1");
  7755. req.body = xml;
  7756. auto res = cli_.send(req);
  7757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7758. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7759. EXPECT_EQ(xml, res->body);
  7760. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7761. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7762. }
  7763. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7764. Request req;
  7765. req.method = "PROPFIND";
  7766. req.path = "/dav/42";
  7767. auto res = cli_.send(req);
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7770. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7771. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7772. }
  7773. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7774. Request req;
  7775. req.method = "PROPFIND";
  7776. req.path = "/dav-re/123";
  7777. auto res = cli_.send(req);
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7780. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7781. }
  7782. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7783. Request req;
  7784. req.method = "MKCOL";
  7785. req.path = "/dav-mkcol";
  7786. auto res = cli_.send(req);
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ(StatusCode::Created_201, res->status);
  7789. }
  7790. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7791. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7792. Request req;
  7793. req.method = "REPORT";
  7794. req.path = "/dav-report";
  7795. req.body = xml;
  7796. auto res = cli_.send(req);
  7797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7798. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7799. EXPECT_EQ(xml, res->body);
  7800. }
  7801. // A content reader route must fire even when the request carries no body,
  7802. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7803. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7804. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7805. Request req;
  7806. req.method = "REPORT";
  7807. req.path = "/dav-report";
  7808. auto res = cli_.send(req);
  7809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7810. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7811. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7812. }
  7813. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7814. Request req;
  7815. req.method = "PROPFIND";
  7816. req.path = "/not-dav";
  7817. auto res = cli_.send(req);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7820. }
  7821. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7822. Request req;
  7823. req.method = "UNLOCK";
  7824. req.path = "/dav/dir";
  7825. cli_.set_keep_alive(true);
  7826. auto res = cli_.send(req);
  7827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7828. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7829. EXPECT_EQ("close", res->get_header_value("Connection"));
  7830. EXPECT_FALSE(cli_.is_socket_open());
  7831. }
  7832. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7833. // The mount point serves this path, but only for GET and HEAD.
  7834. auto get_res = cli_.Get("/dir/index.html");
  7835. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7836. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7837. Request req;
  7838. req.method = "PROPFIND";
  7839. req.path = "/dir/index.html";
  7840. auto res = cli_.send(req);
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7843. }
  7844. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7845. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7846. cli_.set_keep_alive(true);
  7847. for (auto i = 0; i < 2; i++) {
  7848. Request req;
  7849. req.method = "PROPFIND";
  7850. req.path = "/dav/dir";
  7851. req.body = xml;
  7852. auto res = cli_.send(req);
  7853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7854. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7855. EXPECT_EQ(xml, res->body);
  7856. EXPECT_TRUE(cli_.is_socket_open());
  7857. }
  7858. // A built-in method must still be served on the same connection.
  7859. cli_.set_keep_alive(false);
  7860. auto res = cli_.Get("/hi");
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ("close", res->get_header_value("Connection"));
  7864. }
  7865. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7866. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7867. Request req;
  7868. req.method = "PROPFIND";
  7869. req.path = "/dav/dir";
  7870. req.set_header("Expect", "100-continue");
  7871. req.body = xml;
  7872. auto res = cli_.send(req);
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7875. EXPECT_EQ(xml, res->body);
  7876. }
  7877. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7878. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7879. TEST_F(ServerTest, Gzip) {
  7880. Headers headers;
  7881. headers.emplace("Accept-Encoding", "gzip, deflate");
  7882. auto res = cli_.Get("/compress", headers);
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7885. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7886. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7887. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7888. "7890123456789012345678901234567890",
  7889. res->body);
  7890. EXPECT_EQ(StatusCode::OK_200, res->status);
  7891. }
  7892. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7893. Headers headers;
  7894. headers.emplace("Accept-Encoding", "gzip, deflate");
  7895. auto res = cli_.Get("/compress-with-charset", headers);
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7898. EXPECT_EQ("application/json; charset=utf-8",
  7899. res->get_header_value("Content-Type"));
  7900. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7901. "7890123456789012345678901234567890",
  7902. res->body);
  7903. EXPECT_EQ(StatusCode::OK_200, res->status);
  7904. }
  7905. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7906. Headers headers;
  7907. headers.emplace("Accept-Encoding", "");
  7908. auto res = cli_.Get("/compress", headers);
  7909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7910. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7911. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7912. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7913. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7914. "7890123456789012345678901234567890",
  7915. res->body);
  7916. EXPECT_EQ(StatusCode::OK_200, res->status);
  7917. }
  7918. TEST_F(ServerTest, GzipWithContentReceiver) {
  7919. Headers headers;
  7920. headers.emplace("Accept-Encoding", "gzip, deflate");
  7921. std::string body;
  7922. auto res = cli_.Get("/compress", headers,
  7923. [&](const char *data, uint64_t data_length) {
  7924. EXPECT_EQ(100U, data_length);
  7925. body.append(data, data_length);
  7926. return true;
  7927. });
  7928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7929. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7931. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7933. "7890123456789012345678901234567890",
  7934. body);
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. }
  7937. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7938. Headers headers;
  7939. headers.emplace("Accept-Encoding", "gzip, deflate");
  7940. cli_.set_decompress(false);
  7941. auto res = cli_.Get("/compress", headers);
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7945. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7946. EXPECT_EQ(33U, res->body.size());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "");
  7952. std::string body;
  7953. auto res = cli_.Get("/compress", headers,
  7954. [&](const char *data, uint64_t data_length) {
  7955. EXPECT_EQ(100U, data_length);
  7956. body.append(data, data_length);
  7957. return true;
  7958. });
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7961. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7962. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7963. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7964. "7890123456789012345678901234567890",
  7965. body);
  7966. EXPECT_EQ(StatusCode::OK_200, res->status);
  7967. }
  7968. TEST_F(ServerTest, NoGzip) {
  7969. Headers headers;
  7970. headers.emplace("Accept-Encoding", "gzip, deflate");
  7971. auto res = cli_.Get("/nocompress", headers);
  7972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7973. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7974. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7975. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7976. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7977. "7890123456789012345678901234567890",
  7978. res->body);
  7979. EXPECT_EQ(StatusCode::OK_200, res->status);
  7980. }
  7981. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7982. Headers headers;
  7983. headers.emplace("Accept-Encoding", "gzip, deflate");
  7984. std::string body;
  7985. auto res = cli_.Get("/nocompress", headers,
  7986. [&](const char *data, uint64_t data_length) {
  7987. EXPECT_EQ(100U, data_length);
  7988. body.append(data, data_length);
  7989. return true;
  7990. });
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7993. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7996. "7890123456789012345678901234567890",
  7997. body);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. TEST_F(ServerTest, MultipartFormDataGzip) {
  8001. UploadFormDataItems items = {
  8002. {"key1", "test", "", ""},
  8003. {"key2", "--abcdefg123", "", ""},
  8004. };
  8005. cli_.set_compress(true);
  8006. auto res = cli_.Post("/compress-multipart", items);
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. #endif
  8011. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8012. // Static file compression is opt-in, so these run their own server rather than
  8013. // flipping it on for the shared ServerTest fixture, which would silently
  8014. // rewrite what every other static file test is asserting.
  8015. class StaticFileCompressionTest : public ::testing::Test {
  8016. protected:
  8017. void TearDown() override {
  8018. if (t_.joinable()) {
  8019. svr_.stop();
  8020. t_.join();
  8021. }
  8022. }
  8023. int start(const std::function<void(Server &)> &configure = nullptr) {
  8024. // Serves the same tree as a directory of build-time compressed assets
  8025. // would be served: the mount point names the coding the files are already
  8026. // stored in. Registered before "/" so it is the one that matches.
  8027. svr_.set_mount_point("/pre-encoded", "./www",
  8028. {{"Content-Encoding", "gzip"}});
  8029. svr_.set_mount_point("/", "./www");
  8030. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8031. res.set_file_content("./www/dir/index.html", "text/html");
  8032. });
  8033. svr_.Get("/pre-encoded-file-content",
  8034. [](const Request & /*req*/, Response &res) {
  8035. res.set_header("Content-Encoding", "gzip");
  8036. res.set_file_content("./www/dir/index.html", "text/html");
  8037. });
  8038. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8039. res.set_content_provider(
  8040. 6, "text/plain",
  8041. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8042. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8043. return true;
  8044. });
  8045. });
  8046. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8047. res.set_content_provider(
  8048. 1000, "text/plain",
  8049. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8050. if (offset < 100) {
  8051. std::string data(100, 'A');
  8052. sink.write(data.data(), data.size());
  8053. return true;
  8054. }
  8055. std::this_thread::sleep_for(std::chrono::seconds(2));
  8056. std::string data(900, 'B');
  8057. sink.write(data.data(), data.size());
  8058. return true;
  8059. });
  8060. });
  8061. if (configure) { configure(svr_); }
  8062. auto port = svr_.bind_to_any_port(HOST);
  8063. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8064. svr_.wait_until_ready();
  8065. return port;
  8066. }
  8067. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8068. // Every file under ./www except 1MB.txt is smaller than the default
  8069. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8070. // it out of the way.
  8071. static void enable_without_floor(Server &svr) {
  8072. svr.set_static_file_compression(true);
  8073. svr.set_static_file_compression_min_length(0);
  8074. }
  8075. Server svr_;
  8076. std::thread t_;
  8077. };
  8078. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8079. auto port = start();
  8080. Client cli(HOST, port);
  8081. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8085. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8086. EXPECT_EQ(1048576U, res->body.size());
  8087. }
  8088. TEST_F(StaticFileCompressionTest, MountPoint) {
  8089. auto port = start(enable);
  8090. Client cli(HOST, port);
  8091. cli.set_decompress(false);
  8092. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8094. EXPECT_EQ(StatusCode::OK_200, res->status);
  8095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8096. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8097. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8098. // The response stays self-delimiting: a length, not a chunked body.
  8099. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8100. EXPECT_EQ(std::to_string(res->body.size()),
  8101. res->get_header_value("Content-Length"));
  8102. EXPECT_LT(res->body.size(), 1048576U);
  8103. EXPECT_FALSE(res->body.empty());
  8104. }
  8105. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8106. auto port = start(enable);
  8107. Client cli(HOST, port);
  8108. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8110. EXPECT_EQ(StatusCode::OK_200, res->status);
  8111. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8112. EXPECT_EQ(1048576U, res->body.size());
  8113. }
  8114. TEST_F(StaticFileCompressionTest, FileContent) {
  8115. auto port = start(enable_without_floor);
  8116. Client cli(HOST, port);
  8117. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8121. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8122. EXPECT_EQ(104U, res->body.size());
  8123. }
  8124. // A handler that serves an already-encoded file names the coding itself. The
  8125. // file-backed path decided its coding from Accept-Encoding and the content
  8126. // type alone, so it compressed the stored bytes a second time and appended a
  8127. // second Content-Encoding field line.
  8128. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8129. auto port = start(enable_without_floor);
  8130. Client cli(HOST, port);
  8131. cli.set_decompress(false);
  8132. auto res = cli.Get("/pre-encoded-file-content",
  8133. Headers{{"Accept-Encoding", "gzip"}});
  8134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8135. EXPECT_EQ(StatusCode::OK_200, res->status);
  8136. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8137. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8138. // Vary belongs to a coding the server chose, and it chose none here.
  8139. EXPECT_FALSE(res->has_header("Vary"));
  8140. // The file travels exactly as it is stored on disk.
  8141. EXPECT_EQ(104U, res->body.size());
  8142. }
  8143. // The 1MB file clears the default floor, so this one runs the configuration a
  8144. // deployment would actually have.
  8145. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8146. auto port = start(enable);
  8147. Client cli(HOST, port);
  8148. cli.set_decompress(false);
  8149. auto res =
  8150. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8152. EXPECT_EQ(StatusCode::OK_200, res->status);
  8153. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8154. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8155. EXPECT_FALSE(res->has_header("Vary"));
  8156. EXPECT_EQ(1048576U, res->body.size());
  8157. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8158. }
  8159. TEST_F(StaticFileCompressionTest, Head) {
  8160. auto port = start(enable);
  8161. Client cli(HOST, port);
  8162. cli.set_decompress(false);
  8163. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8164. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8165. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8169. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8170. // HEAD still reports the size a GET would return.
  8171. EXPECT_EQ(get->get_header_value("Content-Length"),
  8172. res->get_header_value("Content-Length"));
  8173. EXPECT_TRUE(res->body.empty());
  8174. }
  8175. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8176. auto port = start(enable);
  8177. Client cli(HOST, port);
  8178. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8179. {"Accept-Encoding", "gzip"}});
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8182. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8183. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8184. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8185. EXPECT_EQ("cd", res->body);
  8186. }
  8187. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8188. auto port = start(enable);
  8189. Client cli(HOST, port);
  8190. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8194. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8195. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8196. }
  8197. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8198. auto port = start(enable);
  8199. Client cli(HOST, port);
  8200. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::OK_200, res->status);
  8203. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8204. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8205. EXPECT_TRUE(res->body.empty());
  8206. }
  8207. TEST_F(StaticFileCompressionTest, MinLength) {
  8208. auto port = start(enable);
  8209. Client cli(HOST, port);
  8210. // 104 bytes, well under the default floor. Compressing it would add the
  8211. // gzip header and trailer to a body that already fits in one packet.
  8212. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ(StatusCode::OK_200, res->status);
  8215. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8216. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8217. }
  8218. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8219. auto port = start([](Server &svr) {
  8220. svr.set_static_file_compression(true);
  8221. svr.set_static_file_compression_min_length(1);
  8222. });
  8223. Client cli(HOST, port);
  8224. cli.set_decompress(false);
  8225. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8227. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8228. // A 9-byte file comes back larger than it went in, because gzip's header and
  8229. // trailer outweigh anything deflate can save. That is the end of the range
  8230. // the floor exists to keep out.
  8231. EXPECT_GT(res->body.size(), 9U);
  8232. }
  8233. TEST_F(StaticFileCompressionTest, MaxLength) {
  8234. auto port = start([](Server &svr) {
  8235. svr.set_static_file_compression(true);
  8236. svr.set_static_file_compression_min_length(0);
  8237. svr.set_static_file_compression_max_length(1024);
  8238. });
  8239. Client cli(HOST, port);
  8240. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8241. // defines `small` as a macro on Windows.
  8242. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8243. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8244. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8245. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8246. // Under it: compressed.
  8247. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8248. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8249. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8250. }
  8251. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8252. auto port = start(enable_without_floor);
  8253. Client cli(HOST, port);
  8254. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8255. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8256. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8257. auto identity_etag = identity->get_header_value("ETag");
  8258. ASSERT_FALSE(identity_etag.empty());
  8259. auto gzipped =
  8260. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8261. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8262. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8263. auto gzip_etag = gzipped->get_header_value("ETag");
  8264. ASSERT_FALSE(gzip_etag.empty());
  8265. // Two representations, two validators.
  8266. EXPECT_NE(identity_etag, gzip_etag);
  8267. // Each one revalidates against the request that would produce it...
  8268. auto fresh =
  8269. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8270. {"If-None-Match", gzip_etag}});
  8271. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8272. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8273. auto fresh_identity =
  8274. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8275. {"If-None-Match", identity_etag}});
  8276. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8277. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8278. // ...and not against the other representation.
  8279. auto crossed =
  8280. cli.Get("/dir/index.html",
  8281. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8282. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8283. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8284. }
  8285. // The opt-in covers responses the server reads off disk itself. A caller's own
  8286. // known-length provider keeps its Content-Length and, more importantly, keeps
  8287. // delivering incrementally: routing it through a compressor would hold every
  8288. // write back until zlib's window filled.
  8289. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8290. auto port = start(enable);
  8291. Client cli(HOST, port);
  8292. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8294. EXPECT_EQ(StatusCode::OK_200, res->status);
  8295. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8296. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8297. EXPECT_EQ("aaabbb", res->body);
  8298. }
  8299. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8300. auto port = start(enable);
  8301. Client cli(HOST, port);
  8302. cli.set_read_timeout(1, 0);
  8303. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8304. Headers{{"Accept-Encoding", "gzip"}});
  8305. ASSERT_TRUE(handle.is_valid());
  8306. // The provider writes 100 bytes and then stalls for longer than the read
  8307. // timeout. Those first bytes have to arrive anyway: run the response through
  8308. // a compressor and zlib holds them until its window fills, so the read would
  8309. // come back empty instead.
  8310. char buf[256];
  8311. auto n = handle.read(buf, sizeof(buf));
  8312. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8313. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8314. }
  8315. #endif
  8316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8317. TEST_F(ServerTest, Brotli) {
  8318. Headers headers;
  8319. headers.emplace("Accept-Encoding", "br");
  8320. auto res = cli_.Get("/compress", headers);
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8323. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8324. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8325. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8326. "7890123456789012345678901234567890",
  8327. res->body);
  8328. EXPECT_EQ(StatusCode::OK_200, res->status);
  8329. }
  8330. #endif
  8331. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8332. TEST_F(ServerTest, Zstd) {
  8333. Headers headers;
  8334. headers.emplace("Accept-Encoding", "zstd");
  8335. auto res = cli_.Get("/compress", headers);
  8336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8340. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8341. "7890123456789012345678901234567890",
  8342. res->body);
  8343. EXPECT_EQ(StatusCode::OK_200, res->status);
  8344. }
  8345. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8346. Headers headers;
  8347. headers.emplace("Accept-Encoding", "");
  8348. auto res = cli_.Get("/compress", headers);
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8352. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8353. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8354. "7890123456789012345678901234567890",
  8355. res->body);
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. }
  8358. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8359. Headers headers;
  8360. headers.emplace("Accept-Encoding", "zstd");
  8361. std::string body;
  8362. auto res = cli_.Get("/compress", headers,
  8363. [&](const char *data, uint64_t data_length) {
  8364. EXPECT_EQ(100U, data_length);
  8365. body.append(data, data_length);
  8366. return true;
  8367. });
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8371. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8372. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8373. "7890123456789012345678901234567890",
  8374. body);
  8375. EXPECT_EQ(StatusCode::OK_200, res->status);
  8376. }
  8377. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8378. Headers headers;
  8379. headers.emplace("Accept-Encoding", "zstd");
  8380. cli_.set_decompress(false);
  8381. auto res = cli_.Get("/compress", headers);
  8382. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8383. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8384. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8385. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8388. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8389. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. ASSERT_EQ(26U, res->body.size());
  8392. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8393. 0);
  8394. }
  8395. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8396. Headers headers;
  8397. headers.emplace("Accept-Encoding", "");
  8398. std::string body;
  8399. auto res = cli_.Get("/compress", headers,
  8400. [&](const char *data, uint64_t data_length) {
  8401. EXPECT_EQ(100U, data_length);
  8402. body.append(data, data_length);
  8403. return true;
  8404. });
  8405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8406. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8408. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8409. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8410. "7890123456789012345678901234567890",
  8411. body);
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. }
  8414. TEST_F(ServerTest, NoZstd) {
  8415. Headers headers;
  8416. headers.emplace("Accept-Encoding", "zstd");
  8417. auto res = cli_.Get("/nocompress", headers);
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8420. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8421. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8423. "7890123456789012345678901234567890",
  8424. res->body);
  8425. EXPECT_EQ(StatusCode::OK_200, res->status);
  8426. }
  8427. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8428. Headers headers;
  8429. headers.emplace("Accept-Encoding", "zstd");
  8430. std::string body;
  8431. auto res = cli_.Get("/nocompress", headers,
  8432. [&](const char *data, uint64_t data_length) {
  8433. EXPECT_EQ(100U, data_length);
  8434. body.append(data, data_length);
  8435. return true;
  8436. });
  8437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8438. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8439. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8440. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8441. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8442. "7890123456789012345678901234567890",
  8443. body);
  8444. EXPECT_EQ(StatusCode::OK_200, res->status);
  8445. }
  8446. // TODO: How to enable zstd ??
  8447. TEST_F(ServerTest, MultipartFormDataZstd) {
  8448. UploadFormDataItems items = {
  8449. {"key1", "test", "", ""},
  8450. {"key2", "--abcdefg123", "", ""},
  8451. };
  8452. Headers headers;
  8453. headers.emplace("Accept-Encoding", "zstd");
  8454. cli_.set_compress(true);
  8455. auto res = cli_.Post("/compress-multipart", headers, items);
  8456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8457. EXPECT_EQ(StatusCode::OK_200, res->status);
  8458. }
  8459. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8460. Headers headers;
  8461. headers.emplace("Accept-Encoding", "zstd");
  8462. cli_.set_compress(true);
  8463. auto res = cli_.Put(
  8464. "/put", headers, 3,
  8465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8466. sink.os << "PUT";
  8467. return true;
  8468. },
  8469. "text/plain");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_EQ(StatusCode::OK_200, res->status);
  8472. EXPECT_EQ("PUT", res->body);
  8473. }
  8474. // Pre-compression logging tests
  8475. TEST_F(ServerTest, PreCompressionLogging) {
  8476. // Test data for compression (matches the actual /compress endpoint content)
  8477. const std::string test_content =
  8478. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8479. "3456789012345678901234567890";
  8480. // Variables to capture logging data
  8481. std::string pre_compression_body;
  8482. std::string pre_compression_content_type;
  8483. std::string pre_compression_content_encoding;
  8484. std::string post_compression_body;
  8485. std::string post_compression_content_type;
  8486. std::string post_compression_content_encoding;
  8487. // Set up pre-compression logger
  8488. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8489. const Response &res) {
  8490. pre_compression_body = res.body;
  8491. pre_compression_content_type = res.get_header_value("Content-Type");
  8492. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8493. });
  8494. // Set up post-compression logger
  8495. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8496. post_compression_body = res.body;
  8497. post_compression_content_type = res.get_header_value("Content-Type");
  8498. post_compression_content_encoding =
  8499. res.get_header_value("Content-Encoding");
  8500. });
  8501. // Test with gzip compression
  8502. Headers headers;
  8503. headers.emplace("Accept-Encoding", "gzip");
  8504. auto res = cli_.Get("/compress", headers);
  8505. // Verify response was compressed
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::OK_200, res->status);
  8508. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8509. // Verify pre-compression logger captured uncompressed content
  8510. EXPECT_EQ(test_content, pre_compression_body);
  8511. EXPECT_EQ("text/plain", pre_compression_content_type);
  8512. EXPECT_TRUE(pre_compression_content_encoding
  8513. .empty()); // No encoding header before compression
  8514. // Verify post-compression logger captured compressed content
  8515. EXPECT_NE(test_content,
  8516. post_compression_body); // Should be different after compression
  8517. EXPECT_EQ("text/plain", post_compression_content_type);
  8518. EXPECT_EQ("gzip", post_compression_content_encoding);
  8519. // Verify compressed content is smaller
  8520. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8521. }
  8522. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8523. const std::string test_content =
  8524. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8525. "3456789012345678901234567890";
  8526. std::string pre_compression_body;
  8527. std::string post_compression_body;
  8528. svr_.set_pre_compression_logger(
  8529. [&](const Request & /*req*/, const Response &res) {
  8530. pre_compression_body = res.body;
  8531. });
  8532. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8533. post_compression_body = res.body;
  8534. });
  8535. Headers headers;
  8536. headers.emplace("Accept-Encoding", "br");
  8537. auto res = cli_.Get("/compress", headers);
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ(StatusCode::OK_200, res->status);
  8540. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8541. // Verify pre-compression content is uncompressed
  8542. EXPECT_EQ(test_content, pre_compression_body);
  8543. // Verify post-compression content is compressed
  8544. EXPECT_NE(test_content, post_compression_body);
  8545. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8546. }
  8547. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8548. const std::string test_content =
  8549. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8550. "3456789012345678901234567890";
  8551. std::string pre_compression_body;
  8552. std::string post_compression_body;
  8553. svr_.set_pre_compression_logger(
  8554. [&](const Request & /*req*/, const Response &res) {
  8555. pre_compression_body = res.body;
  8556. });
  8557. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8558. post_compression_body = res.body;
  8559. });
  8560. // Request without compression (use /nocompress endpoint)
  8561. Headers headers;
  8562. auto res = cli_.Get("/nocompress", headers);
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::OK_200, res->status);
  8565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8566. // Pre-compression logger should not be called when no compression is applied
  8567. EXPECT_TRUE(
  8568. pre_compression_body.empty()); // Pre-compression logger not called
  8569. EXPECT_EQ(
  8570. test_content,
  8571. post_compression_body); // Post-compression logger captures final content
  8572. }
  8573. TEST_F(ServerTest, LoggerSeesContentLength) {
  8574. size_t logged_content_length = 0;
  8575. std::string logged_content_length_header;
  8576. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8577. logged_content_length = res.content_length_;
  8578. logged_content_length_header = res.get_header_value("Content-Length");
  8579. });
  8580. auto res = cli_.Get("/nocompress");
  8581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8582. EXPECT_EQ(StatusCode::OK_200, res->status);
  8583. EXPECT_EQ(res->body.size(), logged_content_length);
  8584. EXPECT_EQ(std::to_string(logged_content_length),
  8585. logged_content_length_header);
  8586. }
  8587. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8588. const std::string test_content =
  8589. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8590. "3456789012345678901234567890";
  8591. std::string pre_compression_body;
  8592. bool pre_logger_called = false;
  8593. // Set only pre-compression logger
  8594. svr_.set_pre_compression_logger(
  8595. [&](const Request & /*req*/, const Response &res) {
  8596. pre_compression_body = res.body;
  8597. pre_logger_called = true;
  8598. });
  8599. Headers headers;
  8600. headers.emplace("Accept-Encoding", "gzip");
  8601. auto res = cli_.Get("/compress", headers);
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8605. // Verify pre-compression logger was called
  8606. EXPECT_TRUE(pre_logger_called);
  8607. EXPECT_EQ(test_content, pre_compression_body);
  8608. }
  8609. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8610. {
  8611. // Test with Expect: 100-continue header - success case
  8612. // Server returns 100 Continue, client sends body, server returns 200 OK
  8613. Request req;
  8614. req.method = "POST";
  8615. req.path = "/post-large";
  8616. req.set_header("Expect", "100-continue");
  8617. req.body = LARGE_DATA;
  8618. Response res;
  8619. auto error = Error::Success;
  8620. cli_.set_keep_alive(true);
  8621. auto ret = cli_.send(req, res, error);
  8622. EXPECT_TRUE(ret);
  8623. EXPECT_EQ(StatusCode::OK_200, res.status);
  8624. EXPECT_EQ(LARGE_DATA, res.body);
  8625. }
  8626. {
  8627. // Test with Expect: 100-continue header - error case
  8628. // Client should not send the body when server returns an error
  8629. Request req;
  8630. req.method = "POST";
  8631. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8632. req.set_header("Expect", "100-continue");
  8633. req.body = LARGE_DATA;
  8634. Response res;
  8635. auto error = Error::Success;
  8636. auto start = std::chrono::high_resolution_clock::now();
  8637. cli_.set_keep_alive(true);
  8638. auto ret = cli_.send(req, res, error);
  8639. auto end = std::chrono::high_resolution_clock::now();
  8640. auto elapsed =
  8641. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8642. .count();
  8643. // With Expect: 100-continue, request completes successfully but with error
  8644. EXPECT_TRUE(ret);
  8645. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8646. EXPECT_EQ("close", res.get_header_value("Connection"));
  8647. EXPECT_FALSE(cli_.is_socket_open());
  8648. EXPECT_LE(elapsed, 2000);
  8649. }
  8650. {
  8651. // Send an extra GET request to ensure error recovery without hanging
  8652. Request req;
  8653. req.method = "GET";
  8654. req.path = "/hi";
  8655. auto start = std::chrono::high_resolution_clock::now();
  8656. auto res = cli_.send(req);
  8657. auto end = std::chrono::high_resolution_clock::now();
  8658. auto elapsed =
  8659. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8660. .count();
  8661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8662. EXPECT_EQ(StatusCode::OK_200, res->status);
  8663. EXPECT_EQ("Hello World!", res->body);
  8664. EXPECT_LE(elapsed, 500);
  8665. }
  8666. }
  8667. TEST(ZstdDecompressor, ChunkedDecompression) {
  8668. std::string data;
  8669. for (size_t i = 0; i < 32 * 1024; ++i) {
  8670. data.push_back(static_cast<char>('a' + i % 26));
  8671. }
  8672. std::string compressed_data;
  8673. {
  8674. httplib::detail::zstd_compressor compressor;
  8675. bool result = compressor.compress(
  8676. data.data(), data.size(),
  8677. /*last=*/true,
  8678. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8679. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8680. compressed_data_size);
  8681. return true;
  8682. });
  8683. ASSERT_TRUE(result);
  8684. }
  8685. std::string decompressed_data;
  8686. {
  8687. httplib::detail::zstd_decompressor decompressor;
  8688. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8689. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8690. size_t chunk_size = 130;
  8691. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8692. chunk_begin += chunk_size) {
  8693. size_t current_chunk_size =
  8694. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8695. bool result = decompressor.decompress(
  8696. compressed_data.data() + chunk_begin, current_chunk_size,
  8697. [&](const char *decompressed_data_chunk,
  8698. size_t decompressed_data_chunk_size) {
  8699. decompressed_data.insert(decompressed_data.size(),
  8700. decompressed_data_chunk,
  8701. decompressed_data_chunk_size);
  8702. return true;
  8703. });
  8704. ASSERT_TRUE(result);
  8705. }
  8706. }
  8707. ASSERT_EQ(data, decompressed_data);
  8708. }
  8709. TEST(ZstdDecompressor, Decompress) {
  8710. std::string original_text = "Compressed with ZSTD";
  8711. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8712. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8713. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8714. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8715. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8716. std::string decompressed_data;
  8717. {
  8718. httplib::detail::zstd_decompressor decompressor;
  8719. bool result = decompressor.decompress(
  8720. compressed_data.data(), compressed_data.size(),
  8721. [&](const char *decompressed_data_chunk,
  8722. size_t decompressed_data_chunk_size) {
  8723. decompressed_data.insert(decompressed_data.size(),
  8724. decompressed_data_chunk,
  8725. decompressed_data_chunk_size);
  8726. return true;
  8727. });
  8728. ASSERT_TRUE(result);
  8729. }
  8730. ASSERT_EQ(original_text, decompressed_data);
  8731. }
  8732. #endif
  8733. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8734. // separate chunks so that the server sees each part in its own read(). Used to
  8735. // place a read boundary at a specific offset of a request body.
  8736. static bool send_request_in_parts(time_t read_timeout_sec,
  8737. const std::vector<std::string> &parts,
  8738. std::string *resp = nullptr,
  8739. int port = PORT) {
  8740. auto error = Error::Success;
  8741. auto client_sock = detail::create_client_socket(
  8742. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8743. /*connection_timeout_sec=*/5, 0,
  8744. /*read_timeout_sec=*/5, 0,
  8745. /*write_timeout_sec=*/5, 0, std::string(), error);
  8746. if (client_sock == INVALID_SOCKET) { return false; }
  8747. auto ret = detail::process_client_socket(
  8748. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8749. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8750. for (size_t i = 0; i < parts.size(); i++) {
  8751. const auto &part = parts[i];
  8752. if (part.size() !=
  8753. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8754. return false;
  8755. }
  8756. if (i + 1 < parts.size()) {
  8757. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8758. }
  8759. }
  8760. char buf[512];
  8761. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8762. while (line_reader.getline()) {
  8763. if (resp) { *resp += line_reader.ptr(); }
  8764. }
  8765. return true;
  8766. });
  8767. detail::close_socket(client_sock);
  8768. return ret;
  8769. }
  8770. // Sends a raw request to a server listening at HOST:PORT.
  8771. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8772. std::string *resp = nullptr, int port = PORT) {
  8773. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8774. }
  8775. #ifdef CPPHTTPLIB_SSL_ENABLED
  8776. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8778. ASSERT_TRUE(svr.is_valid());
  8779. svr.set_read_timeout(1, 0);
  8780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8781. auto se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. t.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8788. // keeps each wait well within the read timeout. The server gives up a
  8789. // second in, so the bytes sent after that fail.
  8790. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8791. parts.resize(26, std::string(1, '\0'));
  8792. EXPECT_FALSE(send_request_in_parts(5, parts));
  8793. }
  8794. #endif
  8795. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8796. Server svr;
  8797. std::string header_value;
  8798. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8799. header_value = req.get_header_value("foo");
  8800. res.set_content("ok", "text/plain");
  8801. });
  8802. thread t = thread([&] { svr.listen(HOST, PORT); });
  8803. auto se = detail::scope_exit([&] {
  8804. svr.stop();
  8805. t.join();
  8806. ASSERT_FALSE(svr.is_running());
  8807. });
  8808. svr.wait_until_ready();
  8809. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8810. // like characters are not treated the same - use vertical tab and escape.
  8811. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8812. "foo: \t \v bar \x1B\t \r\n"
  8813. "Connection: close\r\n"
  8814. "\r\n";
  8815. std::string res;
  8816. ASSERT_TRUE(send_request(5, req, &res));
  8817. EXPECT_EQ(header_value, "");
  8818. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8819. }
  8820. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8821. Server svr;
  8822. std::string received;
  8823. svr.Get("/order", [&](const Request &req, Response &res) {
  8824. received = entries_to_string(req.headers);
  8825. res.set_content("ok", "text/plain");
  8826. });
  8827. auto port = svr.bind_to_any_port(HOST);
  8828. thread t = thread([&] { svr.listen_after_bind(); });
  8829. auto se = detail::scope_exit([&] {
  8830. svr.stop();
  8831. t.join();
  8832. ASSERT_FALSE(svr.is_running());
  8833. });
  8834. svr.wait_until_ready();
  8835. const std::string req = "GET /order HTTP/1.1\r\n"
  8836. "Host: localhost\r\n"
  8837. "X-First: 1\r\n"
  8838. "X-Dup: a\r\n"
  8839. "X-Second: 2\r\n"
  8840. "X-Dup: b\r\n"
  8841. "Connection: close\r\n"
  8842. "\r\n";
  8843. std::string res;
  8844. ASSERT_TRUE(send_request(5, req, &res, port));
  8845. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8846. EXPECT_EQ(
  8847. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8848. received);
  8849. }
  8850. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8851. Server svr;
  8852. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8853. res.set_header("Set-Cookie", "first=1");
  8854. res.set_header("X-Between", "y");
  8855. res.set_header("Set-Cookie", "second=2");
  8856. res.set_content("ok", "text/plain");
  8857. });
  8858. auto port = svr.bind_to_any_port(HOST);
  8859. thread t = thread([&] { svr.listen_after_bind(); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. Client cli(HOST, port);
  8867. auto res = cli.Get("/cookies");
  8868. ASSERT_TRUE(res);
  8869. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8870. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8871. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8872. }
  8873. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8874. Server svr;
  8875. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8876. auto i = new int(0);
  8877. res.set_header("Trailer", "X-Safe, X-Reflected");
  8878. res.set_chunked_content_provider(
  8879. "text/plain",
  8880. [i](size_t /*offset*/, DataSink &sink) {
  8881. if (*i == 0) {
  8882. sink.os << "body";
  8883. } else {
  8884. Headers trailer;
  8885. // A valid trailer that must survive.
  8886. trailer.emplace("X-Safe", "safe");
  8887. // Attacker-controlled value carrying CR/LF (response splitting).
  8888. trailer.emplace("X-Reflected",
  8889. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8890. // Attacker-controlled name carrying CR/LF.
  8891. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8892. sink.done_with_trailer(trailer);
  8893. }
  8894. (*i)++;
  8895. return true;
  8896. },
  8897. [i](bool /*success*/) { delete i; });
  8898. });
  8899. thread t = thread([&] { svr.listen(HOST, PORT); });
  8900. auto se = detail::scope_exit([&] {
  8901. svr.stop();
  8902. t.join();
  8903. ASSERT_FALSE(svr.is_running());
  8904. });
  8905. svr.wait_until_ready();
  8906. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8907. "Host: " + HOST +
  8908. "\r\n"
  8909. "Connection: close\r\n"
  8910. "\r\n";
  8911. std::string res;
  8912. ASSERT_TRUE(send_request(5, req, &res));
  8913. // The injected fields must not appear anywhere in the raw response.
  8914. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8915. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8916. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8917. // Invalid trailers are dropped entirely, matching set_header().
  8918. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8919. // The valid trailer still passes through.
  8920. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8921. }
  8922. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8923. Server svr;
  8924. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8925. // res.headers is a public field an application can populate directly,
  8926. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8927. // A valid header that must survive.
  8928. res.headers.emplace("X-Safe", "safe");
  8929. // Attacker-controlled value carrying CR/LF (response splitting).
  8930. res.headers.emplace("X-Reflected",
  8931. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8932. // Attacker-controlled name carrying CR/LF.
  8933. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8934. res.set_content("body", "text/plain");
  8935. });
  8936. thread t = thread([&] { svr.listen(HOST, PORT); });
  8937. auto se = detail::scope_exit([&] {
  8938. svr.stop();
  8939. t.join();
  8940. ASSERT_FALSE(svr.is_running());
  8941. });
  8942. svr.wait_until_ready();
  8943. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8944. "Host: " + HOST +
  8945. "\r\n"
  8946. "Connection: close\r\n"
  8947. "\r\n";
  8948. std::string res;
  8949. ASSERT_TRUE(send_request(5, req, &res));
  8950. // The injected fields must not appear anywhere in the raw response.
  8951. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8952. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8953. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8954. // Invalid headers are dropped entirely, matching set_header().
  8955. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8956. // The valid header still passes through.
  8957. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8958. }
  8959. // Forward declaration: in split builds split.py strips `inline` and moves the
  8960. // definition into httplib.cc, so detail::write_request_line is not visible from
  8961. // the public httplib.h. Re-declaring it here lets the tests link against the
  8962. // symbol in both header-only and split builds.
  8963. namespace httplib {
  8964. namespace detail {
  8965. ssize_t write_request_line(Stream &strm, const std::string &method,
  8966. const std::string &path);
  8967. } // namespace detail
  8968. } // namespace httplib
  8969. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8970. // A well-formed target is written verbatim.
  8971. {
  8972. detail::BufferStream strm;
  8973. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8974. EXPECT_GT(n, 0);
  8975. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8976. }
  8977. // A target carrying CR/LF, SP or other control octets must be rejected
  8978. // before anything reaches the wire, otherwise it splits the request line and
  8979. // injects a header or a whole request.
  8980. const std::string evil_targets[] = {
  8981. "/a\r\nInjected: pwned",
  8982. "/a\rInjected",
  8983. "/a\nInjected",
  8984. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8985. "/a b",
  8986. "/a\tb",
  8987. "/a\x7f",
  8988. };
  8989. for (const auto &evil : evil_targets) {
  8990. detail::BufferStream strm;
  8991. auto n = detail::write_request_line(strm, "GET", evil);
  8992. EXPECT_LT(n, 0);
  8993. EXPECT_TRUE(strm.get_buffer().empty());
  8994. }
  8995. }
  8996. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8997. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8998. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8999. // target reaches write_request. The client must fail cleanly with
  9000. // Error::Write instead of putting a request-line-less, header-injecting
  9001. // request on the wire.
  9002. Server svr;
  9003. svr.Get("/a", [](const Request &, Response &res) {
  9004. res.set_content("ok", "text/plain");
  9005. });
  9006. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9007. auto se = detail::scope_exit([&] {
  9008. svr.stop();
  9009. thread.join();
  9010. ASSERT_FALSE(svr.is_running());
  9011. });
  9012. svr.wait_until_ready();
  9013. {
  9014. Client cli(HOST, PORT);
  9015. cli.set_path_encode(false);
  9016. // The request is rejected before anything is written, so the connection
  9017. // stays silent and the subsequent response read would otherwise block for
  9018. // the full default read timeout. Shorten it -- the assertion is on the
  9019. // error, not the timeout.
  9020. cli.set_read_timeout(1, 0);
  9021. auto res = cli.Get("/a\r\nInjected: pwned");
  9022. EXPECT_FALSE(res);
  9023. EXPECT_EQ(Error::Write, res.error());
  9024. }
  9025. }
  9026. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9027. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9028. // including extension methods.
  9029. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9030. for (const auto &method : good_methods) {
  9031. detail::BufferStream strm;
  9032. auto n = detail::write_request_line(strm, method, "/");
  9033. EXPECT_GT(n, 0);
  9034. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9035. }
  9036. // A method carrying CR/LF would split the request line and smuggle a whole
  9037. // request ahead of the real one. A space or an empty method corrupts the
  9038. // request line. All must be rejected before anything reaches the wire.
  9039. const std::string evil_methods[] = {
  9040. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9041. "GET\r\nInjected: pwned",
  9042. "GET\r",
  9043. "GET\n",
  9044. "GE T",
  9045. "",
  9046. };
  9047. for (const auto &evil : evil_methods) {
  9048. detail::BufferStream strm;
  9049. auto n = detail::write_request_line(strm, evil, "/");
  9050. EXPECT_LT(n, 0);
  9051. EXPECT_TRUE(strm.get_buffer().empty());
  9052. }
  9053. }
  9054. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9055. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9056. // through Client::send must fail with Error::Write and no request, neither
  9057. // the smuggled one nor the real one, may reach the server.
  9058. Server svr;
  9059. std::atomic<int> request_count(0);
  9060. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9061. request_count++;
  9062. res.status = StatusCode::OK_200;
  9063. return Server::HandlerResponse::Handled;
  9064. });
  9065. auto port = svr.bind_to_any_port(HOST);
  9066. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9067. auto se = detail::scope_exit([&] {
  9068. svr.stop();
  9069. thread.join();
  9070. ASSERT_FALSE(svr.is_running());
  9071. });
  9072. svr.wait_until_ready();
  9073. {
  9074. Client cli(HOST, port);
  9075. const std::string evil_methods[] = {
  9076. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9077. "GE T",
  9078. "",
  9079. };
  9080. for (const auto &evil : evil_methods) {
  9081. Request req;
  9082. req.method = evil;
  9083. req.path = "/";
  9084. auto res = cli.send(req);
  9085. EXPECT_FALSE(res);
  9086. EXPECT_EQ(Error::Write, res.error());
  9087. }
  9088. auto handle =
  9089. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9090. EXPECT_FALSE(handle.is_valid());
  9091. EXPECT_EQ(Error::Write, handle.error);
  9092. // A valid request on the same client still goes through.
  9093. auto res = cli.Get("/");
  9094. ASSERT_TRUE(res);
  9095. EXPECT_EQ(StatusCode::OK_200, res->status);
  9096. }
  9097. EXPECT_EQ(1, request_count.load());
  9098. }
  9099. // Sends a raw request and verifies that there isn't a crash or exception.
  9100. static void test_raw_request(const std::string &req,
  9101. std::string *out = nullptr) {
  9102. Server svr;
  9103. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9104. res.set_content("ok", "text/plain");
  9105. });
  9106. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9107. res.set_content("ok", "text/plain");
  9108. });
  9109. svr.Get("/header_field_value_check",
  9110. [&](const Request & /*req*/, Response &res) {
  9111. res.set_content("ok", "text/plain");
  9112. });
  9113. svr.CustomRoute("PROPFIND", "/dav",
  9114. [&](const Request & /*req*/, Response &res) {
  9115. res.status = StatusCode::MultiStatus_207;
  9116. });
  9117. // Server read timeout must be longer than the client read timeout for the
  9118. // bug to reproduce, probably to force the server to process a request
  9119. // without a trailing blank line.
  9120. const time_t client_read_timeout_sec = 1;
  9121. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9122. bool listen_thread_ok = false;
  9123. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. t.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. EXPECT_TRUE(listen_thread_ok);
  9129. });
  9130. svr.wait_until_ready();
  9131. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9132. }
  9133. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9134. // A certain header line causes an exception if the header property is parsed
  9135. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9136. test_raw_request(
  9137. "GET /hi HTTP/1.1\r\n"
  9138. " : "
  9139. " "
  9140. " ");
  9141. }
  9142. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9143. // A certain header line causes an exception if the header property *name* is
  9144. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9145. // greedy matcher and requires backtracking when there are a lot of ":"
  9146. // characters.
  9147. // This occurs with libc++ but not libstdc++.
  9148. test_raw_request(
  9149. "GET /hi HTTP/1.1\r\n"
  9150. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9151. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9152. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9153. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9154. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9155. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9156. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9157. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9158. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9159. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9160. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9161. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9162. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9163. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9164. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9165. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9166. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9167. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9168. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9169. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9170. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9171. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9172. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9173. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9174. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9175. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9176. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9177. "&&&%%%");
  9178. }
  9179. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9180. // Make sure this doesn't crash the server.
  9181. // In a previous version of the header line regex, the "\r" rendered the line
  9182. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9183. // a new position where the leading white space ended and the field value
  9184. // began.
  9185. // The crash occurs with libc++ but not libstdc++.
  9186. test_raw_request("GET /hi HTTP/1.1\r\n"
  9187. "a:" +
  9188. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9189. "\r\n"
  9190. "\r\n");
  9191. }
  9192. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9193. const char *rejected[] = {
  9194. // RFC 9112 §3: one SP between the parts, and nothing else
  9195. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9196. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9197. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9198. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9199. // A request-target has no fragment
  9200. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9201. // An HTTP/1.1 request needs a Host
  9202. "GET /hi HTTP/1.1\r\n\r\n",
  9203. };
  9204. for (auto request : rejected) {
  9205. std::string out;
  9206. test_raw_request(request, &out);
  9207. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9208. }
  9209. std::string out;
  9210. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9211. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9212. }
  9213. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9214. // RFC 9112 §6.1
  9215. const char *requests[] = {
  9216. "PUT /put_hi HTTP/1.1\r\n"
  9217. "Host: localhost\r\n"
  9218. "Content-Length: 0\r\n"
  9219. "Transfer-Encoding: chunked\r\n"
  9220. "\r\n"
  9221. "0\r\n\r\n",
  9222. "PUT /put_hi HTTP/1.0\r\n"
  9223. "Connection: keep-alive\r\n"
  9224. "Transfer-Encoding: chunked\r\n"
  9225. "\r\n"
  9226. "0\r\n\r\n",
  9227. };
  9228. for (auto request : requests) {
  9229. std::string out;
  9230. test_raw_request(request, &out);
  9231. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9232. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9233. }
  9234. }
  9235. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9236. std::string out;
  9237. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9238. "Content-Type: text/plain\r\n"
  9239. "Transfer-Encoding: chunked\r\n"
  9240. "\r\n"
  9241. "nothex\r\n",
  9242. &out);
  9243. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9244. }
  9245. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9246. std::string out;
  9247. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9248. "Content-Type: text/plain\r\n"
  9249. "Transfer-Encoding: chunked\r\n"
  9250. "\r\n"
  9251. "3\r\n"
  9252. "xyz\r\n"
  9253. "NaN\r\n",
  9254. &out);
  9255. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9256. }
  9257. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9258. std::string out;
  9259. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9260. "Content-Type: text/plain\r\n"
  9261. "Transfer-Encoding: chunked\r\n"
  9262. "\r\n"
  9263. // Length is too large for 64 bits.
  9264. "1ffffffffffffffff\r\n"
  9265. "xyz\r\n",
  9266. &out);
  9267. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9268. }
  9269. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9270. test_raw_request("GET /hi HTTP/1.1\r\n"
  9271. "Content-Type: text/plain\r\n\r");
  9272. }
  9273. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9274. std::string out;
  9275. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9276. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9277. }
  9278. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9279. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9280. std::string out;
  9281. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9282. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9283. }
  9284. }
  9285. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9286. std::string out;
  9287. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9288. "Host: localhost\r\n"
  9289. "Connection: close\r\n\r\n",
  9290. &out);
  9291. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9292. }
  9293. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9294. Server svr;
  9295. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9296. EXPECT_TRUE(!req.remote_addr.empty());
  9297. });
  9298. thread t = thread([&] { svr.listen(HOST, PORT); });
  9299. auto se = detail::scope_exit([&] {
  9300. svr.stop();
  9301. t.join();
  9302. ASSERT_FALSE(svr.is_running());
  9303. });
  9304. svr.wait_until_ready();
  9305. // Send an invalid request line to trigger Bad Request
  9306. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9307. std::string out;
  9308. ASSERT_TRUE(send_request(5, bad_req, &out));
  9309. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9310. }
  9311. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9312. // answered right away rather than blocking on a read that waits for EOF.
  9313. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9314. std::string out;
  9315. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9316. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9317. }
  9318. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9319. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9320. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9321. for (const auto *method : methods) {
  9322. Server svr;
  9323. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9324. EXPECT_FALSE(svr.is_valid()) << method;
  9325. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9326. }
  9327. }
  9328. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9329. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9330. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9331. for (const auto *method : methods) {
  9332. Server svr;
  9333. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9334. EXPECT_FALSE(svr.is_valid()) << method;
  9335. }
  9336. }
  9337. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9338. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9339. "COPY", "MOVE", "LOCK",
  9340. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9341. Server svr;
  9342. for (const auto *method : methods) {
  9343. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9344. }
  9345. EXPECT_TRUE(svr.is_valid());
  9346. }
  9347. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9348. Server svr;
  9349. svr.CustomRoute("POST", "/x",
  9350. [](const Request &, Response &, const ContentReader &) {});
  9351. EXPECT_FALSE(svr.is_valid());
  9352. }
  9353. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9354. Server svr;
  9355. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9356. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9357. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9358. EXPECT_FALSE(svr.is_valid());
  9359. }
  9360. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9361. Server svr;
  9362. auto captured = Error::Success;
  9363. svr.set_error_logger(
  9364. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9365. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9366. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9367. }
  9368. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9369. std::string out;
  9370. std::string request(
  9371. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9372. test_raw_request(request, &out);
  9373. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9374. }
  9375. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9376. std::string out;
  9377. std::string request(
  9378. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9379. test_raw_request(request, &out);
  9380. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9381. }
  9382. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9383. std::string out;
  9384. std::string request(
  9385. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9386. test_raw_request(request, &out);
  9387. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9388. }
  9389. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9390. std::string out;
  9391. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9392. "Host: localhost\r\n"
  9393. "Test: \r\n\r\n",
  9394. &out);
  9395. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9396. }
  9397. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9398. Server svr;
  9399. std::string x_custom;
  9400. std::string cookie;
  9401. std::string xff;
  9402. std::string x_unicode;
  9403. std::string x_iis;
  9404. svr.Get("/check", [&](const Request &req, Response &res) {
  9405. x_custom = req.get_header_value("X-Custom");
  9406. cookie = req.get_header_value("Cookie");
  9407. xff = req.get_header_value("X-Forwarded-For");
  9408. x_unicode = req.get_header_value("X-Unicode");
  9409. x_iis = req.get_header_value("X-IIS");
  9410. res.set_content("ok", "text/plain");
  9411. });
  9412. thread t = thread([&] { svr.listen(HOST, PORT); });
  9413. auto se = detail::scope_exit([&] {
  9414. svr.stop();
  9415. t.join();
  9416. ASSERT_FALSE(svr.is_running());
  9417. });
  9418. svr.wait_until_ready();
  9419. const std::string req = "GET /check HTTP/1.1\r\n"
  9420. "Host: localhost\r\n"
  9421. "X-Custom: a%0D%0AInjected: b\r\n"
  9422. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9423. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9424. "X-Unicode: %E3%81%82\r\n"
  9425. "X-IIS: %u00E9\r\n"
  9426. "Connection: close\r\n"
  9427. "\r\n";
  9428. std::string res;
  9429. ASSERT_TRUE(send_request(5, req, &res));
  9430. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9431. // Every value must be returned verbatim (wire form), with no decoding.
  9432. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9433. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9434. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9435. EXPECT_EQ("%E3%81%82", x_unicode);
  9436. EXPECT_EQ("%u00E9", x_iis);
  9437. }
  9438. // Applications that previously relied on automatic percent-decoding can
  9439. // reproduce the old behavior by explicitly calling decode_path_component()
  9440. // or, for RFC 3986 conformance, decode_uri_component().
  9441. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9442. Server svr;
  9443. std::string decoded;
  9444. svr.Get("/check", [&](const Request &req, Response &res) {
  9445. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9446. res.set_content("ok", "text/plain");
  9447. });
  9448. thread t = thread([&] { svr.listen(HOST, PORT); });
  9449. auto se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. t.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. const std::string req = "GET /check HTTP/1.1\r\n"
  9456. "Host: localhost\r\n"
  9457. "X-Custom: hello%20world\r\n"
  9458. "Connection: close\r\n"
  9459. "\r\n";
  9460. std::string res;
  9461. ASSERT_TRUE(send_request(5, req, &res));
  9462. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9463. EXPECT_EQ("hello world", decoded);
  9464. }
  9465. // Regression test for #2033. Browsers send Referer values that include
  9466. // percent-encoded characters such as %0A inside the URL. Decoding the
  9467. // header value would either trip the post-decode CR/LF/NUL guard (the
  9468. // original bug, returning 400) or, after that guard was relaxed, silently
  9469. // store a literal LF — both unacceptable. The wire form must round-trip.
  9470. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9471. Server svr;
  9472. std::string referer;
  9473. svr.Get("/check", [&](const Request &req, Response &res) {
  9474. referer = req.get_header_value("Referer");
  9475. res.set_content("ok", "text/plain");
  9476. });
  9477. thread t = thread([&] { svr.listen(HOST, PORT); });
  9478. auto se = detail::scope_exit([&] {
  9479. svr.stop();
  9480. t.join();
  9481. ASSERT_FALSE(svr.is_running());
  9482. });
  9483. svr.wait_until_ready();
  9484. const std::string req = "GET /check HTTP/1.1\r\n"
  9485. "Host: localhost\r\n"
  9486. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9487. "Connection: close\r\n"
  9488. "\r\n";
  9489. std::string res;
  9490. ASSERT_TRUE(send_request(5, req, &res));
  9491. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9492. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9493. }
  9494. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9495. Server svr;
  9496. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9497. res.set_header("Cache-Control", "no-cache");
  9498. res.set_chunked_content_provider(
  9499. "text/event-stream", [](size_t offset, DataSink &sink) {
  9500. std::string s = "data:";
  9501. s += std::to_string(offset);
  9502. s += "\n\n";
  9503. auto ret = sink.write(s.data(), s.size());
  9504. EXPECT_TRUE(ret);
  9505. std::this_thread::sleep_for(std::chrono::seconds(1));
  9506. return true;
  9507. });
  9508. });
  9509. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9510. svr.wait_until_ready();
  9511. Client client(HOST, PORT);
  9512. const Headers headers = {{"Accept", "text/event-stream"}};
  9513. auto get_thread = std::thread([&client, &headers]() {
  9514. auto res = client.Get(
  9515. "/events", headers,
  9516. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9517. });
  9518. auto se = detail::scope_exit([&] {
  9519. svr.stop();
  9520. get_thread.join();
  9521. listen_thread.join();
  9522. ASSERT_FALSE(svr.is_running());
  9523. });
  9524. // Give GET time to get a few messages.
  9525. std::this_thread::sleep_for(std::chrono::seconds(2));
  9526. }
  9527. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9528. httplib::Server svr;
  9529. svr.Post("/hi",
  9530. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9531. res.status = StatusCode::OK_200;
  9532. });
  9533. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9534. svr.wait_until_ready();
  9535. Client cli(HOST, PORT);
  9536. auto res = cli.Post("/hi", "data", "text/plain");
  9537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9538. EXPECT_EQ(StatusCode::OK_200, res->status);
  9539. svr.stop();
  9540. thread.join();
  9541. ASSERT_FALSE(svr.is_running());
  9542. res = cli.Post("/hi", "data", "text/plain");
  9543. ASSERT_FALSE(res);
  9544. }
  9545. TEST(ServerStopTest, ListenFailure) {
  9546. Server svr;
  9547. auto t = thread([&]() {
  9548. auto ret = svr.listen("????", PORT);
  9549. EXPECT_FALSE(ret);
  9550. });
  9551. svr.wait_until_ready();
  9552. svr.stop();
  9553. t.join();
  9554. }
  9555. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9556. TEST(ServerStopTest, Decommision) {
  9557. Server svr;
  9558. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9559. for (int i = 0; i < 4; i++) {
  9560. auto is_even = !(i % 2);
  9561. std::thread t{[&] {
  9562. try {
  9563. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9564. if (is_even) {
  9565. throw std::runtime_error("Some thing that happens to go wrong.");
  9566. }
  9567. svr.listen(HOST, PORT);
  9568. } catch (...) { svr.decommission(); }
  9569. }};
  9570. svr.wait_until_ready();
  9571. // Server is up
  9572. {
  9573. Client cli(HOST, PORT);
  9574. auto res = cli.Get("/hi");
  9575. if (is_even) {
  9576. EXPECT_FALSE(res);
  9577. } else {
  9578. EXPECT_TRUE(res);
  9579. EXPECT_EQ("hi...", res->body);
  9580. }
  9581. }
  9582. svr.stop();
  9583. t.join();
  9584. // Server is down...
  9585. {
  9586. Client cli(HOST, PORT);
  9587. auto res = cli.Get("/hi");
  9588. EXPECT_FALSE(res);
  9589. }
  9590. }
  9591. }
  9592. #endif
  9593. // Helper function for string body upload progress tests
  9594. template <typename SetupHandler, typename ClientCall>
  9595. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9596. ClientCall &&client_call,
  9597. const string &body) {
  9598. Server svr;
  9599. setup_handler(svr);
  9600. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9601. auto se = detail::scope_exit([&] {
  9602. svr.stop();
  9603. t.join();
  9604. });
  9605. svr.wait_until_ready();
  9606. Client cli(HOST, PORT);
  9607. vector<uint64_t> progress_values;
  9608. bool progress_called = false;
  9609. auto res =
  9610. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9611. progress_values.push_back(current);
  9612. progress_called = true;
  9613. return true;
  9614. });
  9615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9616. EXPECT_EQ(200, res->status);
  9617. EXPECT_TRUE(progress_called);
  9618. }
  9619. TEST(UploadProgressTest, PostStringBodyBasic) {
  9620. TestStringBodyUploadProgress(
  9621. [](Server &svr) {
  9622. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9623. res.set_content("received", "text/plain");
  9624. });
  9625. },
  9626. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9627. return cli.Post("/test", body, "text/plain", progress_callback);
  9628. },
  9629. "test data for upload progress");
  9630. }
  9631. TEST(UploadProgressTest, PutStringBodyBasic) {
  9632. TestStringBodyUploadProgress(
  9633. [](Server &svr) {
  9634. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9635. res.set_content("put received", "text/plain");
  9636. });
  9637. },
  9638. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9639. return cli.Put("/test", body, "text/plain", progress_callback);
  9640. },
  9641. "put test data for upload progress");
  9642. }
  9643. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9644. TestStringBodyUploadProgress(
  9645. [](Server &svr) {
  9646. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9647. res.set_content("patch received", "text/plain");
  9648. });
  9649. },
  9650. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9651. return cli.Patch("/test", body, "text/plain", progress_callback);
  9652. },
  9653. "patch test data for upload progress");
  9654. }
  9655. // Helper function for content provider upload progress tests
  9656. template <typename SetupHandler, typename ClientCall>
  9657. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9658. ClientCall &&client_call) {
  9659. Server svr;
  9660. setup_handler(svr);
  9661. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9662. auto se = detail::scope_exit([&] {
  9663. svr.stop();
  9664. t.join();
  9665. });
  9666. svr.wait_until_ready();
  9667. Client cli(HOST, PORT);
  9668. vector<uint64_t> progress_values;
  9669. auto res =
  9670. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9671. progress_values.push_back(current);
  9672. return true;
  9673. });
  9674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9675. EXPECT_EQ(200, res->status);
  9676. EXPECT_FALSE(progress_values.empty());
  9677. }
  9678. TEST(UploadProgressTest, PostContentProviderProgress) {
  9679. TestContentProviderUploadProgress(
  9680. [](Server &svr) {
  9681. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9682. res.set_content("provider received", "text/plain");
  9683. });
  9684. },
  9685. [](Client &cli, UploadProgress progress_callback) {
  9686. return cli.Post(
  9687. "/test", 10,
  9688. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9689. sink.os << "test data";
  9690. return true;
  9691. },
  9692. "text/plain", progress_callback);
  9693. });
  9694. }
  9695. // Helper function for multipart upload progress tests
  9696. template <typename SetupHandler, typename ClientCall>
  9697. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9698. ClientCall &&client_call,
  9699. const string &endpoint) {
  9700. Server svr;
  9701. setup_handler(svr);
  9702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9703. auto se = detail::scope_exit([&] {
  9704. svr.stop();
  9705. t.join();
  9706. });
  9707. svr.wait_until_ready();
  9708. Client cli(HOST, PORT);
  9709. vector<uint64_t> progress_values;
  9710. UploadFormDataItems items = {
  9711. {"field1", "value1", "", ""},
  9712. {"field2", "longer value for progress tracking test", "", ""},
  9713. {"file1", "file content data for upload progress", "test.txt",
  9714. "text/plain"}};
  9715. auto res = client_call(cli, endpoint, items,
  9716. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9717. progress_values.push_back(current);
  9718. return true;
  9719. });
  9720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9721. EXPECT_EQ(200, res->status);
  9722. EXPECT_FALSE(progress_values.empty());
  9723. }
  9724. TEST(UploadProgressTest, PostMultipartProgress) {
  9725. TestMultipartUploadProgress(
  9726. [](Server &svr) {
  9727. svr.Post("/multipart", [](const Request &req, Response &res) {
  9728. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9729. res.set_content("multipart received", "text/plain");
  9730. });
  9731. },
  9732. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9733. UploadProgress progress_callback) {
  9734. return cli.Post(endpoint, items, progress_callback);
  9735. },
  9736. "/multipart");
  9737. }
  9738. // Helper function for basic download progress tests
  9739. template <typename SetupHandler, typename ClientCall>
  9740. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9741. ClientCall &&client_call, const string &endpoint,
  9742. size_t expected_content_size) {
  9743. Server svr;
  9744. setup_handler(svr);
  9745. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9746. auto se = detail::scope_exit([&] {
  9747. svr.stop();
  9748. t.join();
  9749. });
  9750. svr.wait_until_ready();
  9751. Client cli(HOST, PORT);
  9752. vector<uint64_t> progress_values;
  9753. auto res = client_call(cli, endpoint,
  9754. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9755. progress_values.push_back(current);
  9756. return true;
  9757. });
  9758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9759. EXPECT_EQ(200, res->status);
  9760. EXPECT_FALSE(progress_values.empty());
  9761. EXPECT_EQ(expected_content_size, res->body.size());
  9762. }
  9763. TEST(DownloadProgressTest, GetBasic) {
  9764. TestBasicDownloadProgress(
  9765. [](Server &svr) {
  9766. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9767. string content(1000, 'D');
  9768. res.set_content(content, "text/plain");
  9769. });
  9770. },
  9771. [](Client &cli, const string &endpoint,
  9772. DownloadProgress progress_callback) {
  9773. return cli.Get(endpoint, progress_callback);
  9774. },
  9775. "/download", 1000u);
  9776. }
  9777. // Helper function for content receiver download progress tests
  9778. template <typename SetupHandler, typename ClientCall>
  9779. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9780. ClientCall &&client_call,
  9781. const string &endpoint,
  9782. size_t expected_content_size) {
  9783. Server svr;
  9784. setup_handler(svr);
  9785. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. t.join();
  9789. });
  9790. svr.wait_until_ready();
  9791. Client cli(HOST, PORT);
  9792. vector<uint64_t> progress_values;
  9793. string received_body;
  9794. auto res = client_call(
  9795. cli, endpoint,
  9796. [&](const char *data, size_t data_length) -> bool {
  9797. received_body.append(data, data_length);
  9798. return true;
  9799. },
  9800. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9801. progress_values.push_back(current);
  9802. return true;
  9803. });
  9804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9805. EXPECT_EQ(200, res->status);
  9806. EXPECT_FALSE(progress_values.empty());
  9807. EXPECT_EQ(expected_content_size, received_body.size());
  9808. EXPECT_TRUE(res->body.empty());
  9809. }
  9810. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9811. TestContentReceiverDownloadProgress(
  9812. [](Server &svr) {
  9813. svr.Get("/download-receiver",
  9814. [](const Request & /*req*/, Response &res) {
  9815. string content(2000, 'R');
  9816. res.set_content(content, "text/plain");
  9817. });
  9818. },
  9819. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9820. DownloadProgress progress_callback) {
  9821. return cli.Get(endpoint, content_receiver, progress_callback);
  9822. },
  9823. "/download-receiver", 2000u);
  9824. }
  9825. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9826. // A provider reaching a pass with nothing to hand over - an empty buffer
  9827. // popped off a queue, say - must not be taken to mean the body is finished.
  9828. // It used to end the loop with the terminating chunk unwritten while the
  9829. // server still considered the response complete, so the peer waited for an
  9830. // end that never arrived.
  9831. Server svr;
  9832. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9833. auto step = std::make_shared<int>(0);
  9834. res.set_chunked_content_provider("text/plain",
  9835. [step](size_t /*offset*/, DataSink &sink) {
  9836. switch ((*step)++) {
  9837. case 0: sink.write("", 0); break;
  9838. case 1: sink.write("hello", 5); break;
  9839. default: sink.done(); break;
  9840. }
  9841. return true;
  9842. });
  9843. });
  9844. auto port = svr.bind_to_any_port(HOST);
  9845. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9846. auto listen_se = detail::scope_exit([&] {
  9847. svr.stop();
  9848. listen_thread.join();
  9849. ASSERT_FALSE(svr.is_running());
  9850. });
  9851. svr.wait_until_ready();
  9852. Client cli(HOST, port);
  9853. // Without the fix the body is never terminated, so bound the wait rather
  9854. // than letting the test hang on the default read timeout.
  9855. cli.set_read_timeout(5, 0);
  9856. auto res = cli.Get("/stream");
  9857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9858. EXPECT_EQ(StatusCode::OK_200, res->status);
  9859. EXPECT_EQ("hello", res->body);
  9860. }
  9861. TEST(StreamingTest, NoContentLengthStreaming) {
  9862. Server svr;
  9863. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9864. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9865. if (offset < 6) {
  9866. sink.os << (offset < 3 ? "a" : "b");
  9867. } else {
  9868. sink.done();
  9869. }
  9870. return true;
  9871. });
  9872. });
  9873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9874. auto listen_se = detail::scope_exit([&] {
  9875. svr.stop();
  9876. listen_thread.join();
  9877. ASSERT_FALSE(svr.is_running());
  9878. });
  9879. svr.wait_until_ready();
  9880. Client client(HOST, PORT);
  9881. auto get_thread = std::thread([&client]() {
  9882. std::string s;
  9883. auto res =
  9884. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9885. s += std::string(data, len);
  9886. return true;
  9887. });
  9888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9889. EXPECT_EQ(StatusCode::OK_200, res->status);
  9890. EXPECT_EQ("aaabbb", s);
  9891. });
  9892. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9893. // Give GET time to get a few messages.
  9894. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9895. }
  9896. TEST(MountTest, Unmount) {
  9897. Server svr;
  9898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9899. auto se = detail::scope_exit([&] {
  9900. svr.stop();
  9901. listen_thread.join();
  9902. ASSERT_FALSE(svr.is_running());
  9903. });
  9904. svr.wait_until_ready();
  9905. Client cli("localhost", PORT);
  9906. svr.set_mount_point("/mount2", "./www2");
  9907. auto res = cli.Get("/");
  9908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9909. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9910. res = cli.Get("/mount2/dir/test.html");
  9911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9912. EXPECT_EQ(StatusCode::OK_200, res->status);
  9913. svr.set_mount_point("/", "./www");
  9914. res = cli.Get("/dir/");
  9915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9916. EXPECT_EQ(StatusCode::OK_200, res->status);
  9917. svr.remove_mount_point("/");
  9918. res = cli.Get("/dir/");
  9919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9921. svr.remove_mount_point("/mount2");
  9922. res = cli.Get("/mount2/dir/test.html");
  9923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9925. }
  9926. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9927. Server svr;
  9928. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9929. svr.Get("/api/hello", [](const Request &, Response &res) {
  9930. res.set_content("api", "text/plain");
  9931. });
  9932. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9933. auto se = detail::scope_exit([&] {
  9934. svr.stop();
  9935. listen_thread.join();
  9936. ASSERT_FALSE(svr.is_running());
  9937. });
  9938. svr.wait_until_ready();
  9939. Client cli(HOST, PORT);
  9940. auto res = cli.Get("/dir/test.html");
  9941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9942. EXPECT_EQ(StatusCode::OK_200, res->status);
  9943. res = cli.Get("/api/hello");
  9944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9945. EXPECT_EQ(StatusCode::OK_200, res->status);
  9946. EXPECT_EQ("api", res->body);
  9947. }
  9948. TEST(MountTest, PathSegmentBoundary) {
  9949. Server svr;
  9950. svr.set_mount_point("/mount2", "./www2");
  9951. svr.set_mount_point("/", "./www");
  9952. auto port = svr.bind_to_any_port(HOST);
  9953. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9954. auto se = detail::scope_exit([&] {
  9955. svr.stop();
  9956. listen_thread.join();
  9957. ASSERT_FALSE(svr.is_running());
  9958. });
  9959. svr.wait_until_ready();
  9960. Client cli(HOST, port);
  9961. auto res = cli.Get("/mount2/dir/test.html");
  9962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9963. EXPECT_EQ(StatusCode::OK_200, res->status);
  9964. // "/mount2" must not match part-way through a path segment.
  9965. res = cli.Get("/mount2dir/test.html");
  9966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9968. // A mount point ending in '/' keeps matching every path below it.
  9969. res = cli.Get("/dir/test.html");
  9970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9971. EXPECT_EQ(StatusCode::OK_200, res->status);
  9972. }
  9973. TEST(MountTest, Redicect) {
  9974. Server svr;
  9975. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9976. auto se = detail::scope_exit([&] {
  9977. svr.stop();
  9978. listen_thread.join();
  9979. ASSERT_FALSE(svr.is_running());
  9980. });
  9981. svr.set_mount_point("/", "./www");
  9982. svr.wait_until_ready();
  9983. Client cli("localhost", PORT);
  9984. auto res = cli.Get("/dir/");
  9985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9986. EXPECT_EQ(StatusCode::OK_200, res->status);
  9987. res = cli.Get("/dir");
  9988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9989. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9990. res = cli.Get("/file");
  9991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9992. EXPECT_EQ(StatusCode::OK_200, res->status);
  9993. res = cli.Get("/file/");
  9994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9995. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9996. cli.set_follow_location(true);
  9997. res = cli.Get("/dir");
  9998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. }
  10001. TEST(MountTest, MultibytesPathName) {
  10002. Server svr;
  10003. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10004. auto se = detail::scope_exit([&] {
  10005. svr.stop();
  10006. listen_thread.join();
  10007. ASSERT_FALSE(svr.is_running());
  10008. });
  10009. svr.set_mount_point("/", "./www");
  10010. svr.wait_until_ready();
  10011. Client cli("localhost", PORT);
  10012. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10014. EXPECT_EQ(StatusCode::OK_200, res->status);
  10015. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10016. }
  10017. #ifdef _WIN32
  10018. // Issue #2435: mmap::open() must succeed even when another handle holds
  10019. // the file open for writing (e.g. an active log file).
  10020. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10021. const char *path = "mmap_concurrent_writer_test.txt";
  10022. const char *content = "hello";
  10023. {
  10024. std::ofstream f(path, std::ios::binary);
  10025. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10026. }
  10027. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10028. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10029. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10030. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10031. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10032. detail::mmap m(path);
  10033. ASSERT_TRUE(m.is_open());
  10034. EXPECT_EQ(strlen(content), m.size());
  10035. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10036. }
  10037. #endif
  10038. #ifndef _WIN32
  10039. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10040. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10041. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10042. TEST(MmapTest, FailedMappingIsNotOpen) {
  10043. const char *path = "./mmap_failed_mapping_test_dir";
  10044. ASSERT_EQ(0, ::mkdir(path, 0755));
  10045. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10046. detail::mmap m(path);
  10047. EXPECT_FALSE(m.is_open());
  10048. EXPECT_EQ(0U, m.size());
  10049. EXPECT_NE(static_cast<const void *>(m.data()),
  10050. static_cast<const void *>(MAP_FAILED));
  10051. }
  10052. #endif
  10053. TEST(KeepAliveTest, ReadTimeout) {
  10054. Server svr;
  10055. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10056. std::this_thread::sleep_for(std::chrono::seconds(2));
  10057. res.set_content("a", "text/plain");
  10058. });
  10059. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10060. res.set_content("b", "text/plain");
  10061. });
  10062. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10063. auto se = detail::scope_exit([&] {
  10064. svr.stop();
  10065. listen_thread.join();
  10066. ASSERT_FALSE(svr.is_running());
  10067. });
  10068. svr.wait_until_ready();
  10069. Client cli("localhost", PORT);
  10070. cli.set_keep_alive(true);
  10071. cli.set_read_timeout(std::chrono::seconds(1));
  10072. auto resa = cli.Get("/a");
  10073. ASSERT_FALSE(resa);
  10074. EXPECT_EQ(Error::Read, resa.error());
  10075. auto resb = cli.Get("/b");
  10076. ASSERT_TRUE(resb);
  10077. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10078. EXPECT_EQ("b", resb->body);
  10079. }
  10080. TEST(KeepAliveTest, MaxCount) {
  10081. size_t keep_alive_max_count = 3;
  10082. Server svr;
  10083. svr.set_keep_alive_max_count(keep_alive_max_count);
  10084. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10085. res.set_content("Hello World!", "text/plain");
  10086. });
  10087. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10088. auto se = detail::scope_exit([&] {
  10089. svr.stop();
  10090. listen_thread.join();
  10091. ASSERT_FALSE(svr.is_running());
  10092. });
  10093. svr.wait_until_ready();
  10094. Client cli(HOST, PORT);
  10095. cli.set_keep_alive(true);
  10096. for (size_t i = 0; i < 5; i++) {
  10097. auto result = cli.Get("/hi");
  10098. ASSERT_TRUE(result);
  10099. EXPECT_EQ(StatusCode::OK_200, result->status);
  10100. if (i == keep_alive_max_count - 1) {
  10101. EXPECT_EQ("close", result->get_header_value("Connection"));
  10102. } else {
  10103. EXPECT_FALSE(result->has_header("Connection"));
  10104. }
  10105. }
  10106. }
  10107. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10108. // can pull the next one into the server's buffer. The server must serve it
  10109. // without waiting for the socket to become readable again. The keep-alive
  10110. // timeout outlasts the client's read timeout, so a request left waiting for it
  10111. // shows up as a missing response.
  10112. static void serve_pipelining_routes(Server &svr,
  10113. const std::function<void(int)> &client) {
  10114. svr.set_keep_alive_timeout(5);
  10115. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10116. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10117. });
  10118. svr.Post("/echo", [](const Request &req, Response &res) {
  10119. res.set_content("echo " + req.body, "text/plain");
  10120. });
  10121. auto port = svr.bind_to_any_port(HOST);
  10122. thread t = thread([&] { svr.listen_after_bind(); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. t.join();
  10126. });
  10127. svr.wait_until_ready();
  10128. client(port);
  10129. }
  10130. static std::string
  10131. send_pipelined_requests(const std::vector<std::string> &parts) {
  10132. Server svr;
  10133. std::string res;
  10134. serve_pipelining_routes(svr, [&](int port) {
  10135. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10136. });
  10137. return res;
  10138. }
  10139. static void expect_in_order(const std::string &res,
  10140. const std::vector<std::string> &bodies) {
  10141. size_t pos = 0;
  10142. for (const auto &body : bodies) {
  10143. pos = res.find(body, pos);
  10144. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10145. pos += body.size();
  10146. }
  10147. }
  10148. TEST(KeepAliveTest, PipelinedRequests) {
  10149. auto res = send_pipelined_requests(
  10150. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10151. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10152. "Content-Length: 4\r\n\r\nbody"
  10153. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10154. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10155. }
  10156. // The second request starts in the server's buffer and ends on the socket.
  10157. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10158. auto res =
  10159. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10160. "GET /hi/2 HTTP/1.1\r\nHo",
  10161. "st: localhost\r\nConnection: close\r\n\r\n"});
  10162. expect_in_order(res, {"hi 1", "hi 2"});
  10163. }
  10164. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10165. // CRLF after a body does not turn into a 400 for the next request.
  10166. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10167. auto res = send_pipelined_requests(
  10168. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10169. "Content-Length: 4\r\n\r\nbody\r\n"
  10170. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10171. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10172. expect_in_order(res, {"echo body", "hi 2"});
  10173. }
  10174. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10175. // must not be served as the next request.
  10176. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10177. auto res = send_pipelined_requests(
  10178. {"INVALID REQUEST LINE\r\n\r\n"
  10179. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10180. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10181. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10182. }
  10183. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10184. // Over TLS, the next request is held by the TLS library as already decrypted
  10185. // data rather than on the socket.
  10186. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10187. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10188. std::string res;
  10189. serve_pipelining_routes(svr, [&](int port) {
  10190. auto error = Error::Success;
  10191. auto sock = detail::create_client_socket(
  10192. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10193. /*connection_timeout_sec=*/5, 0,
  10194. /*read_timeout_sec=*/2, 0,
  10195. /*write_timeout_sec=*/5, 0, std::string(), error);
  10196. ASSERT_NE(INVALID_SOCKET, sock);
  10197. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10198. auto ctx = SSL_CTX_new(TLS_client_method());
  10199. auto ssl = SSL_new(ctx);
  10200. auto ssl_se = detail::scope_exit([&] {
  10201. SSL_free(ssl);
  10202. SSL_CTX_free(ctx);
  10203. });
  10204. SSL_set_fd(ssl, static_cast<int>(sock));
  10205. ASSERT_EQ(1, SSL_connect(ssl));
  10206. // One write, so all three requests arrive in one TLS record
  10207. const std::string req =
  10208. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10209. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10210. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10211. ASSERT_EQ(static_cast<int>(req.size()),
  10212. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10213. char buf[512];
  10214. int n;
  10215. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10216. res.append(buf, static_cast<size_t>(n));
  10217. }
  10218. });
  10219. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10220. }
  10221. #endif
  10222. TEST(KeepAliveTest, Issue1041) {
  10223. Server svr;
  10224. svr.set_keep_alive_timeout(3);
  10225. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10226. res.set_content("Hello World!", "text/plain");
  10227. });
  10228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10229. auto se = detail::scope_exit([&] {
  10230. svr.stop();
  10231. listen_thread.join();
  10232. ASSERT_FALSE(svr.is_running());
  10233. });
  10234. svr.wait_until_ready();
  10235. Client cli(HOST, PORT);
  10236. cli.set_keep_alive(true);
  10237. auto result = cli.Get("/hi");
  10238. ASSERT_TRUE(result);
  10239. EXPECT_EQ(StatusCode::OK_200, result->status);
  10240. std::this_thread::sleep_for(std::chrono::seconds(5));
  10241. result = cli.Get("/hi");
  10242. ASSERT_TRUE(result);
  10243. EXPECT_EQ(StatusCode::OK_200, result->status);
  10244. }
  10245. TEST(KeepAliveTest, Issue1959) {
  10246. Server svr;
  10247. svr.set_keep_alive_timeout(5);
  10248. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10249. res.set_content("a", "text/plain");
  10250. });
  10251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10252. auto se = detail::scope_exit([&] {
  10253. if (!svr.is_running()) return;
  10254. svr.stop();
  10255. listen_thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. Client cli("localhost", PORT);
  10260. cli.set_keep_alive(true);
  10261. using namespace std::chrono;
  10262. auto start = steady_clock::now();
  10263. cli.Get("/a");
  10264. svr.stop();
  10265. listen_thread.join();
  10266. auto end = steady_clock::now();
  10267. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10268. EXPECT_LT(elapsed, 5000);
  10269. }
  10270. #ifdef CPPHTTPLIB_SSL_ENABLED
  10271. TEST(KeepAliveTest, SSLClientReconnection) {
  10272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10273. ASSERT_TRUE(svr.is_valid());
  10274. svr.set_keep_alive_timeout(1);
  10275. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10276. res.set_content("Hello World!", "text/plain");
  10277. });
  10278. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10279. auto se = detail::scope_exit([&] {
  10280. svr.stop();
  10281. listen_thread.join();
  10282. ASSERT_FALSE(svr.is_running());
  10283. });
  10284. svr.wait_until_ready();
  10285. SSLClient cli(HOST, PORT);
  10286. cli.enable_server_certificate_verification(false);
  10287. cli.set_keep_alive(true);
  10288. auto result = cli.Get("/hi");
  10289. ASSERT_TRUE(result);
  10290. EXPECT_EQ(StatusCode::OK_200, result->status);
  10291. result = cli.Get("/hi");
  10292. ASSERT_TRUE(result);
  10293. EXPECT_EQ(StatusCode::OK_200, result->status);
  10294. std::this_thread::sleep_for(std::chrono::seconds(2));
  10295. // Recoonect
  10296. result = cli.Get("/hi");
  10297. ASSERT_TRUE(result);
  10298. EXPECT_EQ(StatusCode::OK_200, result->status);
  10299. result = cli.Get("/hi");
  10300. ASSERT_TRUE(result);
  10301. EXPECT_EQ(StatusCode::OK_200, result->status);
  10302. }
  10303. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10305. ASSERT_TRUE(svr.is_valid());
  10306. svr.set_keep_alive_timeout(1);
  10307. std::string content = "reconnect";
  10308. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10309. res.set_content("Hello World!", "text/plain");
  10310. });
  10311. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. listen_thread.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. SSLClient cli(HOST, PORT);
  10319. cli.enable_server_certificate_verification(false);
  10320. cli.set_keep_alive(true);
  10321. auto result = cli.Post(
  10322. "/hi", content.size(),
  10323. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10324. sink.write(content.c_str(), content.size());
  10325. return true;
  10326. },
  10327. "text/plain");
  10328. ASSERT_TRUE(result);
  10329. EXPECT_EQ(200, result->status);
  10330. std::this_thread::sleep_for(std::chrono::seconds(2));
  10331. // Recoonect
  10332. result = cli.Post(
  10333. "/hi", content.size(),
  10334. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10335. sink.write(content.c_str(), content.size());
  10336. return true;
  10337. },
  10338. "text/plain");
  10339. ASSERT_TRUE(result);
  10340. EXPECT_EQ(200, result->status);
  10341. result = cli.Post(
  10342. "/hi", content.size(),
  10343. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10344. sink.write(content.c_str(), content.size());
  10345. return true;
  10346. },
  10347. "text/plain");
  10348. ASSERT_TRUE(result);
  10349. EXPECT_EQ(200, result->status);
  10350. }
  10351. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10352. using namespace httplib::tls;
  10353. {
  10354. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10355. ASSERT_TRUE(svr.is_valid());
  10356. svr.Get("/sni", [&](const Request &req, Response &res) {
  10357. std::string expected = req.sni();
  10358. EXPECT_EQ(expected, req.get_param_value("expected"));
  10359. res.set_content("ok", "text/plain");
  10360. });
  10361. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10362. auto se = detail::scope_exit([&] {
  10363. svr.stop();
  10364. listen_thread.join();
  10365. ASSERT_FALSE(svr.is_running());
  10366. });
  10367. svr.wait_until_ready();
  10368. {
  10369. SSLClient cli("localhost", PORT);
  10370. cli.enable_server_certificate_verification(false);
  10371. auto res = cli.Get("/sni?expected=localhost");
  10372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10373. }
  10374. {
  10375. SSLClient cli("::1", PORT);
  10376. cli.enable_server_certificate_verification(false);
  10377. auto res = cli.Get("/sni?expected=");
  10378. // NOTE: This may fail if the server is listening on IPv4 only
  10379. // (e.g., when localhost resolves to 127.0.0.1 only)
  10380. if (res) {
  10381. EXPECT_EQ(StatusCode::OK_200, res->status);
  10382. } else {
  10383. EXPECT_EQ(Error::Connection, res.error());
  10384. }
  10385. }
  10386. }
  10387. }
  10388. #endif
  10389. TEST(ClientProblemDetectionTest, ContentProvider) {
  10390. Server svr;
  10391. size_t content_length = 1024 * 1024;
  10392. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10393. res.set_content_provider(
  10394. content_length, "text/plain",
  10395. [&](size_t offset, size_t length, DataSink &sink) {
  10396. auto out_len = std::min(length, static_cast<size_t>(1024));
  10397. std::string out(out_len, '@');
  10398. sink.write(out.data(), out_len);
  10399. return offset < 4096;
  10400. },
  10401. [](bool success) { ASSERT_FALSE(success); });
  10402. });
  10403. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10404. res.set_content_provider(
  10405. 0, "text/plain",
  10406. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10407. EXPECT_TRUE(false);
  10408. return true;
  10409. },
  10410. [](bool success) { ASSERT_FALSE(success); });
  10411. });
  10412. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10413. auto se = detail::scope_exit([&] {
  10414. svr.stop();
  10415. listen_thread.join();
  10416. ASSERT_FALSE(svr.is_running());
  10417. });
  10418. svr.wait_until_ready();
  10419. Client cli("localhost", PORT);
  10420. {
  10421. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10422. size_t /*data_length*/) { return false; });
  10423. ASSERT_FALSE(res);
  10424. }
  10425. {
  10426. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10427. size_t /*data_length*/) { return false; });
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. }
  10430. }
  10431. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10432. // A provider that reports success without writing anything and without
  10433. // calling done() used to be handed the same offset and length again on every
  10434. // pass, so it spun for as long as the peer stayed connected.
  10435. Server svr;
  10436. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10437. res.set_content("ok", "text/plain");
  10438. });
  10439. auto port = svr.bind_to_any_port(HOST);
  10440. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10441. auto se = detail::scope_exit([&] {
  10442. svr.stop();
  10443. listen_thread.join();
  10444. ASSERT_FALSE(svr.is_running());
  10445. });
  10446. svr.wait_until_ready();
  10447. std::atomic<int> call_count{0};
  10448. Client cli(HOST, port);
  10449. auto res = cli.Post(
  10450. "/", 1024,
  10451. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10452. // Give up after enough passes to show the spin, so that losing the
  10453. // check below fails this test instead of hanging it.
  10454. return ++call_count < 100;
  10455. },
  10456. "text/plain");
  10457. ASSERT_FALSE(res);
  10458. EXPECT_EQ(Error::Write, res.error());
  10459. EXPECT_EQ(1, call_count.load());
  10460. }
  10461. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10462. // A writer only has to assign `write`. The other three used to be left as
  10463. // empty std::functions, so a provider calling one threw
  10464. // std::bad_function_call out of the thread running it and took the whole
  10465. // process down.
  10466. DataSink sink;
  10467. std::string written;
  10468. sink.write = [&](const char *data, size_t data_len) {
  10469. written.append(data, data_len);
  10470. return true;
  10471. };
  10472. EXPECT_TRUE(sink.is_writable());
  10473. sink.done();
  10474. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10475. EXPECT_TRUE(written.empty());
  10476. }
  10477. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10478. // A sink that cannot carry trailers still has to finish.
  10479. DataSink sink;
  10480. auto done_count = 0;
  10481. sink.done = [&]() { done_count++; };
  10482. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10483. EXPECT_EQ(1, done_count);
  10484. }
  10485. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10486. Server svr;
  10487. const std::string body(4096, 'x');
  10488. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10489. res.set_content_provider(body.size(), "text/plain",
  10490. [&](size_t offset, size_t length, DataSink &sink) {
  10491. sink.write(body.data() + offset, length);
  10492. sink.done();
  10493. return true;
  10494. });
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. listen_thread.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. Client cli(HOST, port);
  10505. auto res = cli.Get("/");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. EXPECT_EQ(body, res->body);
  10509. }
  10510. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10511. Server svr;
  10512. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10513. res.set_content_provider(
  10514. 1024, "text/plain",
  10515. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10516. sink.write("hello", 5);
  10517. sink.done(); // short of the 1024 bytes the response promised
  10518. return true;
  10519. });
  10520. });
  10521. auto port = svr.bind_to_any_port(HOST);
  10522. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10523. auto se = detail::scope_exit([&] {
  10524. svr.stop();
  10525. listen_thread.join();
  10526. ASSERT_FALSE(svr.is_running());
  10527. });
  10528. svr.wait_until_ready();
  10529. Client cli(HOST, port);
  10530. cli.set_read_timeout(5, 0);
  10531. // The response is short of its Content-Length, so the client cannot read a
  10532. // complete body. What matters is that this returns at all: a no-op done()
  10533. // would leave the writer looping over a provider that never makes progress.
  10534. auto res = cli.Get("/");
  10535. EXPECT_FALSE(res);
  10536. }
  10537. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10538. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10539. // The compressed path builds the whole body before connecting, so this
  10540. // fails client-side and never reaches a server.
  10541. Client cli(HOST, PORT);
  10542. cli.set_compress(true);
  10543. auto res = cli.Post(
  10544. "/", 1024,
  10545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10546. sink.write("hello", 5);
  10547. sink.done(); // short of the 1024 bytes the request announced
  10548. return true;
  10549. },
  10550. "text/plain");
  10551. ASSERT_FALSE(res);
  10552. EXPECT_EQ(Error::Write, res.error());
  10553. }
  10554. #endif
  10555. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10556. Server svr;
  10557. svr.set_error_handler([](Request const &, Response &res) -> void {
  10558. res.set_chunked_content_provider(
  10559. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10560. sink.os << "hello";
  10561. sink.os << "world";
  10562. sink.done();
  10563. return true;
  10564. });
  10565. });
  10566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10567. auto se = detail::scope_exit([&] {
  10568. svr.stop();
  10569. listen_thread.join();
  10570. ASSERT_FALSE(svr.is_running());
  10571. });
  10572. svr.wait_until_ready();
  10573. Client cli("localhost", PORT);
  10574. auto res = cli.Get("/");
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10577. EXPECT_EQ("helloworld", res->body);
  10578. }
  10579. // A body set after a content provider must replace it, not be sent through it.
  10580. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10581. Server svr;
  10582. svr.set_mount_point("/", "./www");
  10583. svr.set_file_request_handler([](const Request &req, Response &res) {
  10584. if (req.path == "/dir/test.html") {
  10585. res.status = StatusCode::Forbidden_403;
  10586. res.set_content(std::string(5000, 'D'), "text/plain");
  10587. } else if (req.path == "/file") {
  10588. res.status = StatusCode::Forbidden_403;
  10589. res.body = "Denied";
  10590. }
  10591. });
  10592. auto port = svr.bind_to_any_port(HOST);
  10593. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10594. auto se = detail::scope_exit([&] {
  10595. svr.stop();
  10596. t.join();
  10597. ASSERT_FALSE(svr.is_running());
  10598. });
  10599. svr.wait_until_ready();
  10600. Client cli(HOST, port);
  10601. {
  10602. auto res = cli.Get("/dir/test.html");
  10603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10604. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10605. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10606. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10607. }
  10608. {
  10609. auto res = cli.Get("/file");
  10610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10611. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10612. EXPECT_EQ("Denied", res->body);
  10613. }
  10614. {
  10615. auto res = cli.Get("/dir/index.html");
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(StatusCode::OK_200, res->status);
  10618. EXPECT_EQ(0U, res->body.find("<html>"));
  10619. }
  10620. }
  10621. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10622. Server svr;
  10623. std::vector<bool> released;
  10624. std::mutex released_mutex;
  10625. auto releaser = [&](bool success) {
  10626. std::lock_guard<std::mutex> guard(released_mutex);
  10627. released.push_back(success);
  10628. };
  10629. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10630. return sink.write(&"hello"[offset], length);
  10631. };
  10632. svr.Get("/sized", [&](const Request &, Response &res) {
  10633. res.status = StatusCode::NotFound_404;
  10634. res.set_content_provider(5, "text/plain", provider, releaser);
  10635. });
  10636. svr.Get("/chunked", [&](const Request &, Response &res) {
  10637. res.status = StatusCode::ServiceUnavailable_503;
  10638. res.set_chunked_content_provider(
  10639. "text/plain",
  10640. [](size_t, DataSink &sink) {
  10641. sink.os << "chunk";
  10642. sink.done();
  10643. return true;
  10644. },
  10645. releaser);
  10646. });
  10647. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10648. res.set_content_provider(5, "text/plain", provider, releaser);
  10649. throw std::runtime_error("after the provider");
  10650. });
  10651. svr.set_error_handler([](const Request &req, Response &res) {
  10652. // Leave the exception handler's content to it.
  10653. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10654. res.set_content(std::string(1000, 'E'), "text/html");
  10655. return Server::HandlerResponse::Handled;
  10656. });
  10657. svr.set_exception_handler(
  10658. [](const Request &, Response &res, std::exception_ptr) {
  10659. res.status = StatusCode::InternalServerError_500;
  10660. res.set_content(std::string(1000, 'X'), "text/html");
  10661. });
  10662. auto port = svr.bind_to_any_port(HOST);
  10663. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. t.join();
  10667. ASSERT_FALSE(svr.is_running());
  10668. });
  10669. svr.wait_until_ready();
  10670. Client cli(HOST, port);
  10671. {
  10672. auto res = cli.Get("/sized");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10675. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10676. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10677. }
  10678. {
  10679. auto res = cli.Get("/chunked");
  10680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10681. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10682. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10683. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10684. }
  10685. {
  10686. auto res = cli.Get("/throw");
  10687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10688. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10689. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10690. }
  10691. std::lock_guard<std::mutex> guard(released_mutex);
  10692. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10693. }
  10694. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10695. Server svr;
  10696. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10697. return sink.write(&"abc"[offset], length);
  10698. };
  10699. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10700. res.set_file_content("./www/dir/test.html");
  10701. res.set_content("body", "text/plain");
  10702. });
  10703. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10704. res.set_content(std::string(100, 'B'), "text/plain");
  10705. res.set_file_content("./www/dir/test.html");
  10706. });
  10707. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10708. res.set_content(std::string(100, 'B'), "text/plain");
  10709. res.set_content_provider(3, "text/plain", abc);
  10710. });
  10711. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10712. res.set_content_provider(3, "text/plain", abc);
  10713. res.set_content(std::string(100, 'B'), "text/plain");
  10714. });
  10715. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10716. res.set_content_provider(3, "text/plain", abc);
  10717. res.body = "direct";
  10718. });
  10719. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10720. res.set_file_content("./www/dir/test.html");
  10721. res.body = "direct";
  10722. });
  10723. auto port = svr.bind_to_any_port(HOST);
  10724. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10725. auto se = detail::scope_exit([&] {
  10726. svr.stop();
  10727. t.join();
  10728. ASSERT_FALSE(svr.is_running());
  10729. });
  10730. svr.wait_until_ready();
  10731. Client cli(HOST, port);
  10732. auto expect_body = [&](const char *path, const std::string &body) {
  10733. // Uncompressed, so Content-Length can be compared with the body.
  10734. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10735. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10736. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10737. EXPECT_EQ(body, res->body) << path;
  10738. EXPECT_EQ(std::to_string(body.size()),
  10739. res->get_header_value("Content-Length"))
  10740. << path;
  10741. };
  10742. expect_body("/file-then-body", "body");
  10743. expect_body("/body-then-file", "test.html");
  10744. expect_body("/body-then-provider", "abc");
  10745. expect_body("/provider-then-body", std::string(100, 'B'));
  10746. expect_body("/provider-then-direct-body", "direct");
  10747. expect_body("/file-then-direct-body", "direct");
  10748. // Ranges are checked against the body, not the dropped provider.
  10749. {
  10750. auto res = cli.Get("/provider-then-direct-body",
  10751. Headers{{make_range_header({{1, 2}})}});
  10752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10754. EXPECT_EQ("ir", res->body);
  10755. }
  10756. {
  10757. auto res = cli.Get("/file-then-direct-body",
  10758. Headers{{make_range_header({{7, 8}})}});
  10759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10760. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10761. }
  10762. }
  10763. // Forward declaration (see the base64_encode note).
  10764. namespace httplib {
  10765. namespace detail {
  10766. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10767. const std::string &content_type,
  10768. EncodingType encoding);
  10769. } // namespace detail
  10770. } // namespace httplib
  10771. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10772. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10773. ASSERT_TRUE(mm->is_open());
  10774. Response res;
  10775. detail::set_file_content_provider(res, mm, "text/html",
  10776. detail::EncodingType::None);
  10777. std::string out;
  10778. DataSink sink;
  10779. sink.write = [&](const char *d, size_t l) {
  10780. out.append(d, l);
  10781. return true;
  10782. };
  10783. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10784. EXPECT_EQ("test.html", out);
  10785. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10786. EXPECT_EQ("test.html", out);
  10787. }
  10788. TEST(LongPollingTest, ClientCloseDetection) {
  10789. Server svr;
  10790. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10791. res.set_chunked_content_provider(
  10792. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10793. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10794. sink.os << "hello";
  10795. auto count = 10;
  10796. while (count > 0 && sink.is_writable()) {
  10797. this_thread::sleep_for(chrono::milliseconds(10));
  10798. count--;
  10799. }
  10800. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10801. return true;
  10802. });
  10803. });
  10804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. ASSERT_FALSE(svr.is_running());
  10809. });
  10810. svr.wait_until_ready();
  10811. Client cli("localhost", PORT);
  10812. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10813. EXPECT_EQ("hello", string(data, data_length));
  10814. return false; // close the socket immediately.
  10815. });
  10816. ASSERT_FALSE(res);
  10817. }
  10818. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10819. Server svr;
  10820. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10821. res.set_chunked_content_provider(
  10822. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10823. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10824. sink.os << "hello";
  10825. EXPECT_TRUE(sink.os.good());
  10826. // Wait for the client to close the connection
  10827. auto count = 10;
  10828. while (count > 0 && sink.is_writable()) {
  10829. this_thread::sleep_for(chrono::milliseconds(10));
  10830. count--;
  10831. }
  10832. // After client disconnect, write repeatedly until the socket
  10833. // write actually fails (small writes may be absorbed by the
  10834. // kernel buffer)
  10835. std::string chunk(1024, 'x');
  10836. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10837. sink.os << chunk;
  10838. }
  10839. EXPECT_TRUE(sink.os.fail());
  10840. return true;
  10841. });
  10842. });
  10843. auto port = svr.bind_to_any_port("localhost");
  10844. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10845. auto se = detail::scope_exit([&] {
  10846. svr.stop();
  10847. listen_thread.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. Client cli("localhost", port);
  10852. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10853. EXPECT_EQ("hello", string(data, data_length));
  10854. return false; // close the socket immediately.
  10855. });
  10856. ASSERT_FALSE(res);
  10857. }
  10858. TEST(GetWithParametersTest, GetWithParameters) {
  10859. Server svr;
  10860. svr.Get("/", [&](const Request &req, Response &) {
  10861. EXPECT_EQ("world", req.get_param_value("hello"));
  10862. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10863. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10864. });
  10865. svr.Get("/params", [&](const Request &req, Response &) {
  10866. EXPECT_EQ("world", req.get_param_value("hello"));
  10867. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10868. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10869. });
  10870. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10871. EXPECT_EQ("resource-id", req.matches[1]);
  10872. EXPECT_EQ("foo", req.get_param_value("param1"));
  10873. EXPECT_EQ("bar", req.get_param_value("param2"));
  10874. });
  10875. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10876. EXPECT_EQ("user-id", req.path_params.at("id"));
  10877. EXPECT_EQ("foo", req.get_param_value("param1"));
  10878. EXPECT_EQ("bar", req.get_param_value("param2"));
  10879. });
  10880. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10881. auto se = detail::scope_exit([&] {
  10882. svr.stop();
  10883. listen_thread.join();
  10884. ASSERT_FALSE(svr.is_running());
  10885. });
  10886. svr.wait_until_ready();
  10887. {
  10888. Client cli(HOST, PORT);
  10889. Params params;
  10890. params.emplace("hello", "world");
  10891. params.emplace("hello2", "world2");
  10892. params.emplace("hello3", "world3");
  10893. auto res = cli.Get("/", params, Headers{});
  10894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10895. EXPECT_EQ(StatusCode::OK_200, res->status);
  10896. }
  10897. {
  10898. Client cli(HOST, PORT);
  10899. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10901. EXPECT_EQ(StatusCode::OK_200, res->status);
  10902. }
  10903. {
  10904. Client cli(HOST, PORT);
  10905. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10907. EXPECT_EQ(StatusCode::OK_200, res->status);
  10908. }
  10909. {
  10910. Client cli(HOST, PORT);
  10911. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::OK_200, res->status);
  10914. }
  10915. }
  10916. TEST(GetWithParametersTest, GetWithParameters2) {
  10917. Server svr;
  10918. svr.Get("/", [&](const Request &req, Response &res) {
  10919. auto text = req.get_param_value("hello");
  10920. res.set_content(text, "text/plain");
  10921. });
  10922. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. listen_thread.join();
  10926. ASSERT_FALSE(svr.is_running());
  10927. });
  10928. svr.wait_until_ready();
  10929. Client cli("localhost", PORT);
  10930. Params params;
  10931. params.emplace("hello", "world");
  10932. std::string body;
  10933. auto res = cli.Get("/", params, Headers{},
  10934. [&](const char *data, size_t data_length) {
  10935. body.append(data, data_length);
  10936. return true;
  10937. });
  10938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10939. EXPECT_EQ(StatusCode::OK_200, res->status);
  10940. EXPECT_EQ("world", body);
  10941. }
  10942. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10943. Server svr;
  10944. svr.Get("/search", [&](const Request &req, Response &res) {
  10945. auto q = req.get_param_value("q");
  10946. res.set_content(q, "text/plain");
  10947. });
  10948. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10949. auto se = detail::scope_exit([&] {
  10950. svr.stop();
  10951. listen_thread.join();
  10952. ASSERT_FALSE(svr.is_running());
  10953. });
  10954. svr.wait_until_ready();
  10955. Client cli("localhost", PORT);
  10956. // Verify that Get(path, params) works without requiring Headers argument
  10957. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10959. EXPECT_EQ(StatusCode::OK_200, res->status);
  10960. EXPECT_EQ("cpp-httplib", res->body);
  10961. }
  10962. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10963. auto host = "httpbingo.org";
  10964. auto path = std::string{"/range/32"};
  10965. #ifdef CPPHTTPLIB_SSL_ENABLED
  10966. SSLClient cli(host);
  10967. #else
  10968. Client cli(host);
  10969. #endif
  10970. cli.set_default_headers({make_range_header({{1, 10}})});
  10971. cli.set_connection_timeout(5);
  10972. {
  10973. auto res = cli.Get(path);
  10974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10975. EXPECT_EQ("bcdefghijk", res->body);
  10976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10977. }
  10978. {
  10979. auto res = cli.Get(path);
  10980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10981. EXPECT_EQ("bcdefghijk", res->body);
  10982. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10983. }
  10984. }
  10985. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10986. Server svr;
  10987. svr.set_default_headers({{"Hello", "World"}});
  10988. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10989. res.set_content("ok", "text/plain");
  10990. });
  10991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10992. auto se = detail::scope_exit([&] {
  10993. svr.stop();
  10994. listen_thread.join();
  10995. ASSERT_FALSE(svr.is_running());
  10996. });
  10997. svr.wait_until_ready();
  10998. Client cli("localhost", PORT);
  10999. auto res = cli.Get("/");
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. EXPECT_EQ(StatusCode::OK_200, res->status);
  11002. EXPECT_EQ("ok", res->body);
  11003. EXPECT_EQ("World", res->get_header_value("Hello"));
  11004. }
  11005. #ifdef CPPHTTPLIB_SSL_ENABLED
  11006. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11008. ASSERT_TRUE(svr.is_valid());
  11009. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11010. std::this_thread::sleep_for(std::chrono::seconds(2));
  11011. res.set_content("a", "text/plain");
  11012. });
  11013. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11014. res.set_content("b", "text/plain");
  11015. });
  11016. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11017. auto se = detail::scope_exit([&] {
  11018. svr.stop();
  11019. listen_thread.join();
  11020. ASSERT_FALSE(svr.is_running());
  11021. });
  11022. svr.wait_until_ready();
  11023. SSLClient cli("localhost", PORT);
  11024. cli.enable_server_certificate_verification(false);
  11025. cli.set_keep_alive(true);
  11026. cli.set_read_timeout(std::chrono::seconds(1));
  11027. auto resa = cli.Get("/a");
  11028. ASSERT_TRUE(!resa);
  11029. EXPECT_EQ(Error::Read, resa.error());
  11030. auto resb = cli.Get("/b");
  11031. ASSERT_TRUE(resb);
  11032. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11033. EXPECT_EQ("b", resb->body);
  11034. }
  11035. // Closing an idle keep-alive connection sends close_notify and returns. The
  11036. // server must not wait for the client's close_notify: an idle client never
  11037. // sends one, so the worker would be held until the read timeout expires, and
  11038. // stop() would wait for it.
  11039. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11041. ASSERT_TRUE(svr.is_valid());
  11042. svr.set_keep_alive_timeout(1);
  11043. svr.set_read_timeout(10, 0);
  11044. svr.Get("/", [](const Request &, Response &res) {
  11045. res.set_content("ok", "text/plain");
  11046. });
  11047. auto port = svr.bind_to_any_port(HOST);
  11048. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11049. auto se = detail::scope_exit([&] {
  11050. if (listen_thread.joinable()) {
  11051. svr.stop();
  11052. listen_thread.join();
  11053. }
  11054. });
  11055. svr.wait_until_ready();
  11056. SSLClient cli(HOST, port);
  11057. cli.enable_server_certificate_verification(false);
  11058. cli.set_keep_alive(true);
  11059. auto res = cli.Get("/");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. EXPECT_EQ(StatusCode::OK_200, res->status);
  11062. // Stay idle past the keep-alive timeout so the server closes the connection.
  11063. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11064. auto start = std::chrono::steady_clock::now();
  11065. svr.stop();
  11066. listen_thread.join();
  11067. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11068. std::chrono::steady_clock::now() - start)
  11069. .count();
  11070. EXPECT_LT(elapsed, 3000);
  11071. }
  11072. #endif
  11073. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11074. protected:
  11075. ServerTestWithAI_PASSIVE()
  11076. : cli_(HOST, PORT)
  11077. #ifdef CPPHTTPLIB_SSL_ENABLED
  11078. ,
  11079. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11080. #endif
  11081. {
  11082. #ifdef CPPHTTPLIB_SSL_ENABLED
  11083. cli_.enable_server_certificate_verification(false);
  11084. #endif
  11085. }
  11086. virtual void SetUp() {
  11087. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11088. res.set_content("Hello World!", "text/plain");
  11089. });
  11090. t_ = thread(
  11091. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11092. svr_.wait_until_ready();
  11093. }
  11094. virtual void TearDown() {
  11095. svr_.stop();
  11096. t_.join();
  11097. }
  11098. #ifdef CPPHTTPLIB_SSL_ENABLED
  11099. SSLClient cli_;
  11100. SSLServer svr_;
  11101. #else
  11102. Client cli_;
  11103. Server svr_;
  11104. #endif
  11105. thread t_;
  11106. };
  11107. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11108. auto res = cli_.Get("/hi");
  11109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11110. EXPECT_EQ(StatusCode::OK_200, res->status);
  11111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11112. EXPECT_EQ("Hello World!", res->body);
  11113. }
  11114. class ServerUpDownTest : public ::testing::Test {
  11115. protected:
  11116. ServerUpDownTest() : cli_(HOST, PORT) {}
  11117. virtual void SetUp() {
  11118. t_ = thread([&]() {
  11119. svr_.bind_to_any_port(HOST);
  11120. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11121. ASSERT_TRUE(svr_.listen_after_bind());
  11122. });
  11123. svr_.wait_until_ready();
  11124. }
  11125. virtual void TearDown() {
  11126. svr_.stop();
  11127. t_.join();
  11128. }
  11129. Client cli_;
  11130. Server svr_;
  11131. thread t_;
  11132. };
  11133. TEST_F(ServerUpDownTest, QuickStartStop) {
  11134. // Should not crash, especially when run with
  11135. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11136. }
  11137. class PayloadMaxLengthTest : public ::testing::Test {
  11138. protected:
  11139. PayloadMaxLengthTest()
  11140. : cli_(HOST, PORT)
  11141. #ifdef CPPHTTPLIB_SSL_ENABLED
  11142. ,
  11143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11144. #endif
  11145. {
  11146. #ifdef CPPHTTPLIB_SSL_ENABLED
  11147. cli_.enable_server_certificate_verification(false);
  11148. #endif
  11149. }
  11150. virtual void SetUp() {
  11151. svr_.set_payload_max_length(8);
  11152. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11153. res.set_content("test", "text/plain");
  11154. });
  11155. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11156. svr_.wait_until_ready();
  11157. }
  11158. virtual void TearDown() {
  11159. svr_.stop();
  11160. t_.join();
  11161. }
  11162. #ifdef CPPHTTPLIB_SSL_ENABLED
  11163. SSLClient cli_;
  11164. SSLServer svr_;
  11165. #else
  11166. Client cli_;
  11167. Server svr_;
  11168. #endif
  11169. thread t_;
  11170. };
  11171. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11172. auto res = cli_.Post("/test", "123456789", "text/plain");
  11173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11174. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11175. res = cli_.Post("/test", "12345678", "text/plain");
  11176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11177. EXPECT_EQ(StatusCode::OK_200, res->status);
  11178. }
  11179. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11180. // Test chunked encoding with payload exceeding the 8-byte limit
  11181. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11182. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11184. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11185. }
  11186. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11187. // Test chunked encoding with payload within the 8-byte limit
  11188. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11189. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11191. EXPECT_EQ(StatusCode::OK_200, res->status);
  11192. }
  11193. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11194. // Test using send_request to send chunked data exceeding payload limit
  11195. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11196. "Host: " +
  11197. std::string(HOST) + ":" + std::to_string(PORT) +
  11198. "\r\n"
  11199. "Transfer-Encoding: chunked\r\n"
  11200. "Connection: close\r\n"
  11201. "\r\n"
  11202. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11203. "0123456789\r\n"
  11204. "0\r\n" // End chunk
  11205. "\r\n";
  11206. std::string response;
  11207. bool result = send_request(1, chunked_request, &response);
  11208. if (!result) {
  11209. // If send_request fails, it might be because the server closed the
  11210. // connection due to payload limit enforcement, which is acceptable
  11211. SUCCEED()
  11212. << "Server rejected oversized chunked request (connection closed)";
  11213. } else {
  11214. // If we got a response, check if it's an error response or connection was
  11215. // closed early Short response length indicates connection was closed due to
  11216. // payload limit
  11217. if (response.length() <= 10) {
  11218. SUCCEED() << "Server closed connection for oversized chunked request";
  11219. } else {
  11220. // Check for error status codes
  11221. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11222. response.find("Payload Too Large") != std::string::npos ||
  11223. response.find("400") != std::string::npos);
  11224. }
  11225. }
  11226. }
  11227. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11228. // Test request without Content-Length header exceeding payload limit
  11229. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11230. "Host: " +
  11231. std::string(HOST) + ":" +
  11232. std::to_string(PORT) +
  11233. "\r\n"
  11234. "Connection: close\r\n"
  11235. "\r\n";
  11236. // Add payload exceeding the 8-byte limit
  11237. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11238. request_without_content_length += large_payload;
  11239. std::string response;
  11240. bool result = send_request(1, request_without_content_length, &response);
  11241. if (!result) {
  11242. // If send_request fails, server likely closed connection due to payload
  11243. // limit
  11244. SUCCEED() << "Server rejected oversized request without Content-Length "
  11245. "(connection closed)";
  11246. } else {
  11247. // Check if server responded with error or closed connection early
  11248. if (response.length() <= 10) {
  11249. SUCCEED() << "Server closed connection for oversized request without "
  11250. "Content-Length";
  11251. } else {
  11252. // Check for error status codes
  11253. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11254. response.find("Payload Too Large") != std::string::npos ||
  11255. response.find("400") != std::string::npos);
  11256. }
  11257. }
  11258. }
  11259. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11260. // Test request without Content-Length header within payload limit
  11261. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11262. "Host: " +
  11263. std::string(HOST) + ":" +
  11264. std::to_string(PORT) +
  11265. "\r\n"
  11266. "Connection: close\r\n"
  11267. "\r\n";
  11268. // Add payload within the 8-byte limit
  11269. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11270. request_without_content_length += small_payload;
  11271. std::string response;
  11272. bool result = send_request(1, request_without_content_length, &response);
  11273. // For requests without Content-Length, the server may have different behavior
  11274. // The key is that it should not reject due to payload limit for small
  11275. // payloads
  11276. if (result) {
  11277. // Check for any HTTP response (success or error, but not connection closed)
  11278. if (response.length() > 10) {
  11279. SUCCEED()
  11280. << "Server processed request without Content-Length within limit";
  11281. } else {
  11282. // Short response might indicate connection closed, which is acceptable
  11283. SUCCEED() << "Server closed connection for request without "
  11284. "Content-Length (acceptable behavior)";
  11285. }
  11286. } else {
  11287. // Connection failure might be due to protocol requirements
  11288. SUCCEED() << "Connection issue with request without Content-Length "
  11289. "(environment-specific)";
  11290. }
  11291. }
  11292. class LargePayloadMaxLengthTest : public ::testing::Test {
  11293. protected:
  11294. LargePayloadMaxLengthTest()
  11295. : cli_(HOST, PORT)
  11296. #ifdef CPPHTTPLIB_SSL_ENABLED
  11297. ,
  11298. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11299. #endif
  11300. {
  11301. #ifdef CPPHTTPLIB_SSL_ENABLED
  11302. cli_.enable_server_certificate_verification(false);
  11303. #endif
  11304. }
  11305. virtual void SetUp() {
  11306. // Set 10MB payload limit
  11307. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11308. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11309. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11310. res.set_content("Large payload test", "text/plain");
  11311. });
  11312. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11313. svr_.wait_until_ready();
  11314. }
  11315. virtual void TearDown() {
  11316. svr_.stop();
  11317. t_.join();
  11318. }
  11319. #ifdef CPPHTTPLIB_SSL_ENABLED
  11320. SSLClient cli_;
  11321. SSLServer svr_;
  11322. #else
  11323. Client cli_;
  11324. Server svr_;
  11325. #endif
  11326. thread t_;
  11327. };
  11328. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11329. // Test chunked encoding with payload within 10MB limit
  11330. std::string medium_payload(5 * 1024 * 1024,
  11331. 'A'); // 5MB payload, within 10MB limit
  11332. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11334. EXPECT_EQ(StatusCode::OK_200, res->status);
  11335. }
  11336. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11337. // Test chunked encoding with payload exceeding 10MB limit
  11338. std::string large_payload(12 * 1024 * 1024,
  11339. 'B'); // 12MB payload, exceeds 10MB limit
  11340. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11341. // Server may either return 413 or close the connection
  11342. if (res) {
  11343. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11344. } else {
  11345. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11346. }
  11347. }
  11348. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11349. // Test request without Content-Length header within 10MB limit
  11350. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11351. "Host: " +
  11352. std::string(HOST) + ":" +
  11353. std::to_string(PORT) +
  11354. "\r\n"
  11355. "Connection: close\r\n"
  11356. "\r\n";
  11357. // Add 1MB payload (within 10MB limit)
  11358. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11359. request_without_content_length += medium_payload;
  11360. std::string response;
  11361. bool result = send_request(5, request_without_content_length, &response);
  11362. if (result) {
  11363. // Should get a proper HTTP response for payloads within limit
  11364. if (response.length() > 10) {
  11365. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11366. "10MB limit";
  11367. } else {
  11368. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11369. "Content-Length)";
  11370. }
  11371. } else {
  11372. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11373. }
  11374. }
  11375. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11376. // Test request without Content-Length header exceeding 10MB limit
  11377. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11378. "Host: " +
  11379. std::string(HOST) + ":" +
  11380. std::to_string(PORT) +
  11381. "\r\n"
  11382. "Connection: close\r\n"
  11383. "\r\n";
  11384. // Add 12MB payload (exceeds 10MB limit)
  11385. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11386. request_without_content_length += large_payload;
  11387. std::string response;
  11388. bool result = send_request(10, request_without_content_length, &response);
  11389. if (!result) {
  11390. // Server should close connection due to payload limit
  11391. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11392. "(connection closed)";
  11393. } else {
  11394. // Check for error response
  11395. if (response.length() <= 10) {
  11396. SUCCEED()
  11397. << "Server closed connection for 12MB request exceeding 10MB limit";
  11398. } else {
  11399. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11400. response.find("Payload Too Large") != std::string::npos ||
  11401. response.find("400") != std::string::npos);
  11402. }
  11403. }
  11404. }
  11405. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11406. Server svr;
  11407. svr.Get("/", [](const Request &, Response &res) {
  11408. // Claims far more than it sends, then drops the connection.
  11409. res.set_content_provider(size_t(1) << 41, "text/plain",
  11410. [](size_t, size_t, DataSink &sink) {
  11411. sink.write("abc", 3);
  11412. return false;
  11413. });
  11414. });
  11415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11416. auto se = detail::scope_exit([&] {
  11417. svr.stop();
  11418. thread.join();
  11419. ASSERT_FALSE(svr.is_running());
  11420. });
  11421. svr.wait_until_ready();
  11422. Client cli(HOST, PORT);
  11423. cli.set_payload_max_length(0);
  11424. EXPECT_FALSE(cli.Get("/"));
  11425. }
  11426. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11427. // back the given bytes, which httplib::Server could not be made to send.
  11428. static void serve_raw_once(int port, const std::string &response) {
  11429. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11430. default_socket_options(srv);
  11431. sockaddr_in addr{};
  11432. addr.sin_family = AF_INET;
  11433. addr.sin_port = htons(static_cast<uint16_t>(port));
  11434. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11435. int opt = 1;
  11436. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11437. #ifdef _WIN32
  11438. reinterpret_cast<const char *>(&opt),
  11439. #else
  11440. &opt,
  11441. #endif
  11442. sizeof(opt));
  11443. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11444. ::listen(srv, 1);
  11445. auto cli = ::accept(srv, nullptr, nullptr);
  11446. if (cli != INVALID_SOCKET) {
  11447. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11448. std::string head;
  11449. char c;
  11450. while (head.find("\r\n\r\n") == std::string::npos &&
  11451. ::recv(cli, &c, 1, 0) == 1) {
  11452. head += c;
  11453. }
  11454. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11455. detail::close_socket(cli);
  11456. }
  11457. detail::close_socket(srv);
  11458. }
  11459. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11460. const char *responses[] = {
  11461. "HTTP/1.1 103 Early Hints\r\n"
  11462. "Link: </style.css>; rel=preload\r\n"
  11463. "\r\n"
  11464. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11465. "HTTP/1.1 100 Continue\r\n"
  11466. "X-Note: interim\r\n"
  11467. "\r\n"
  11468. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11469. };
  11470. for (auto response : responses) {
  11471. std::thread t([&]() { serve_raw_once(PORT, response); });
  11472. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11473. Client cli("127.0.0.1", PORT);
  11474. auto res = cli.Get("/");
  11475. t.join();
  11476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11477. EXPECT_EQ(StatusCode::OK_200, res->status);
  11478. EXPECT_EQ("ok", res->body);
  11479. }
  11480. }
  11481. #ifdef CPPHTTPLIB_SSL_ENABLED
  11482. TEST(ProxyConnectTest, OnlyARefusalIsPassedOn) {
  11483. // Anything but 200 or a refusal would read as the origin's own response.
  11484. {
  11485. std::thread t([] {
  11486. serve_raw_once(PORT, "HTTP/1.1 201 Created\r\n"
  11487. "Set-Cookie: session=from-proxy\r\n"
  11488. "Content-Length: 0\r\n\r\n");
  11489. });
  11490. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11491. SSLClient cli("example.com", 443);
  11492. cli.set_proxy("127.0.0.1", PORT);
  11493. auto res = cli.Get("/");
  11494. t.join();
  11495. EXPECT_FALSE(res);
  11496. EXPECT_EQ(Error::ProxyConnection, res.error());
  11497. }
  11498. {
  11499. std::thread t([] {
  11500. serve_raw_once(PORT, "HTTP/1.1 407 Proxy Authentication Required\r\n"
  11501. "Content-Length: 0\r\n\r\n");
  11502. });
  11503. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11504. SSLClient cli("example.com", 443);
  11505. cli.set_proxy("127.0.0.1", PORT);
  11506. auto res = cli.Get("/");
  11507. t.join();
  11508. ASSERT_TRUE(res);
  11509. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  11510. }
  11511. }
  11512. #endif
  11513. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11514. std::atomic<bool> closed_by_client{false};
  11515. auto server_thread = std::thread([&] {
  11516. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11517. default_socket_options(srv);
  11518. sockaddr_in addr{};
  11519. addr.sin_family = AF_INET;
  11520. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11521. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11522. int opt = 1;
  11523. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11524. #ifdef _WIN32
  11525. reinterpret_cast<const char *>(&opt),
  11526. #else
  11527. &opt,
  11528. #endif
  11529. sizeof(opt));
  11530. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11531. ::listen(srv, 1);
  11532. auto cli = ::accept(srv, nullptr, nullptr);
  11533. if (cli != INVALID_SOCKET) {
  11534. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11535. // Answer the head without asking for the body, and keep the connection.
  11536. std::string head;
  11537. char c;
  11538. while (head.find("\r\n\r\n") == std::string::npos &&
  11539. ::recv(cli, &c, 1, 0) == 1) {
  11540. head += c;
  11541. }
  11542. std::string res =
  11543. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11544. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11545. // Bytes here would be read as the body the first request declared.
  11546. char buf[256];
  11547. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11548. detail::close_socket(cli);
  11549. }
  11550. detail::close_socket(srv);
  11551. });
  11552. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11553. Client cli("127.0.0.1", PORT);
  11554. cli.set_keep_alive(true);
  11555. cli.set_read_timeout(1, 0);
  11556. // Long enough for the client to send Expect: 100-continue.
  11557. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11559. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11560. cli.Get("/second");
  11561. server_thread.join();
  11562. EXPECT_TRUE(closed_by_client);
  11563. }
  11564. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11565. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11566. // path.
  11567. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11568. Server svr;
  11569. const size_t LIMIT = 64 * 1024; // 64KB
  11570. svr.set_payload_max_length(LIMIT);
  11571. size_t total = 0;
  11572. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11573. const ContentReader &content_reader) {
  11574. content_reader([&](const char * /*data*/, size_t len) {
  11575. total += len;
  11576. return true;
  11577. });
  11578. res.status = 200;
  11579. res.set_content("stream_ok", "text/plain");
  11580. });
  11581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11582. auto se = detail::scope_exit([&] {
  11583. svr.stop();
  11584. thread.join();
  11585. ASSERT_FALSE(svr.is_running());
  11586. });
  11587. svr.wait_until_ready();
  11588. // Prepare 256KB raw data and gzip-compress it
  11589. std::string raw(256 * 1024, 'A');
  11590. std::string gz;
  11591. {
  11592. z_stream zs{};
  11593. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11594. Z_DEFAULT_STRATEGY);
  11595. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11596. zs.avail_in = static_cast<uInt>(raw.size());
  11597. char outbuf[4096];
  11598. int ret;
  11599. do {
  11600. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11601. zs.avail_out = sizeof(outbuf);
  11602. ret = deflate(&zs, Z_FINISH);
  11603. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11604. } while (ret != Z_STREAM_END);
  11605. deflateEnd(&zs);
  11606. }
  11607. Client cli(HOST, PORT);
  11608. cli.set_connection_timeout(std::chrono::seconds(5));
  11609. Headers headers = {{"Content-Encoding", "gzip"}};
  11610. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11611. "application/octet-stream");
  11612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11613. // Server must reject oversized decompressed payloads with 413.
  11614. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11615. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11616. EXPECT_LE(total, LIMIT);
  11617. }
  11618. #ifndef CPPHTTPLIB_SSL_ENABLED
  11619. // For a request with neither Content-Length nor Transfer-Encoding, the
  11620. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11621. // compressed wire bytes straight to the ContentReader without ever routing
  11622. // them through the decompressor, so payload_max_length_ only bounded the
  11623. // compressed size on the wire, not the decompressed size.
  11624. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11625. Server svr;
  11626. const size_t LIMIT = 64 * 1024; // 64KB
  11627. svr.set_payload_max_length(LIMIT);
  11628. size_t total = 0;
  11629. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11630. const ContentReader &content_reader) {
  11631. content_reader([&](const char * /*data*/, size_t len) {
  11632. total += len;
  11633. return true;
  11634. });
  11635. res.status = 200;
  11636. res.set_content("stream_ok", "text/plain");
  11637. });
  11638. auto port = svr.bind_to_any_port(HOST);
  11639. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11640. auto se = detail::scope_exit([&] {
  11641. svr.stop();
  11642. thread.join();
  11643. ASSERT_FALSE(svr.is_running());
  11644. });
  11645. svr.wait_until_ready();
  11646. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11647. // StreamingGzipDecompression test above.
  11648. std::string raw(256 * 1024, 'A');
  11649. std::string gz;
  11650. {
  11651. httplib::detail::gzip_compressor compressor;
  11652. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11653. [&](const char *chunk, size_t len) {
  11654. gz.append(chunk, len);
  11655. return true;
  11656. });
  11657. ASSERT_TRUE(result);
  11658. }
  11659. // Send the gzip body over raw TCP with neither Content-Length nor
  11660. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11661. // kicks in.
  11662. std::string req = "POST /stream HTTP/1.1\r\n"
  11663. "Host: " +
  11664. std::string(HOST) + ":" + std::to_string(port) +
  11665. "\r\n"
  11666. "Content-Encoding: gzip\r\n"
  11667. "Connection: close\r\n"
  11668. "\r\n" +
  11669. gz;
  11670. std::string response;
  11671. ASSERT_TRUE(send_request(5, req, &response, port));
  11672. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11673. EXPECT_LE(total, LIMIT);
  11674. }
  11675. #endif
  11676. #endif
  11677. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11678. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11679. // the payload must be passed through untouched instead of being rejected.
  11680. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11681. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11682. Server svr;
  11683. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11684. res.set_content(body, "image/jpeg");
  11685. res.set_header("Content-Encoding", "UTF-8");
  11686. });
  11687. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11688. res.set_content(body, "image/jpeg");
  11689. res.set_header("Content-Encoding", "identity");
  11690. });
  11691. svr.Post("/echo", [](const Request &req, Response &res) {
  11692. res.set_content(req.body, "image/jpeg");
  11693. });
  11694. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11695. auto se = detail::scope_exit([&] {
  11696. svr.stop();
  11697. t.join();
  11698. ASSERT_FALSE(svr.is_running());
  11699. });
  11700. svr.wait_until_ready();
  11701. Client cli(HOST, PORT);
  11702. {
  11703. auto res = cli.Get("/image");
  11704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11705. EXPECT_EQ(StatusCode::OK_200, res->status);
  11706. EXPECT_EQ(body, res->body);
  11707. }
  11708. {
  11709. auto res = cli.Get("/identity");
  11710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11711. EXPECT_EQ(StatusCode::OK_200, res->status);
  11712. EXPECT_EQ(body, res->body);
  11713. }
  11714. {
  11715. // The same applies to a request body reaching the server.
  11716. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11717. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11719. EXPECT_EQ(StatusCode::OK_200, res->status);
  11720. EXPECT_EQ(body, res->body);
  11721. }
  11722. }
  11723. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11724. // gzip-encoded response even when the build has no zlib support.
  11725. static const char GZIPPED_HELLO_WORLD[] = {
  11726. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11727. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11728. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11729. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11730. // A content coding is a whole token, not something the field value merely
  11731. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11732. // as "fibre" look like Brotli, and turned a multi-coding value like
  11733. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11734. // it was never meant to see.
  11735. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11736. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11737. Server svr;
  11738. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11739. res.set_content(body, "image/jpeg");
  11740. res.set_header("Content-Encoding", "fibre");
  11741. });
  11742. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11743. res.set_content(body, "image/jpeg");
  11744. res.set_header("Content-Encoding", "gzip, br");
  11745. });
  11746. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11747. res.set_content(body, "image/jpeg");
  11748. res.set_header("Content-Encoding", "x-zstd-ish");
  11749. });
  11750. auto port = svr.bind_to_any_port(HOST);
  11751. thread t = thread([&]() { svr.listen_after_bind(); });
  11752. auto se = detail::scope_exit([&] {
  11753. svr.stop();
  11754. t.join();
  11755. ASSERT_FALSE(svr.is_running());
  11756. });
  11757. svr.wait_until_ready();
  11758. Client cli(HOST, port);
  11759. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11760. auto res = cli.Get(path);
  11761. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11762. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11763. // Not a coding we recognize, so the payload comes back untouched
  11764. EXPECT_EQ(body, res->body) << path;
  11765. }
  11766. }
  11767. // A content coding cpp-httplib recognizes but was not built with must be
  11768. // reported as such. Handing the still-compressed payload back to the caller
  11769. // would silently corrupt it.
  11770. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11771. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11772. Server svr;
  11773. // "image/jpeg" keeps the server from applying a content coding of its own,
  11774. // so the hand-crafted Content-Encoding below survives.
  11775. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11776. res.set_content(gzipped, "image/jpeg");
  11777. res.set_header("Content-Encoding", "gzip");
  11778. });
  11779. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11780. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11781. res.set_content(gzipped, "image/jpeg");
  11782. res.set_header("Content-Encoding", "GZIP");
  11783. });
  11784. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11785. auto se = detail::scope_exit([&] {
  11786. svr.stop();
  11787. t.join();
  11788. ASSERT_FALSE(svr.is_running());
  11789. });
  11790. svr.wait_until_ready();
  11791. Client cli(HOST, PORT);
  11792. {
  11793. auto res = cli.Get("/gzipped");
  11794. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11796. EXPECT_EQ("Hello World!", res->body);
  11797. #else
  11798. ASSERT_FALSE(res);
  11799. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11800. #endif
  11801. }
  11802. {
  11803. // open_stream() must behave the same way.
  11804. auto handle = cli.open_stream("GET", "/gzipped");
  11805. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11806. ASSERT_TRUE(handle.is_valid());
  11807. std::string received;
  11808. char buf[256];
  11809. ssize_t n;
  11810. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11811. received.append(buf, static_cast<size_t>(n));
  11812. }
  11813. EXPECT_EQ("Hello World!", received);
  11814. #else
  11815. EXPECT_FALSE(handle.is_valid());
  11816. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11817. #endif
  11818. }
  11819. {
  11820. // A differently-cased coding must not be mistaken for an unknown one, or
  11821. // the body would be handed back still compressed.
  11822. auto res = cli.Get("/gzipped-uppercase");
  11823. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11825. EXPECT_EQ("Hello World!", res->body);
  11826. #else
  11827. ASSERT_FALSE(res);
  11828. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11829. #endif
  11830. }
  11831. }
  11832. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11833. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11834. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11835. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11836. // body a second time and appending a second Content-Encoding field line, so
  11837. // clients that decode one coding per listed value handed back raw gzip bytes.
  11838. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11839. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11840. Server svr;
  11841. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11842. // keeps the server from applying a coding of its own.
  11843. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11844. res.set_content(gzipped, "text/plain");
  11845. res.set_header("Content-Encoding", "gzip");
  11846. });
  11847. auto port = svr.bind_to_any_port(HOST);
  11848. thread t = thread([&]() { svr.listen_after_bind(); });
  11849. auto se = detail::scope_exit([&] {
  11850. svr.stop();
  11851. t.join();
  11852. ASSERT_FALSE(svr.is_running());
  11853. });
  11854. svr.wait_until_ready();
  11855. Client cli(HOST, port);
  11856. Headers headers = {{"Accept-Encoding", "gzip"}};
  11857. auto res = cli.Get("/pre-gzipped", headers);
  11858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11859. EXPECT_EQ(StatusCode::OK_200, res->status);
  11860. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11861. EXPECT_EQ("Hello World!", res->body);
  11862. }
  11863. // A chunked provider settles its coding where the headers are written and
  11864. // reuses it at write time. Both ends of that have to hold: a handler's own
  11865. // Content-Encoding suppresses the coding, and a response without one is still
  11866. // compressed as it always was.
  11867. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11868. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11869. const std::string plain = "Hello World! Hello World! Hello World!";
  11870. Server svr;
  11871. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11872. res.set_header("Content-Encoding", "gzip");
  11873. res.set_chunked_content_provider(
  11874. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11875. sink.write(gzipped.data(), gzipped.size());
  11876. sink.done();
  11877. return true;
  11878. });
  11879. });
  11880. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11881. res.set_chunked_content_provider(
  11882. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11883. sink.write(plain.data(), plain.size());
  11884. sink.done();
  11885. return true;
  11886. });
  11887. });
  11888. auto port = svr.bind_to_any_port(HOST);
  11889. thread t = thread([&]() { svr.listen_after_bind(); });
  11890. auto se = detail::scope_exit([&] {
  11891. svr.stop();
  11892. t.join();
  11893. ASSERT_FALSE(svr.is_running());
  11894. });
  11895. svr.wait_until_ready();
  11896. Client cli(HOST, port);
  11897. Headers headers = {{"Accept-Encoding", "gzip"}};
  11898. {
  11899. auto res = cli.Get("/pre-gzipped", headers);
  11900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11901. EXPECT_EQ(StatusCode::OK_200, res->status);
  11902. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11903. EXPECT_EQ("Hello World!", res->body);
  11904. }
  11905. {
  11906. auto res = cli.Get("/negotiated", headers);
  11907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11908. EXPECT_EQ(StatusCode::OK_200, res->status);
  11909. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11910. EXPECT_EQ(plain, res->body);
  11911. }
  11912. }
  11913. #endif
  11914. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11915. // the same message as the comma-joined one, so both have to be read the same
  11916. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11917. // single gzip coding, and a body the sender says was encoded twice was handed
  11918. // back after one pass, still compressed but presented as decoded.
  11919. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11920. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11921. Server svr;
  11922. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11923. res.set_content(body, "image/jpeg");
  11924. res.headers.emplace("Content-Encoding", "gzip");
  11925. res.headers.emplace("Content-Encoding", "gzip");
  11926. });
  11927. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11928. res.set_content(body, "image/jpeg");
  11929. res.set_header("Content-Encoding", "gzip, gzip");
  11930. });
  11931. auto port = svr.bind_to_any_port(HOST);
  11932. thread t = thread([&]() { svr.listen_after_bind(); });
  11933. auto se = detail::scope_exit([&] {
  11934. svr.stop();
  11935. t.join();
  11936. ASSERT_FALSE(svr.is_running());
  11937. });
  11938. svr.wait_until_ready();
  11939. Client cli(HOST, port);
  11940. // Two codings is not something cpp-httplib decodes, so both representations
  11941. // take the pass-through path rather than one of them being gunzipped once.
  11942. for (const char *path : {"/split", "/joined"}) {
  11943. auto res = cli.Get(path);
  11944. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11945. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11946. EXPECT_EQ(body, res->body) << path;
  11947. }
  11948. }
  11949. // Regression test for DoS vulnerability: a malicious server sending a response
  11950. // without Content-Length header must not cause unbounded memory consumption on
  11951. // the client side. The client should stop reading after a reasonable limit,
  11952. // similar to the server-side set_payload_max_length protection.
  11953. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11954. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11955. #ifndef _WIN32
  11956. signal(SIGPIPE, SIG_IGN);
  11957. #endif
  11958. auto server_thread = std::thread([] {
  11959. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11960. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11961. default_socket_options(srv);
  11962. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11963. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11964. sockaddr_in addr{};
  11965. addr.sin_family = AF_INET;
  11966. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11967. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11968. int opt = 1;
  11969. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11970. #ifdef _WIN32
  11971. reinterpret_cast<const char *>(&opt),
  11972. #else
  11973. &opt,
  11974. #endif
  11975. sizeof(opt));
  11976. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11977. ::listen(srv, 1);
  11978. sockaddr_in cli_addr{};
  11979. socklen_t cli_len = sizeof(cli_addr);
  11980. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11981. if (cli != INVALID_SOCKET) {
  11982. char buf[4096];
  11983. ::recv(cli, buf, sizeof(buf), 0);
  11984. // Malicious response: no Content-Length, no chunked encoding
  11985. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11986. "Connection: close\r\n"
  11987. "\r\n";
  11988. ::send(cli,
  11989. #ifdef _WIN32
  11990. static_cast<const char *>(response_header.c_str()),
  11991. static_cast<int>(response_header.size()),
  11992. #else
  11993. response_header.c_str(), response_header.size(),
  11994. #endif
  11995. 0);
  11996. // Send 10MB of data
  11997. std::string chunk(64 * 1024, 'A');
  11998. size_t total_sent = 0;
  11999. while (total_sent < MALICIOUS_DATA_SIZE) {
  12000. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12001. auto sent = ::send(cli,
  12002. #ifdef _WIN32
  12003. static_cast<const char *>(chunk.c_str()),
  12004. static_cast<int>(to_send),
  12005. #else
  12006. chunk.c_str(), to_send,
  12007. #endif
  12008. 0);
  12009. if (sent <= 0) break;
  12010. total_sent += static_cast<size_t>(sent);
  12011. }
  12012. detail::close_socket(cli);
  12013. }
  12014. detail::close_socket(srv);
  12015. });
  12016. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12017. size_t total_read = 0;
  12018. {
  12019. Client cli("127.0.0.1", PORT + 2);
  12020. cli.set_read_timeout(5, 0);
  12021. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12022. auto stream = cli.open_stream("GET", "/malicious");
  12023. ASSERT_TRUE(stream.is_valid());
  12024. char buffer[64 * 1024];
  12025. ssize_t n;
  12026. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12027. total_read += static_cast<size_t>(n);
  12028. }
  12029. } // StreamHandle and Client destroyed here, closing the socket
  12030. server_thread.join();
  12031. // With set_payload_max_length, the client must stop reading before consuming
  12032. // all 10MB. The read loop should be cut off at or near the configured limit.
  12033. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12034. << "Client read " << total_read << " bytes, exceeding the configured "
  12035. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12036. }
  12037. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12038. // the entire response body without truncation.
  12039. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12040. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12041. #ifndef _WIN32
  12042. signal(SIGPIPE, SIG_IGN);
  12043. #endif
  12044. auto server_thread = std::thread([] {
  12045. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12046. default_socket_options(srv);
  12047. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12048. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12049. sockaddr_in addr{};
  12050. addr.sin_family = AF_INET;
  12051. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12052. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12053. int opt = 1;
  12054. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12055. #ifdef _WIN32
  12056. reinterpret_cast<const char *>(&opt),
  12057. #else
  12058. &opt,
  12059. #endif
  12060. sizeof(opt));
  12061. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12062. ::listen(srv, 1);
  12063. sockaddr_in cli_addr{};
  12064. socklen_t cli_len = sizeof(cli_addr);
  12065. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12066. if (cli != INVALID_SOCKET) {
  12067. char buf[4096];
  12068. ::recv(cli, buf, sizeof(buf), 0);
  12069. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12070. "Connection: close\r\n"
  12071. "\r\n";
  12072. ::send(cli,
  12073. #ifdef _WIN32
  12074. static_cast<const char *>(response_header.c_str()),
  12075. static_cast<int>(response_header.size()),
  12076. #else
  12077. response_header.c_str(), response_header.size(),
  12078. #endif
  12079. 0);
  12080. std::string chunk(64 * 1024, 'A');
  12081. size_t total_sent = 0;
  12082. while (total_sent < DATA_SIZE) {
  12083. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12084. auto sent = ::send(cli,
  12085. #ifdef _WIN32
  12086. static_cast<const char *>(chunk.c_str()),
  12087. static_cast<int>(to_send),
  12088. #else
  12089. chunk.c_str(), to_send,
  12090. #endif
  12091. 0);
  12092. if (sent <= 0) break;
  12093. total_sent += static_cast<size_t>(sent);
  12094. }
  12095. #ifdef _WIN32
  12096. ::shutdown(cli, SD_SEND);
  12097. #else
  12098. ::shutdown(cli, SHUT_WR);
  12099. #endif
  12100. // Drain until the client closes its end, ensuring all data is delivered
  12101. char drain[1024];
  12102. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12103. detail::close_socket(cli);
  12104. }
  12105. detail::close_socket(srv);
  12106. });
  12107. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12108. size_t total_read = 0;
  12109. {
  12110. Client cli("127.0.0.1", PORT + 2);
  12111. cli.set_read_timeout(5, 0);
  12112. cli.set_payload_max_length(0); // 0 means no limit
  12113. auto stream = cli.open_stream("GET", "/data");
  12114. ASSERT_TRUE(stream.is_valid());
  12115. char buffer[64 * 1024];
  12116. ssize_t n;
  12117. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12118. total_read += static_cast<size_t>(n);
  12119. }
  12120. }
  12121. server_thread.join();
  12122. EXPECT_EQ(total_read, DATA_SIZE)
  12123. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12124. << " bytes without truncation, but only read " << total_read << " bytes.";
  12125. }
  12126. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12127. // enormous Content-Length must not cause the client to pre-allocate a huge
  12128. // response body buffer. The reservation is capped at payload_max_length_, and
  12129. // the read itself fails when the body exceeds the limit.
  12130. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12131. #ifndef _WIN32
  12132. signal(SIGPIPE, SIG_IGN);
  12133. #endif
  12134. auto server_thread = std::thread([] {
  12135. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12136. default_socket_options(srv);
  12137. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12138. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12139. sockaddr_in addr{};
  12140. addr.sin_family = AF_INET;
  12141. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12142. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12143. int opt = 1;
  12144. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12145. #ifdef _WIN32
  12146. reinterpret_cast<const char *>(&opt),
  12147. #else
  12148. &opt,
  12149. #endif
  12150. sizeof(opt));
  12151. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12152. ::listen(srv, 1);
  12153. sockaddr_in cli_addr{};
  12154. socklen_t cli_len = sizeof(cli_addr);
  12155. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12156. if (cli != INVALID_SOCKET) {
  12157. char buf[4096];
  12158. ::recv(cli, buf, sizeof(buf), 0);
  12159. // Malicious response: claim a 20GB body but send only a tiny payload.
  12160. std::string response = "HTTP/1.1 200 OK\r\n"
  12161. "Content-Length: 20000000000\r\n"
  12162. "\r\n"
  12163. "abc";
  12164. ::send(cli,
  12165. #ifdef _WIN32
  12166. static_cast<const char *>(response.c_str()),
  12167. static_cast<int>(response.size()),
  12168. #else
  12169. response.c_str(), response.size(),
  12170. #endif
  12171. 0);
  12172. detail::close_socket(cli);
  12173. }
  12174. detail::close_socket(srv);
  12175. });
  12176. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12177. {
  12178. Client cli("127.0.0.1", PORT + 2);
  12179. cli.set_read_timeout(5, 0);
  12180. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12181. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12182. // (server claims more bytes than payload_max_length permits), but it must
  12183. // not exhaust memory before getting there.
  12184. auto res = cli.Get("/malicious");
  12185. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12186. }
  12187. server_thread.join();
  12188. }
  12189. // Verify that content_receiver bypasses the default payload_max_length,
  12190. // allowing streaming downloads larger than 100MB without requiring an explicit
  12191. // set_payload_max_length call.
  12192. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12193. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12194. #ifndef _WIN32
  12195. signal(SIGPIPE, SIG_IGN);
  12196. #endif
  12197. auto server_thread = std::thread([] {
  12198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12199. default_socket_options(srv);
  12200. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12202. sockaddr_in addr{};
  12203. addr.sin_family = AF_INET;
  12204. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12206. int opt = 1;
  12207. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12208. #ifdef _WIN32
  12209. reinterpret_cast<const char *>(&opt),
  12210. #else
  12211. &opt,
  12212. #endif
  12213. sizeof(opt));
  12214. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12215. ::listen(srv, 1);
  12216. sockaddr_in cli_addr{};
  12217. socklen_t cli_len = sizeof(cli_addr);
  12218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12219. if (cli != INVALID_SOCKET) {
  12220. char buf[4096];
  12221. ::recv(cli, buf, sizeof(buf), 0);
  12222. // Response with Content-Length larger than default 100MB limit
  12223. auto content_length = std::to_string(DATA_SIZE);
  12224. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12225. "Content-Length: " +
  12226. content_length +
  12227. "\r\n"
  12228. "Connection: close\r\n"
  12229. "\r\n";
  12230. ::send(cli,
  12231. #ifdef _WIN32
  12232. static_cast<const char *>(response_header.c_str()),
  12233. static_cast<int>(response_header.size()),
  12234. #else
  12235. response_header.c_str(), response_header.size(),
  12236. #endif
  12237. 0);
  12238. std::string chunk(64 * 1024, 'A');
  12239. size_t total_sent = 0;
  12240. while (total_sent < DATA_SIZE) {
  12241. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12242. auto sent = ::send(cli,
  12243. #ifdef _WIN32
  12244. static_cast<const char *>(chunk.c_str()),
  12245. static_cast<int>(to_send),
  12246. #else
  12247. chunk.c_str(), to_send,
  12248. #endif
  12249. 0);
  12250. if (sent <= 0) break;
  12251. total_sent += static_cast<size_t>(sent);
  12252. }
  12253. detail::close_socket(cli);
  12254. }
  12255. detail::close_socket(srv);
  12256. });
  12257. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12258. size_t total_received = 0;
  12259. {
  12260. Client cli("127.0.0.1", PORT + 2);
  12261. cli.set_read_timeout(10, 0);
  12262. // Do NOT call set_payload_max_length — use the default 100MB limit
  12263. auto res =
  12264. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12265. total_received += data_length;
  12266. return true;
  12267. });
  12268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12269. EXPECT_EQ(StatusCode::OK_200, res->status);
  12270. }
  12271. server_thread.join();
  12272. EXPECT_EQ(total_received, DATA_SIZE)
  12273. << "With content_receiver, the client should read all " << DATA_SIZE
  12274. << " bytes despite the default 100MB payload_max_length, but only read "
  12275. << total_received << " bytes.";
  12276. }
  12277. // Verify that an explicit set_payload_max_length smaller than the response is
  12278. // enforced even when a content_receiver is used.
  12279. TEST(ClientVulnerabilityTest,
  12280. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12281. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12282. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12283. #ifndef _WIN32
  12284. signal(SIGPIPE, SIG_IGN);
  12285. #endif
  12286. auto server_thread = std::thread([] {
  12287. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12288. default_socket_options(srv);
  12289. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12290. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12291. sockaddr_in addr{};
  12292. addr.sin_family = AF_INET;
  12293. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12294. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12295. int opt = 1;
  12296. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12297. #ifdef _WIN32
  12298. reinterpret_cast<const char *>(&opt),
  12299. #else
  12300. &opt,
  12301. #endif
  12302. sizeof(opt));
  12303. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12304. ::listen(srv, 1);
  12305. sockaddr_in cli_addr{};
  12306. socklen_t cli_len = sizeof(cli_addr);
  12307. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12308. if (cli != INVALID_SOCKET) {
  12309. char buf[4096];
  12310. ::recv(cli, buf, sizeof(buf), 0);
  12311. auto content_length = std::to_string(DATA_SIZE);
  12312. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12313. "Content-Length: " +
  12314. content_length +
  12315. "\r\n"
  12316. "Connection: close\r\n"
  12317. "\r\n";
  12318. ::send(cli,
  12319. #ifdef _WIN32
  12320. static_cast<const char *>(response_header.c_str()),
  12321. static_cast<int>(response_header.size()),
  12322. #else
  12323. response_header.c_str(), response_header.size(),
  12324. #endif
  12325. 0);
  12326. std::string chunk(64 * 1024, 'A');
  12327. size_t total_sent = 0;
  12328. while (total_sent < DATA_SIZE) {
  12329. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12330. auto sent = ::send(cli,
  12331. #ifdef _WIN32
  12332. static_cast<const char *>(chunk.c_str()),
  12333. static_cast<int>(to_send),
  12334. #else
  12335. chunk.c_str(), to_send,
  12336. #endif
  12337. 0);
  12338. if (sent <= 0) break;
  12339. total_sent += static_cast<size_t>(sent);
  12340. }
  12341. detail::close_socket(cli);
  12342. }
  12343. detail::close_socket(srv);
  12344. });
  12345. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12346. size_t total_received = 0;
  12347. {
  12348. Client cli("127.0.0.1", PORT + 2);
  12349. cli.set_read_timeout(10, 0);
  12350. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12351. auto res =
  12352. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12353. total_received += data_length;
  12354. return true;
  12355. });
  12356. // Should fail because 200MB exceeds the explicit 150MB limit
  12357. EXPECT_FALSE(res);
  12358. }
  12359. server_thread.join();
  12360. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12361. << "Client with content_receiver should respect the explicit "
  12362. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12363. << total_received << " bytes.";
  12364. }
  12365. // Verify that an explicit set_payload_max_length larger than the response
  12366. // allows the content_receiver to read all data successfully.
  12367. TEST(ClientVulnerabilityTest,
  12368. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12369. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12370. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12371. #ifndef _WIN32
  12372. signal(SIGPIPE, SIG_IGN);
  12373. #endif
  12374. auto server_thread = std::thread([] {
  12375. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12376. default_socket_options(srv);
  12377. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12378. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12379. sockaddr_in addr{};
  12380. addr.sin_family = AF_INET;
  12381. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12382. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12383. int opt = 1;
  12384. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12385. #ifdef _WIN32
  12386. reinterpret_cast<const char *>(&opt),
  12387. #else
  12388. &opt,
  12389. #endif
  12390. sizeof(opt));
  12391. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12392. ::listen(srv, 1);
  12393. sockaddr_in cli_addr{};
  12394. socklen_t cli_len = sizeof(cli_addr);
  12395. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12396. if (cli != INVALID_SOCKET) {
  12397. char buf[4096];
  12398. ::recv(cli, buf, sizeof(buf), 0);
  12399. auto content_length = std::to_string(DATA_SIZE);
  12400. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12401. "Content-Length: " +
  12402. content_length +
  12403. "\r\n"
  12404. "Connection: close\r\n"
  12405. "\r\n";
  12406. ::send(cli,
  12407. #ifdef _WIN32
  12408. static_cast<const char *>(response_header.c_str()),
  12409. static_cast<int>(response_header.size()),
  12410. #else
  12411. response_header.c_str(), response_header.size(),
  12412. #endif
  12413. 0);
  12414. std::string chunk(64 * 1024, 'A');
  12415. size_t total_sent = 0;
  12416. while (total_sent < DATA_SIZE) {
  12417. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12418. auto sent = ::send(cli,
  12419. #ifdef _WIN32
  12420. static_cast<const char *>(chunk.c_str()),
  12421. static_cast<int>(to_send),
  12422. #else
  12423. chunk.c_str(), to_send,
  12424. #endif
  12425. 0);
  12426. if (sent <= 0) break;
  12427. total_sent += static_cast<size_t>(sent);
  12428. }
  12429. #ifdef _WIN32
  12430. ::shutdown(cli, SD_SEND);
  12431. #else
  12432. ::shutdown(cli, SHUT_WR);
  12433. #endif
  12434. char drain[1024];
  12435. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12436. detail::close_socket(cli);
  12437. }
  12438. detail::close_socket(srv);
  12439. });
  12440. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12441. size_t total_received = 0;
  12442. {
  12443. Client cli("127.0.0.1", PORT + 2);
  12444. cli.set_read_timeout(10, 0);
  12445. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12446. auto res =
  12447. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12448. total_received += data_length;
  12449. return true;
  12450. });
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::OK_200, res->status);
  12453. }
  12454. server_thread.join();
  12455. EXPECT_EQ(total_received, DATA_SIZE)
  12456. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12457. << " bytes (larger than " << DATA_SIZE
  12458. << " bytes response), content_receiver should read all data, but only "
  12459. "read "
  12460. << total_received << " bytes.";
  12461. }
  12462. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12463. // Regression test for "zip bomb" attack on the client side: a malicious server
  12464. // sends a small gzip-compressed response that decompresses to a huge payload.
  12465. // The client must enforce payload_max_length on the decompressed size.
  12466. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12467. constexpr size_t DECOMPRESSED_SIZE =
  12468. 10 * 1024 * 1024; // 10MB after decompression
  12469. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12470. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12471. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12472. std::string compressed;
  12473. {
  12474. httplib::detail::gzip_compressor compressor;
  12475. bool ok =
  12476. compressor.compress(uncompressed.data(), uncompressed.size(),
  12477. /*last=*/true, [&](const char *buf, size_t len) {
  12478. compressed.append(buf, len);
  12479. return true;
  12480. });
  12481. ASSERT_TRUE(ok);
  12482. }
  12483. // Sanity: compressed data should be much smaller than the decompressed size
  12484. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12485. #ifndef _WIN32
  12486. signal(SIGPIPE, SIG_IGN);
  12487. #endif
  12488. // Set up the listening socket in the main thread so the server is guaranteed
  12489. // to be ready before the client connects (eliminates race condition).
  12490. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12491. default_socket_options(srv);
  12492. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12493. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12494. sockaddr_in addr{};
  12495. addr.sin_family = AF_INET;
  12496. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12497. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12498. int opt = 1;
  12499. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12500. #ifdef _WIN32
  12501. reinterpret_cast<const char *>(&opt),
  12502. #else
  12503. &opt,
  12504. #endif
  12505. sizeof(opt));
  12506. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12507. ASSERT_EQ(0, ::listen(srv, 1));
  12508. auto server_thread = std::thread([&compressed, srv] {
  12509. sockaddr_in cli_addr{};
  12510. socklen_t cli_len = sizeof(cli_addr);
  12511. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12512. if (cli != INVALID_SOCKET) {
  12513. // Read the full HTTP request (until \r\n\r\n)
  12514. char buf[4096];
  12515. size_t total = 0;
  12516. while (total < sizeof(buf)) {
  12517. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12518. if (n <= 0) break;
  12519. total += static_cast<size_t>(n);
  12520. // Check for end of headers
  12521. if (total >= 4) {
  12522. std::string req(buf, total);
  12523. if (req.find("\r\n\r\n") != std::string::npos) break;
  12524. }
  12525. }
  12526. // Malicious response: gzip-compressed body, no Content-Length
  12527. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12528. "Content-Encoding: gzip\r\n"
  12529. "Connection: close\r\n"
  12530. "\r\n";
  12531. ::send(cli,
  12532. #ifdef _WIN32
  12533. static_cast<const char *>(response_header.c_str()),
  12534. static_cast<int>(response_header.size()),
  12535. #else
  12536. response_header.c_str(), response_header.size(),
  12537. #endif
  12538. 0);
  12539. // Send the compressed payload (small on the wire, huge when decompressed)
  12540. size_t total_sent = 0;
  12541. while (total_sent < compressed.size()) {
  12542. auto to_send = std::min(compressed.size() - total_sent,
  12543. static_cast<size_t>(64 * 1024));
  12544. auto sent =
  12545. ::send(cli,
  12546. #ifdef _WIN32
  12547. static_cast<const char *>(compressed.c_str() + total_sent),
  12548. static_cast<int>(to_send),
  12549. #else
  12550. compressed.c_str() + total_sent, to_send,
  12551. #endif
  12552. 0);
  12553. if (sent <= 0) break;
  12554. total_sent += static_cast<size_t>(sent);
  12555. }
  12556. detail::close_socket(cli);
  12557. }
  12558. });
  12559. auto se = detail::scope_exit([&] {
  12560. detail::close_socket(srv);
  12561. server_thread.join();
  12562. });
  12563. size_t total_decompressed = 0;
  12564. {
  12565. Client cli("127.0.0.1", PORT + 3);
  12566. cli.set_read_timeout(5, 0);
  12567. cli.set_decompress(true);
  12568. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12569. auto stream = cli.open_stream("GET", "/zipbomb");
  12570. ASSERT_TRUE(stream.is_valid());
  12571. char buffer[64 * 1024];
  12572. ssize_t n;
  12573. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12574. total_decompressed += static_cast<size_t>(n);
  12575. }
  12576. }
  12577. // The decompressed size must be capped by payload_max_length. Without
  12578. // protection, the client would decompress the full 10MB from a tiny
  12579. // compressed payload, enabling a zip bomb DoS attack.
  12580. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12581. << "Client decompressed " << total_decompressed
  12582. << " bytes from a gzip response. The decompressed size should be "
  12583. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12584. }
  12585. #endif
  12586. TEST(HostAndPortPropertiesTest, NoSSL) {
  12587. httplib::Client cli("www.google.com", 1234);
  12588. ASSERT_EQ("www.google.com", cli.host());
  12589. ASSERT_EQ(1234, cli.port());
  12590. }
  12591. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12592. httplib::Client cli("www.google.com:1234");
  12593. ASSERT_EQ("www.google.com", cli.host());
  12594. ASSERT_EQ(1234, cli.port());
  12595. }
  12596. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12597. // Port number that overflows int — should not crash, client becomes invalid
  12598. httplib::Client cli("http://www.google.com:99999999999999999999");
  12599. ASSERT_FALSE(cli.is_valid());
  12600. }
  12601. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12602. // Port 99999 exceeds valid range (1-65535) — should not crash
  12603. httplib::Client cli("http://www.google.com:99999");
  12604. ASSERT_FALSE(cli.is_valid());
  12605. auto res = cli.Get("/");
  12606. EXPECT_FALSE(res);
  12607. EXPECT_EQ(Error::Connection, res.error());
  12608. }
  12609. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12610. httplib::Client cli("http://www.google.com:80abc");
  12611. ASSERT_FALSE(cli.is_valid());
  12612. }
  12613. #ifdef CPPHTTPLIB_SSL_ENABLED
  12614. TEST(HostAndPortPropertiesTest, SSL) {
  12615. httplib::SSLClient cli("www.google.com");
  12616. ASSERT_EQ("www.google.com", cli.host());
  12617. ASSERT_EQ(443, cli.port());
  12618. }
  12619. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12620. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12621. std::string cert;
  12622. read_file(CA_CERT_FILE, cert);
  12623. httplib::SSLClient httplib_client("www.google.com");
  12624. // Load CA store first time
  12625. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12626. // Load CA store second time (update)
  12627. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12628. // Verify client is still valid and can make connections
  12629. httplib_client.enable_server_certificate_verification(true);
  12630. auto res = httplib_client.Get("/");
  12631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12632. // Google may return 200 or 301 depending on various factors
  12633. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12634. res->status == StatusCode::MovedPermanently_301);
  12635. }
  12636. TEST(SSLClientTest, ServerNameIndication_Online) {
  12637. auto host = "httpbingo.org";
  12638. auto path = std::string{"/get"};
  12639. SSLClient cli(host, 443);
  12640. auto res = cli.Get(path);
  12641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12642. ASSERT_EQ(StatusCode::OK_200, res->status);
  12643. }
  12644. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12645. // Use a site that will cause SSL verification failure due to self-signed cert
  12646. SSLClient cli("self-signed.badssl.com", 443);
  12647. cli.enable_server_certificate_verification(true);
  12648. auto res = cli.Get("/");
  12649. ASSERT_TRUE(!res);
  12650. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12651. // Verify backend error is captured for SSLServerVerification
  12652. // This occurs when certificate verification fails
  12653. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12654. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12655. EXPECT_NE(0UL, res.ssl_backend_error());
  12656. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12657. // For OpenSSL, ssl_error is 0 for verification errors
  12658. EXPECT_EQ(0, res.ssl_error());
  12659. #if !defined(_WIN32) || \
  12660. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12661. // On non-Windows or when Windows Schannel is disabled, the error comes
  12662. // from OpenSSL's verification
  12663. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12664. res.ssl_backend_error());
  12665. #endif
  12666. #endif
  12667. }
  12668. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12669. // Use a site where hostname doesn't match the certificate
  12670. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12671. SSLClient cli("wrong.host.badssl.com", 443);
  12672. cli.enable_server_certificate_verification(true);
  12673. cli.enable_server_hostname_verification(true);
  12674. auto res = cli.Get("/");
  12675. ASSERT_TRUE(!res);
  12676. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12677. // Verify backend error is captured for hostname verification failure
  12678. EXPECT_NE(0UL, res.ssl_backend_error());
  12679. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12680. // For OpenSSL, ssl_error is 0 for verification errors
  12681. EXPECT_EQ(0, res.ssl_error());
  12682. #if !defined(_WIN32) || \
  12683. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12684. // On non-Windows or when Windows Schannel is disabled, the error comes
  12685. // from OpenSSL's hostname verification
  12686. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12687. res.ssl_backend_error());
  12688. #endif
  12689. #endif
  12690. }
  12691. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12692. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12693. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12694. SSLClient cli("www.google.com", 443);
  12695. cli.enable_server_certificate_verification(true);
  12696. auto res = cli.Get("/");
  12697. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12698. }
  12699. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12700. SSLClient cli("www.google.com", 443);
  12701. cli.enable_server_certificate_verification(true);
  12702. cli.enable_windows_certificate_verification(false);
  12703. auto res = cli.Get("/");
  12704. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12705. }
  12706. // The server sends an intermediate cross-signed by a root Windows trusts,
  12707. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12708. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12709. SSLClient cli("accounts.spotify.com", 443);
  12710. auto res = cli.Get("/");
  12711. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12712. << " ssl_backend_error=" << res.ssl_backend_error();
  12713. }
  12714. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12715. // policy status, which no backend reports for a self-signed certificate.
  12716. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12717. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12718. ASSERT_TRUE(svr.is_valid());
  12719. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12720. auto se = detail::scope_exit([&] {
  12721. svr.stop();
  12722. t.join();
  12723. ASSERT_FALSE(svr.is_running());
  12724. });
  12725. svr.wait_until_ready();
  12726. SSLClient cli("127.0.0.1", PORT);
  12727. cli.set_connection_timeout(30);
  12728. auto res = cli.Get("/");
  12729. ASSERT_FALSE(res);
  12730. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12731. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12732. }
  12733. #endif
  12734. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12735. Client cli("https://google.com");
  12736. auto res = cli.Get("/");
  12737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12738. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12739. }
  12740. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12741. SSLClient cli("google.com");
  12742. cli.set_ca_cert_path(CA_CERT_FILE);
  12743. auto res = cli.Get("/");
  12744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12745. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12746. }
  12747. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12748. SSLClient cli("google.com");
  12749. cli.enable_server_certificate_verification(true);
  12750. cli.set_ca_cert_path("hello");
  12751. auto res = cli.Get("/");
  12752. ASSERT_TRUE(!res);
  12753. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12754. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12755. // should be set
  12756. EXPECT_EQ(0, res.ssl_error());
  12757. // Verify backend error is captured for SSLLoadingCerts
  12758. // This error occurs when loading CA certificates fails
  12759. EXPECT_NE(0UL, res.ssl_backend_error());
  12760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12761. // OpenSSL specific error codes:
  12762. // > openssl errstr 0x80000002
  12763. // error:80000002:system library::No such file or directory
  12764. // > openssl errstr 0xA000126
  12765. // error:0A000126:SSL routines::unexpected eof while reading
  12766. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12767. res.ssl_backend_error() == 0xA000126);
  12768. #endif
  12769. }
  12770. TEST(SSLClientTest, ServerCertificateVerification4) {
  12771. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12772. ASSERT_TRUE(svr.is_valid());
  12773. svr.Get("/test", [&](const Request &, Response &res) {
  12774. res.set_content("test", "text/plain");
  12775. svr.stop();
  12776. ASSERT_TRUE(true);
  12777. });
  12778. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12779. auto se = detail::scope_exit([&] {
  12780. t.join();
  12781. ASSERT_FALSE(svr.is_running());
  12782. });
  12783. svr.wait_until_ready();
  12784. SSLClient cli("127.0.0.1", PORT);
  12785. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12786. cli.enable_server_certificate_verification(true);
  12787. cli.set_connection_timeout(30);
  12788. auto res = cli.Get("/test");
  12789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12790. ASSERT_EQ(StatusCode::OK_200, res->status);
  12791. }
  12792. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12793. std::string cert;
  12794. read_file(CA_CERT_FILE, cert);
  12795. SSLClient cli("google.com");
  12796. cli.load_ca_cert_store(cert.data(), cert.size());
  12797. const auto res = cli.Get("/");
  12798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12799. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12800. }
  12801. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12802. // clang-format off
  12803. static constexpr char cert[] =
  12804. "GlobalSign Root CA\n"
  12805. "==================\n"
  12806. "-----BEGIN CERTIFICATE-----\n"
  12807. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12808. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12809. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12810. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12811. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12812. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12813. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12814. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12815. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12816. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12817. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12818. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12819. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12820. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12821. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12822. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12823. "-----END CERTIFICATE-----\n";
  12824. // clang-format on
  12825. SSLClient cli("google.com");
  12826. cli.load_ca_cert_store(cert, sizeof(cert));
  12827. const auto res = cli.Get("/");
  12828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12829. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12830. }
  12831. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12832. SSLClient cli("www.youtube.com");
  12833. cli.set_ca_cert_path(CA_CERT_FILE);
  12834. cli.enable_server_certificate_verification(true);
  12835. cli.set_follow_location(true);
  12836. auto res = cli.Get("/");
  12837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12838. ASSERT_EQ(StatusCode::OK_200, res->status);
  12839. }
  12840. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12841. SSLClient cli("wWw.YouTube.Com");
  12842. cli.set_ca_cert_path(CA_CERT_FILE);
  12843. cli.enable_server_certificate_verification(true);
  12844. cli.enable_server_hostname_verification(true);
  12845. cli.set_follow_location(true);
  12846. auto res = cli.Get("/");
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. ASSERT_EQ(StatusCode::OK_200, res->status);
  12849. }
  12850. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12851. SSLClient cli("gOoGlE.COm");
  12852. cli.enable_server_certificate_verification(true);
  12853. cli.enable_server_hostname_verification(true);
  12854. cli.set_follow_location(true);
  12855. auto res = cli.Get("/");
  12856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12857. ASSERT_EQ(StatusCode::OK_200, res->status);
  12858. }
  12859. TEST(SSLClientTest, Issue2004_Online) {
  12860. Client client("https://google.com");
  12861. client.set_follow_location(true);
  12862. auto res = client.Get("/");
  12863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12864. ASSERT_EQ(StatusCode::OK_200, res->status);
  12865. auto body = res->body;
  12866. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12867. }
  12868. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12869. // Create SSLClient with invalid cert/key to make is_valid() return false
  12870. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12871. "nonexistent_key.pem");
  12872. // is_valid() should be false due to cert loading failure
  12873. ASSERT_FALSE(cli.is_valid());
  12874. auto res = cli.Get("/");
  12875. ASSERT_FALSE(res);
  12876. EXPECT_EQ(Error::SSLConnection, res.error());
  12877. }
  12878. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12879. // Test for Issue #2251: SSL error not properly reported when client cert
  12880. // and key paths are swapped or mismatched
  12881. // This simulates the scenario where user accidentally swaps the cert and key
  12882. // files
  12883. // Using client cert file as private key and vice versa (completely wrong)
  12884. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12885. // Should fail validation due to cert/key mismatch
  12886. ASSERT_FALSE(cli.is_valid());
  12887. // Attempt to make a request should fail with proper error
  12888. auto res = cli.Get("/");
  12889. ASSERT_FALSE(res);
  12890. EXPECT_EQ(Error::SSLConnection, res.error());
  12891. // SSL error should be recorded in the Result object (this is the key fix for
  12892. // Issue #2251)
  12893. auto backend_error = res.ssl_backend_error();
  12894. EXPECT_NE(0u, backend_error);
  12895. }
  12896. // Tests cert/key mismatch detection at the TLS context level
  12897. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12898. // Test that using mismatched cert/key causes connection failure.
  12899. // We verify this at the SSLClient level rather than through internal
  12900. // TLS API functions.
  12901. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12902. cli.enable_server_certificate_verification(false);
  12903. cli.set_connection_timeout(2);
  12904. // The mismatch should cause a connection or handshake error
  12905. auto res = cli.Get("/test");
  12906. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12907. // Either way, the request should fail
  12908. EXPECT_FALSE(res);
  12909. }
  12910. #endif
  12911. #if 0
  12912. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12913. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12914. ASSERT_TRUE(cli != nullptr);
  12915. cli->set_address_family(AF_INET6);
  12916. cli->set_interface("en0");
  12917. auto res = cli->Get("/get");
  12918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12919. ASSERT_EQ(StatusCode::OK_200, res->status);
  12920. }
  12921. #endif
  12922. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12923. #ifdef CPPHTTPLIB_SSL_ENABLED
  12924. void ClientCertPresent(
  12925. const std::string &client_cert_file,
  12926. const std::string &client_private_key_file,
  12927. const std::string &client_encrypted_private_key_pass = std::string()) {
  12928. using namespace httplib::tls;
  12929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12930. CLIENT_CA_CERT_DIR);
  12931. ASSERT_TRUE(svr.is_valid());
  12932. svr.Get("/test", [&](const Request &req, Response &res) {
  12933. res.set_content("test", "text/plain");
  12934. auto cert = req.peer_cert();
  12935. ASSERT_TRUE(static_cast<bool>(cert));
  12936. std::string common_name = cert.subject_cn();
  12937. EXPECT_EQ("Common Name", common_name);
  12938. });
  12939. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12940. auto se = detail::scope_exit([&] {
  12941. svr.stop();
  12942. t.join();
  12943. ASSERT_FALSE(svr.is_running());
  12944. });
  12945. svr.wait_until_ready();
  12946. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12947. client_encrypted_private_key_pass);
  12948. cli.enable_server_certificate_verification(false);
  12949. cli.set_connection_timeout(30);
  12950. auto res = cli.Get("/test");
  12951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12952. ASSERT_EQ(StatusCode::OK_200, res->status);
  12953. }
  12954. TEST(SSLClientServerTest, ClientCertPresent) {
  12955. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12956. }
  12957. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12958. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12959. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12960. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12961. }
  12962. // PEM memory-based constructor tests (works with all TLS backends)
  12963. void PemMemoryClientCertPresent(
  12964. const std::string &client_cert_file,
  12965. const std::string &client_private_key_file,
  12966. const std::string &client_encrypted_private_key_pass = std::string()) {
  12967. // Read PEM files into memory
  12968. std::string server_cert_pem, server_key_pem;
  12969. std::string client_ca_pem;
  12970. std::string client_cert_pem, client_key_pem;
  12971. read_file(SERVER_CERT_FILE, server_cert_pem);
  12972. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12973. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12974. read_file(client_cert_file, client_cert_pem);
  12975. read_file(client_private_key_file, client_key_pem);
  12976. // Create server with PEM memory
  12977. SSLServer::PemMemory server_pem = {
  12978. server_cert_pem.c_str(),
  12979. server_cert_pem.size(),
  12980. server_key_pem.c_str(),
  12981. server_key_pem.size(),
  12982. client_ca_pem.c_str(),
  12983. client_ca_pem.size(),
  12984. nullptr // no password for server key
  12985. };
  12986. SSLServer svr(server_pem);
  12987. ASSERT_TRUE(svr.is_valid());
  12988. svr.Get("/test", [&](const Request &, Response &res) {
  12989. res.set_content("test", "text/plain");
  12990. });
  12991. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12992. auto se = detail::scope_exit([&] {
  12993. svr.stop();
  12994. t.join();
  12995. ASSERT_FALSE(svr.is_running());
  12996. });
  12997. svr.wait_until_ready();
  12998. // Create client with PEM memory
  12999. const char *password = client_encrypted_private_key_pass.empty()
  13000. ? nullptr
  13001. : client_encrypted_private_key_pass.c_str();
  13002. SSLClient::PemMemory client_pem = {
  13003. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13004. client_key_pem.size(), password};
  13005. SSLClient cli(HOST, PORT, client_pem);
  13006. cli.enable_server_certificate_verification(false);
  13007. cli.set_connection_timeout(30);
  13008. auto res = cli.Get("/test");
  13009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13010. ASSERT_EQ(StatusCode::OK_200, res->status);
  13011. }
  13012. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13013. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13014. }
  13015. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13016. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13017. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13018. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13019. }
  13020. TEST(SSLClientServerTest, ClientCertMissing) {
  13021. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13022. CLIENT_CA_CERT_DIR);
  13023. ASSERT_TRUE(svr.is_valid());
  13024. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13025. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13026. auto se = detail::scope_exit([&] {
  13027. svr.stop();
  13028. t.join();
  13029. ASSERT_FALSE(svr.is_running());
  13030. });
  13031. svr.wait_until_ready();
  13032. SSLClient cli(HOST, PORT);
  13033. cli.set_connection_timeout(30);
  13034. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13035. // the chain check on Windows, so the result does not depend on the order.
  13036. cli.enable_server_hostname_verification(false);
  13037. auto res = cli.Get("/test");
  13038. ASSERT_TRUE(!res);
  13039. // When client cert is missing and server requires it, connection fails
  13040. // Error type depends on backend implementation
  13041. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13042. res.error() == Error::SSLConnection);
  13043. // Verify backend error is captured
  13044. // Note: This test may have different error codes depending on the exact
  13045. // verification failure
  13046. EXPECT_NE(0UL, res.ssl_backend_error());
  13047. }
  13048. TEST(SSLClientServerTest, TrustDirOptional) {
  13049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13050. ASSERT_TRUE(svr.is_valid());
  13051. svr.Get("/test", [&](const Request &, Response &res) {
  13052. res.set_content("test", "text/plain");
  13053. });
  13054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13055. auto se = detail::scope_exit([&] {
  13056. svr.stop();
  13057. t.join();
  13058. ASSERT_FALSE(svr.is_running());
  13059. });
  13060. svr.wait_until_ready();
  13061. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13062. cli.enable_server_certificate_verification(false);
  13063. cli.set_connection_timeout(30);
  13064. auto res = cli.Get("/test");
  13065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13066. ASSERT_EQ(StatusCode::OK_200, res->status);
  13067. }
  13068. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13069. class NoListenSSLServer : public SSLServer {
  13070. public:
  13071. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13072. const char *client_ca_cert_file_path,
  13073. const char *client_ca_cert_dir_path = nullptr)
  13074. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13075. client_ca_cert_dir_path),
  13076. stop_(false) {}
  13077. std::atomic_bool stop_;
  13078. private:
  13079. bool process_and_close_socket(socket_t /*sock*/) override {
  13080. // Don't create SSL context
  13081. while (!stop_.load()) {
  13082. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13083. }
  13084. return true;
  13085. }
  13086. };
  13087. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13088. CLIENT_CA_CERT_FILE);
  13089. ASSERT_TRUE(svr.is_valid());
  13090. svr.Get("/test", [&](const Request &, Response &res) {
  13091. res.set_content("test", "text/plain");
  13092. });
  13093. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13094. auto se = detail::scope_exit([&] {
  13095. svr.stop_ = true;
  13096. svr.stop();
  13097. t.join();
  13098. ASSERT_FALSE(svr.is_running());
  13099. });
  13100. svr.wait_until_ready();
  13101. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13102. cli.enable_server_certificate_verification(false);
  13103. cli.set_connection_timeout(1);
  13104. auto res = cli.Get("/test");
  13105. ASSERT_TRUE(!res);
  13106. EXPECT_EQ(Error::SSLConnection, res.error());
  13107. // Timeout results in WantRead error code (maps to backend-specific value)
  13108. EXPECT_NE(0, res.ssl_error());
  13109. }
  13110. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13111. // Test SSLServer with client certificate verification using the standard
  13112. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13114. CLIENT_CA_CERT_DIR);
  13115. ASSERT_TRUE(svr.is_valid());
  13116. svr.Get("/test", [&](const Request &req, Response &res) {
  13117. res.set_content("test", "text/plain");
  13118. auto cert = req.peer_cert();
  13119. ASSERT_TRUE(static_cast<bool>(cert));
  13120. auto common_name = cert.subject_cn();
  13121. EXPECT_EQ("Common Name", common_name);
  13122. });
  13123. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13124. auto se = detail::scope_exit([&] {
  13125. svr.stop();
  13126. t.join();
  13127. ASSERT_FALSE(svr.is_running());
  13128. });
  13129. svr.wait_until_ready();
  13130. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13131. cli.enable_server_certificate_verification(false);
  13132. cli.set_connection_timeout(30);
  13133. auto res = cli.Get("/test");
  13134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13135. ASSERT_EQ(StatusCode::OK_200, res->status);
  13136. }
  13137. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13138. // Verifies that wildcard matching and exact matching work consistently
  13139. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13140. using namespace httplib::tls;
  13141. // We need a running server to test against
  13142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13143. ASSERT_TRUE(svr.is_valid());
  13144. svr.Get("/test", [](const Request &, Response &res) {
  13145. res.set_content("ok", "text/plain");
  13146. });
  13147. thread t([&]() { svr.listen(HOST, PORT); });
  13148. auto se = detail::scope_exit([&] {
  13149. svr.stop();
  13150. t.join();
  13151. });
  13152. svr.wait_until_ready();
  13153. bool verify_callback_called = false;
  13154. bool verify_result_wrong = false;
  13155. SSLClient cli(HOST, PORT);
  13156. cli.enable_server_certificate_verification(true);
  13157. cli.set_ca_cert_path(CA_CERT_FILE);
  13158. cli.set_connection_timeout(5);
  13159. // Note: Test certificate has CN="Common Name", not "localhost"
  13160. bool verify_result_cn = false;
  13161. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13162. verify_callback_called = true;
  13163. if (!ctx.cert) return false;
  13164. // Test 1: "Common Name" should match (our test server cert CN)
  13165. verify_result_cn = ctx.check_hostname("Common Name");
  13166. // Test 2: wrong hostname should not match
  13167. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13168. return true; // Accept for the purpose of this test
  13169. });
  13170. auto res = cli.Get("/test");
  13171. // The request may succeed or fail depending on cert configuration
  13172. // but the callback should have been called
  13173. ASSERT_TRUE(verify_callback_called)
  13174. << "Verify callback should have been called";
  13175. // CN="Common Name" should match our test certificate
  13176. //
  13177. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13178. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13179. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13180. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13181. // <openssl/base.h>, which is included transitively when
  13182. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13183. #if defined(OPENSSL_IS_BORINGSSL)
  13184. EXPECT_FALSE(verify_result_cn)
  13185. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13186. #else
  13187. EXPECT_TRUE(verify_result_cn)
  13188. << "verify_hostname should match 'Common Name' (certificate CN)";
  13189. #endif
  13190. // Wrong hostname should not match
  13191. EXPECT_FALSE(verify_result_wrong)
  13192. << "verify_hostname should not match 'wronghost.example.com'";
  13193. }
  13194. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13195. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13196. // X509_check_ip behavior and must hold for every backend.
  13197. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13198. using namespace httplib::tls;
  13199. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13200. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13201. ASSERT_TRUE(svr.is_valid());
  13202. svr.Get("/test", [](const Request &, Response &res) {
  13203. res.set_content("ok", "text/plain");
  13204. });
  13205. thread t([&]() { svr.listen(HOST, PORT); });
  13206. auto se = detail::scope_exit([&] {
  13207. svr.stop();
  13208. t.join();
  13209. });
  13210. svr.wait_until_ready();
  13211. bool verify_callback_called = false;
  13212. bool ip_matched_via_cn = true;
  13213. SSLClient cli(HOST, PORT);
  13214. cli.enable_server_certificate_verification(true);
  13215. cli.set_ca_cert_path(CA_CERT_FILE);
  13216. cli.set_connection_timeout(5);
  13217. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13218. verify_callback_called = true;
  13219. if (!ctx.cert) return false;
  13220. // The IP appears only in the CN, so it must NOT be accepted.
  13221. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13222. return true; // Accept for the purpose of this test
  13223. });
  13224. cli.Get("/test");
  13225. ASSERT_TRUE(verify_callback_called)
  13226. << "Verify callback should have been called";
  13227. EXPECT_FALSE(ip_matched_via_cn)
  13228. << "An IP host must not be authenticated via the certificate CN";
  13229. }
  13230. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13231. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13232. using namespace httplib::tls;
  13233. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13234. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13235. ASSERT_TRUE(svr.is_valid());
  13236. svr.Get("/test", [](const Request &, Response &res) {
  13237. res.set_content("ok", "text/plain");
  13238. });
  13239. thread t([&]() { svr.listen(HOST, PORT); });
  13240. auto se = detail::scope_exit([&] {
  13241. svr.stop();
  13242. t.join();
  13243. });
  13244. svr.wait_until_ready();
  13245. bool verify_callback_called = false;
  13246. bool san_matched = false;
  13247. bool wrong_ipv6_matched = true;
  13248. bool cn_ipv6_matched = true;
  13249. SSLClient cli(HOST, PORT);
  13250. cli.enable_server_certificate_verification(true);
  13251. cli.set_ca_cert_path(CA_CERT_FILE);
  13252. cli.set_connection_timeout(5);
  13253. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13254. verify_callback_called = true;
  13255. if (!ctx.cert) return false;
  13256. // Matches the IPv6 iPAddress SAN.
  13257. san_matched = ctx.check_hostname("2001:db8::1");
  13258. // A different IPv6 address must not match.
  13259. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13260. // "::1" lives only in the CN, so it must not be accepted.
  13261. cn_ipv6_matched = ctx.check_hostname("::1");
  13262. return true; // Accept for the purpose of this test
  13263. });
  13264. cli.Get("/test");
  13265. ASSERT_TRUE(verify_callback_called)
  13266. << "Verify callback should have been called";
  13267. EXPECT_TRUE(san_matched)
  13268. << "verify_hostname should match an IPv6 iPAddress SAN";
  13269. EXPECT_FALSE(wrong_ipv6_matched)
  13270. << "verify_hostname should not match a non-matching IPv6 address";
  13271. EXPECT_FALSE(cn_ipv6_matched)
  13272. << "An IPv6 host must not be authenticated via the certificate CN";
  13273. }
  13274. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13275. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13276. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13277. using namespace httplib::tls;
  13278. // SANs: DNS:a.zz, IP:42.46.122.122
  13279. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13280. ASSERT_TRUE(svr.is_valid());
  13281. svr.Get("/test", [](const Request &, Response &res) {
  13282. res.set_content("ok", "text/plain");
  13283. });
  13284. auto port = svr.bind_to_any_port(HOST);
  13285. thread t([&]() { svr.listen_after_bind(); });
  13286. auto se = detail::scope_exit([&] {
  13287. svr.stop();
  13288. t.join();
  13289. });
  13290. svr.wait_until_ready();
  13291. bool verify_callback_called = false;
  13292. bool dns_san_matched = false;
  13293. bool ip_san_matched = false;
  13294. bool ip_matched_via_dns_san = true;
  13295. bool dns_matched_via_ip_san = true;
  13296. SSLClient cli(HOST, port);
  13297. cli.enable_server_certificate_verification(true);
  13298. cli.set_ca_cert_path(CA_CERT_FILE);
  13299. cli.set_connection_timeout(5);
  13300. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13301. verify_callback_called = true;
  13302. if (!ctx.cert) return false;
  13303. dns_san_matched = ctx.check_hostname("a.zz");
  13304. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13305. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13306. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13307. return true; // Accept for the purpose of this test
  13308. });
  13309. cli.Get("/test");
  13310. ASSERT_TRUE(verify_callback_called)
  13311. << "Verify callback should have been called";
  13312. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13313. EXPECT_TRUE(ip_san_matched)
  13314. << "verify_hostname should match an iPAddress SAN";
  13315. EXPECT_FALSE(ip_matched_via_dns_san)
  13316. << "An IP host must not be authenticated via a dNSName SAN";
  13317. EXPECT_FALSE(dns_matched_via_ip_san)
  13318. << "A DNS host must not be authenticated via an iPAddress SAN";
  13319. }
  13320. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13321. // "www.*.example.test" names one host and not every host under example.test.
  13322. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13323. using namespace httplib::tls;
  13324. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13325. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. svr.Get("/test", [](const Request &, Response &res) {
  13328. res.set_content("ok", "text/plain");
  13329. });
  13330. auto port = svr.bind_to_any_port(HOST);
  13331. thread t([&]() { svr.listen_after_bind(); });
  13332. auto se = detail::scope_exit([&] {
  13333. svr.stop();
  13334. t.join();
  13335. });
  13336. svr.wait_until_ready();
  13337. bool verify_callback_called = false;
  13338. bool leftmost_wildcard_matched = false;
  13339. bool wildcard_spanned_labels = true;
  13340. bool inner_wildcard_matched = true;
  13341. SSLClient cli(HOST, port);
  13342. cli.enable_server_certificate_verification(true);
  13343. cli.set_ca_cert_path(CA_CERT_FILE);
  13344. cli.set_connection_timeout(5);
  13345. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13346. verify_callback_called = true;
  13347. if (!ctx.cert) return false;
  13348. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13349. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13350. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13351. return true; // Accept for the purpose of this test
  13352. });
  13353. cli.Get("/test");
  13354. ASSERT_TRUE(verify_callback_called)
  13355. << "Verify callback should have been called";
  13356. EXPECT_TRUE(leftmost_wildcard_matched)
  13357. << "A leftmost wildcard should match a single label";
  13358. EXPECT_FALSE(wildcard_spanned_labels)
  13359. << "A wildcard label must not match more than one label";
  13360. EXPECT_FALSE(inner_wildcard_matched)
  13361. << "A wildcard outside the leftmost label must not be honoured";
  13362. }
  13363. // sans() must report each SAN entry under its own type.
  13364. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13365. using namespace httplib::tls;
  13366. // SANs: DNS:a.zz, IP:42.46.122.122
  13367. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13368. ASSERT_TRUE(svr.is_valid());
  13369. svr.Get("/test", [](const Request &, Response &res) {
  13370. res.set_content("ok", "text/plain");
  13371. });
  13372. auto port = svr.bind_to_any_port(HOST);
  13373. thread t([&]() { svr.listen_after_bind(); });
  13374. auto se = detail::scope_exit([&] {
  13375. svr.stop();
  13376. t.join();
  13377. });
  13378. svr.wait_until_ready();
  13379. bool verify_callback_called = false;
  13380. std::vector<SanEntry> sans;
  13381. SSLClient cli(HOST, port);
  13382. cli.enable_server_certificate_verification(true);
  13383. cli.set_ca_cert_path(CA_CERT_FILE);
  13384. cli.set_connection_timeout(5);
  13385. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13386. verify_callback_called = true;
  13387. if (!ctx.cert) return false;
  13388. sans = ctx.sans();
  13389. return true; // Accept for the purpose of this test
  13390. });
  13391. cli.Get("/test");
  13392. ASSERT_TRUE(verify_callback_called)
  13393. << "Verify callback should have been called";
  13394. auto has_san = [&](SanType type, const std::string &value) {
  13395. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13396. return san.type == type && san.value == value;
  13397. });
  13398. };
  13399. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13400. << "sans() should report the dNSName SAN";
  13401. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13402. << "sans() should report the iPAddress SAN";
  13403. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13404. << "sans() must not report the dNSName SAN as an address";
  13405. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13406. << "sans() must not report the iPAddress SAN as a DNS name";
  13407. }
  13408. #endif
  13409. // mbedTLS-specific callback constructor test
  13410. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13411. #ifdef CPPHTTPLIB_SSL_ENABLED
  13412. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13414. ASSERT_TRUE(svr.is_valid());
  13415. // Set up a handler to verify client certificate is present
  13416. bool client_cert_verified = false;
  13417. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13418. // Verify that client certificate was provided
  13419. client_cert_verified = true;
  13420. res.set_content("success", "text/plain");
  13421. });
  13422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13423. auto se = detail::scope_exit([&] {
  13424. svr.stop();
  13425. t.join();
  13426. ASSERT_FALSE(svr.is_running());
  13427. });
  13428. svr.wait_until_ready();
  13429. // Client with certificate
  13430. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13431. cli.enable_server_certificate_verification(false);
  13432. cli.set_connection_timeout(30);
  13433. auto res = cli.Get("/test");
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. ASSERT_EQ(StatusCode::OK_200, res->status);
  13436. ASSERT_TRUE(client_cert_verified);
  13437. EXPECT_EQ("success", res->body);
  13438. }
  13439. #endif
  13440. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13441. // backends
  13442. #ifdef CPPHTTPLIB_SSL_ENABLED
  13443. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13444. using namespace httplib::tls;
  13445. // Test that when client CA cert file is provided,
  13446. // the server properly requests and validates client certificates
  13447. // Create a server with client authentication
  13448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13449. ASSERT_TRUE(svr.is_valid());
  13450. bool handler_called = false;
  13451. svr.Get("/test", [&](const Request &req, Response &res) {
  13452. handler_called = true;
  13453. // Verify that a client certificate was provided
  13454. auto cert = req.peer_cert();
  13455. ASSERT_TRUE(static_cast<bool>(cert));
  13456. // Get the issuer name
  13457. std::string issuer_str = cert.issuer_name();
  13458. ASSERT_FALSE(issuer_str.empty());
  13459. // The client certificate should be issued by our test CA
  13460. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13461. res.set_content("authenticated", "text/plain");
  13462. });
  13463. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13464. auto se = detail::scope_exit([&] {
  13465. svr.stop();
  13466. t.join();
  13467. ASSERT_FALSE(svr.is_running());
  13468. });
  13469. svr.wait_until_ready();
  13470. // Connect with a client certificate issued by the CA
  13471. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13472. cli.enable_server_certificate_verification(false);
  13473. cli.set_connection_timeout(30);
  13474. auto res = cli.Get("/test");
  13475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13476. ASSERT_EQ(StatusCode::OK_200, res->status);
  13477. ASSERT_TRUE(handler_called);
  13478. EXPECT_EQ("authenticated", res->body);
  13479. }
  13480. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13481. using namespace httplib::tls;
  13482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13483. ASSERT_TRUE(svr.is_valid());
  13484. svr.Get("/test", [](const Request &, Response &res) {
  13485. res.set_content("ok", "text/plain");
  13486. });
  13487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13488. auto se = detail::scope_exit([&] {
  13489. svr.stop();
  13490. t.join();
  13491. });
  13492. svr.wait_until_ready();
  13493. SSLClient cli(HOST, PORT);
  13494. cli.enable_server_certificate_verification(false);
  13495. cli.set_connection_timeout(30);
  13496. bool cert_checked = false;
  13497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13498. if (ctx.cert) {
  13499. auto sans = ctx.sans();
  13500. // Test certificate may or may not have SANs - just verify the API
  13501. // works If SANs exist, verify the types are valid
  13502. for (const auto &san : sans) {
  13503. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13504. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13505. san.type == SanType::OTHER);
  13506. EXPECT_FALSE(san.value.empty());
  13507. }
  13508. cert_checked = true;
  13509. }
  13510. return true;
  13511. });
  13512. auto res = cli.Get("/test");
  13513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13514. EXPECT_TRUE(cert_checked);
  13515. }
  13516. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13517. using namespace httplib::tls;
  13518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13519. ASSERT_TRUE(svr.is_valid());
  13520. svr.Get("/test", [](const Request &, Response &res) {
  13521. res.set_content("ok", "text/plain");
  13522. });
  13523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13524. auto se = detail::scope_exit([&] {
  13525. svr.stop();
  13526. t.join();
  13527. });
  13528. svr.wait_until_ready();
  13529. SSLClient cli(HOST, PORT);
  13530. cli.enable_server_certificate_verification(false);
  13531. cli.set_connection_timeout(30);
  13532. bool validity_checked = false;
  13533. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13534. if (ctx.cert) {
  13535. time_t not_before = 0, not_after = 0;
  13536. bool result = ctx.validity(not_before, not_after);
  13537. EXPECT_TRUE(result);
  13538. // Verify that not_before < now < not_after for a valid cert
  13539. time_t now = time(nullptr);
  13540. EXPECT_LT(not_before, now);
  13541. EXPECT_GT(not_after, now);
  13542. validity_checked = true;
  13543. }
  13544. return true;
  13545. });
  13546. auto res = cli.Get("/test");
  13547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13548. EXPECT_TRUE(validity_checked);
  13549. }
  13550. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13551. using namespace httplib::tls;
  13552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13553. ASSERT_TRUE(svr.is_valid());
  13554. svr.Get("/test", [](const Request &, Response &res) {
  13555. res.set_content("ok", "text/plain");
  13556. });
  13557. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13558. auto se = detail::scope_exit([&] {
  13559. svr.stop();
  13560. t.join();
  13561. });
  13562. svr.wait_until_ready();
  13563. SSLClient cli(HOST, PORT);
  13564. cli.enable_server_certificate_verification(false);
  13565. cli.set_connection_timeout(30);
  13566. bool serial_checked = false;
  13567. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13568. if (ctx.cert) {
  13569. std::string serial = ctx.serial();
  13570. EXPECT_FALSE(serial.empty());
  13571. // Serial should be a hex string
  13572. for (char c : serial) {
  13573. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13574. (c >= 'a' && c <= 'f'));
  13575. }
  13576. serial_checked = true;
  13577. }
  13578. return true;
  13579. });
  13580. auto res = cli.Get("/test");
  13581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13582. EXPECT_TRUE(serial_checked);
  13583. }
  13584. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13585. // Test 1: Valid CA file - no error should be recorded
  13586. {
  13587. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13588. CLIENT_CA_CERT_FILE);
  13589. ASSERT_TRUE(svr.is_valid());
  13590. // With valid setup, last_ssl_error should be 0
  13591. EXPECT_EQ(0, svr.ssl_last_error());
  13592. }
  13593. // Test 2: Invalid CA file content
  13594. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13595. {
  13596. // Create a temporary file with completely invalid content
  13597. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13598. {
  13599. std::ofstream ofs(temp_invalid_ca);
  13600. ofs << "This is not a certificate file at all\n";
  13601. ofs << "Just plain text content\n";
  13602. }
  13603. // Create server with invalid CA file
  13604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13605. // Clean up temporary file
  13606. std::remove(temp_invalid_ca);
  13607. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13608. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13609. // Note: SSL_CTX_load_verify_locations typically fails first,
  13610. // but our error handling code path is still exercised
  13611. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13612. }
  13613. }
  13614. TEST(VerifyCallbackTest, VerifyContextFields) {
  13615. using namespace httplib::tls;
  13616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13617. ASSERT_TRUE(svr.is_valid());
  13618. svr.Get("/test", [](const Request &, Response &res) {
  13619. res.set_content("ok", "text/plain");
  13620. });
  13621. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13622. auto se = detail::scope_exit([&] {
  13623. svr.stop();
  13624. t.join();
  13625. });
  13626. svr.wait_until_ready();
  13627. SSLClient cli(HOST, PORT);
  13628. cli.enable_server_certificate_verification(false);
  13629. cli.set_connection_timeout(30);
  13630. int callback_count = 0;
  13631. bool saw_leaf_cert = false;
  13632. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13633. if (ctx.cert) {
  13634. callback_count++;
  13635. // We should see at least one certificate (the leaf)
  13636. std::string cn = ctx.subject_cn();
  13637. if (!cn.empty()) { saw_leaf_cert = true; }
  13638. // Verify context fields are populated
  13639. EXPECT_NE(ctx.session, nullptr);
  13640. EXPECT_GE(ctx.depth, 0);
  13641. }
  13642. return true;
  13643. });
  13644. auto res = cli.Get("/test");
  13645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13646. EXPECT_GT(callback_count, 0);
  13647. EXPECT_TRUE(saw_leaf_cert);
  13648. }
  13649. // A verifier belongs to the client that set it, not to the thread that set it.
  13650. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13651. using namespace httplib::tls;
  13652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13653. ASSERT_TRUE(svr.is_valid());
  13654. svr.Get("/test", [](const Request &, Response &res) {
  13655. res.set_content("ok", "text/plain");
  13656. });
  13657. auto port = svr.bind_to_any_port(HOST);
  13658. thread t([&]() { svr.listen_after_bind(); });
  13659. auto se = detail::scope_exit([&] {
  13660. svr.stop();
  13661. t.join();
  13662. });
  13663. svr.wait_until_ready();
  13664. auto rejecting_calls = 0;
  13665. SSLClient rejecting(HOST, port);
  13666. rejecting.enable_server_certificate_verification(false);
  13667. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13668. rejecting_calls++;
  13669. return false;
  13670. });
  13671. auto accepting_calls = 0;
  13672. SSLClient accepting(HOST, port);
  13673. accepting.enable_server_certificate_verification(false);
  13674. // Set on another thread than the requests below.
  13675. thread([&]() {
  13676. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13677. accepting_calls++;
  13678. return true;
  13679. });
  13680. }).join();
  13681. // Requested on another thread than the verifier was set on.
  13682. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13683. EXPECT_GT(rejecting_calls, 0);
  13684. auto res = accepting.Get("/test");
  13685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13686. EXPECT_GT(accepting_calls, 0);
  13687. }
  13688. // VerifyContext::session is the same handle the other tls:: functions take.
  13689. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13690. using namespace httplib::tls;
  13691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13692. ASSERT_TRUE(svr.is_valid());
  13693. svr.Get("/test", [](const Request &, Response &res) {
  13694. res.set_content("ok", "text/plain");
  13695. });
  13696. auto port = svr.bind_to_any_port(HOST);
  13697. thread t([&]() { svr.listen_after_bind(); });
  13698. auto se = detail::scope_exit([&] {
  13699. svr.stop();
  13700. t.join();
  13701. });
  13702. svr.wait_until_ready();
  13703. SSLClient cli(HOST, port);
  13704. cli.enable_server_certificate_verification(false);
  13705. session_t verifier_session = nullptr;
  13706. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13707. verifier_session = ctx.session;
  13708. return true;
  13709. });
  13710. session_t session_verifier_session = nullptr;
  13711. cli.set_session_verifier([&](session_t session) {
  13712. session_verifier_session = session;
  13713. return SSLVerifierResponse::NoDecisionMade;
  13714. });
  13715. auto res = cli.Get("/test");
  13716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13717. EXPECT_NE(nullptr, verifier_session);
  13718. EXPECT_EQ(session_verifier_session, verifier_session);
  13719. }
  13720. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13721. using httplib::tls::TlsError;
  13722. // Test that verify_error_to_string returns empty for success
  13723. std::string success_str = TlsError::verify_error_to_string(0);
  13724. EXPECT_TRUE(success_str.empty());
  13725. // Test that verify_error_to_string returns non-empty for error codes
  13726. // Using a common error code (certificate expired)
  13727. std::string error_str =
  13728. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13729. EXPECT_FALSE(error_str.empty());
  13730. }
  13731. TEST(SessionVerifierTest, CertificateAccepted) {
  13732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13733. ASSERT_TRUE(svr.is_valid());
  13734. svr.Get("/test", [](const Request &, Response &res) {
  13735. res.set_content("ok", "text/plain");
  13736. });
  13737. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13738. auto se = detail::scope_exit([&] {
  13739. svr.stop();
  13740. t.join();
  13741. });
  13742. svr.wait_until_ready();
  13743. SSLClient cli(HOST, PORT);
  13744. cli.enable_server_certificate_verification(false);
  13745. cli.set_connection_timeout(30);
  13746. bool callback_called = false;
  13747. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13748. EXPECT_NE(session, nullptr);
  13749. callback_called = true;
  13750. return SSLVerifierResponse::CertificateAccepted;
  13751. });
  13752. auto res = cli.Get("/test");
  13753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13754. EXPECT_EQ(200, res->status);
  13755. EXPECT_TRUE(callback_called);
  13756. }
  13757. TEST(SessionVerifierTest, CertificateRejected) {
  13758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13759. ASSERT_TRUE(svr.is_valid());
  13760. svr.Get("/test", [](const Request &, Response &res) {
  13761. res.set_content("ok", "text/plain");
  13762. });
  13763. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13764. auto se = detail::scope_exit([&] {
  13765. svr.stop();
  13766. t.join();
  13767. });
  13768. svr.wait_until_ready();
  13769. SSLClient cli(HOST, PORT);
  13770. cli.enable_server_certificate_verification(false);
  13771. cli.set_connection_timeout(30);
  13772. bool callback_called = false;
  13773. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13774. EXPECT_NE(session, nullptr);
  13775. callback_called = true;
  13776. return SSLVerifierResponse::CertificateRejected;
  13777. });
  13778. auto res = cli.Get("/test");
  13779. EXPECT_FALSE(res);
  13780. EXPECT_TRUE(callback_called);
  13781. }
  13782. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13784. ASSERT_TRUE(svr.is_valid());
  13785. svr.Get("/test", [](const Request &, Response &res) {
  13786. res.set_content("ok", "text/plain");
  13787. });
  13788. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13789. auto se = detail::scope_exit([&] {
  13790. svr.stop();
  13791. t.join();
  13792. });
  13793. svr.wait_until_ready();
  13794. // NoDecisionMade with verification disabled should succeed (no default check)
  13795. SSLClient cli(HOST, PORT);
  13796. cli.enable_server_certificate_verification(false);
  13797. cli.set_connection_timeout(30);
  13798. bool callback_called = false;
  13799. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13800. EXPECT_NE(session, nullptr);
  13801. callback_called = true;
  13802. return SSLVerifierResponse::NoDecisionMade;
  13803. });
  13804. auto res = cli.Get("/test");
  13805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13806. EXPECT_EQ(200, res->status);
  13807. EXPECT_TRUE(callback_called);
  13808. }
  13809. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13811. ASSERT_TRUE(svr.is_valid());
  13812. svr.Get("/test", [](const Request &, Response &res) {
  13813. res.set_content("ok", "text/plain");
  13814. });
  13815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13816. auto se = detail::scope_exit([&] {
  13817. svr.stop();
  13818. t.join();
  13819. });
  13820. svr.wait_until_ready();
  13821. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13822. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13823. // so we only check that the request fails, not whether the callback was
  13824. // called.
  13825. SSLClient cli(HOST, PORT);
  13826. cli.enable_server_certificate_verification(true);
  13827. cli.set_connection_timeout(30);
  13828. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13829. EXPECT_NE(session, nullptr);
  13830. return SSLVerifierResponse::NoDecisionMade;
  13831. });
  13832. auto res = cli.Get("/test");
  13833. EXPECT_FALSE(res);
  13834. }
  13835. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13836. // Test SSL server using PemMemory constructor with client CA certificates
  13837. // Read PEM files
  13838. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13839. read_file(SERVER_CERT_FILE, server_cert_pem);
  13840. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13841. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13842. // Create SSLServer with PemMemory constructor including client CA
  13843. SSLServer::PemMemory server_pem = {
  13844. server_cert_pem.c_str(),
  13845. server_cert_pem.size(),
  13846. server_key_pem.c_str(),
  13847. server_key_pem.size(),
  13848. client_ca_pem.c_str(),
  13849. client_ca_pem.size(),
  13850. nullptr // no password for server key
  13851. };
  13852. SSLServer svr(server_pem);
  13853. ASSERT_TRUE(svr.is_valid());
  13854. // No SSL error should be recorded for valid setup
  13855. EXPECT_EQ(0, svr.ssl_last_error());
  13856. // Set up server endpoints
  13857. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13858. res.set_content("ok", "text/plain");
  13859. });
  13860. // Start server in a thread
  13861. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13862. svr.wait_until_ready();
  13863. // Connect with client certificate (using constructor with paths)
  13864. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13865. cli.enable_server_certificate_verification(false);
  13866. auto res = cli.Get("/test-pem-ca");
  13867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13868. EXPECT_EQ(200, res->status);
  13869. EXPECT_EQ("ok", res->body);
  13870. svr.stop();
  13871. server_thread.join();
  13872. }
  13873. #endif
  13874. #ifdef _WIN32
  13875. TEST(CleanupTest, WSACleanup) {
  13876. int ret = WSACleanup();
  13877. ASSERT_EQ(0, ret);
  13878. }
  13879. #endif
  13880. #ifndef CPPHTTPLIB_SSL_ENABLED
  13881. TEST(NoSSLSupport, SimpleInterface) {
  13882. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13883. }
  13884. #endif
  13885. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13886. TEST(InvalidScheme, SimpleInterface) {
  13887. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13888. }
  13889. #endif
  13890. TEST(NoScheme, SimpleInterface) {
  13891. Client cli("yahoo.com:80");
  13892. ASSERT_TRUE(cli.is_valid());
  13893. }
  13894. TEST(SendAPI, SimpleInterface_Online) {
  13895. Client cli("http://yahoo.com");
  13896. Request req;
  13897. req.method = "GET";
  13898. req.path = "/";
  13899. auto res = cli.send(req);
  13900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13901. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13902. }
  13903. TEST(SendAPI, WithParamsInRequest) {
  13904. Server svr;
  13905. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13906. EXPECT_TRUE(req.has_param("test"));
  13907. EXPECT_EQ("test_value", req.get_param_value("test"));
  13908. });
  13909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13910. auto se = detail::scope_exit([&] {
  13911. svr.stop();
  13912. t.join();
  13913. ASSERT_FALSE(svr.is_running());
  13914. });
  13915. svr.wait_until_ready();
  13916. Client cli(HOST, PORT);
  13917. {
  13918. Request req;
  13919. req.method = "GET";
  13920. req.path = "/";
  13921. req.params.emplace("test", "test_value");
  13922. auto res = cli.send(req);
  13923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13924. }
  13925. {
  13926. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13928. }
  13929. }
  13930. TEST(ClientImplMethods, GetSocketTest) {
  13931. httplib::Server svr;
  13932. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13933. res.status = StatusCode::OK_200;
  13934. });
  13935. auto port = svr.bind_to_any_port("127.0.0.1");
  13936. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13937. auto se = detail::scope_exit([&] {
  13938. svr.stop();
  13939. thread.join();
  13940. ASSERT_FALSE(svr.is_running());
  13941. });
  13942. svr.wait_until_ready();
  13943. {
  13944. httplib::Client cli("127.0.0.1", port);
  13945. cli.set_keep_alive(true);
  13946. // Use the behavior of cpp-httplib of opening the connection
  13947. // only when the first request happens. If that changes,
  13948. // this test would be obsolete.
  13949. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13950. // This also implicitly tests the server. But other tests would fail much
  13951. // earlier than this one to be considered.
  13952. auto res = cli.Get("/");
  13953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13954. EXPECT_EQ(StatusCode::OK_200, res->status);
  13955. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13956. }
  13957. }
  13958. #ifdef CPPHTTPLIB_SSL_ENABLED
  13959. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13960. Client cli("http://yahoo.com");
  13961. auto res = cli.Get("/");
  13962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13963. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13964. cli.set_follow_location(true);
  13965. res = cli.Get("/");
  13966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13967. EXPECT_EQ(StatusCode::OK_200, res->status);
  13968. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13969. }
  13970. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13971. Client cli("https://yahoo.com");
  13972. auto res = cli.Get("/");
  13973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13974. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13975. cli.set_follow_location(true);
  13976. res = cli.Get("/");
  13977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13978. EXPECT_EQ(StatusCode::OK_200, res->status);
  13979. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13980. }
  13981. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13982. Client cli("https://yahoo.com");
  13983. auto res = cli.Get("/");
  13984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13985. ASSERT_FALSE(!res);
  13986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13987. ASSERT_FALSE(res == nullptr);
  13988. ASSERT_TRUE(res != nullptr);
  13989. EXPECT_EQ(Error::Success, res.error());
  13990. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13991. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13992. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13993. cli.set_follow_location(true);
  13994. res = cli.Get("/");
  13995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13996. EXPECT_EQ(Error::Success, res.error());
  13997. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13998. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13999. EXPECT_EQ(StatusCode::OK_200, res->status);
  14000. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14001. }
  14002. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14003. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14004. Client cli("https://cdnjs.cloudflare.com");
  14005. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14006. Headers{{"Accept-Encoding", "br"}});
  14007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14008. EXPECT_EQ(StatusCode::OK_200, res->status);
  14009. EXPECT_EQ(287630U, res->body.size());
  14010. EXPECT_EQ("application/javascript; charset=utf-8",
  14011. res->get_header_value("Content-Type"));
  14012. }
  14013. #endif
  14014. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14015. #undef REDIR_HOST // Silence compiler warning
  14016. #define REDIR_HOST "https://httpbingo.org"
  14017. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14018. Client cli(REDIR_HOST);
  14019. cli.set_follow_location(true);
  14020. auto res =
  14021. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. EXPECT_EQ(StatusCode::OK_200, res->status);
  14024. }
  14025. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14026. Client cli(REDIR_HOST);
  14027. cli.set_follow_location(true);
  14028. Params params;
  14029. params.emplace("url", "http://example.com");
  14030. params.emplace("status_code", "302");
  14031. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14033. EXPECT_EQ(StatusCode::OK_200, res->status);
  14034. }
  14035. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14036. Client cli(REDIR_HOST);
  14037. cli.set_follow_location(true);
  14038. Params params;
  14039. params.emplace("url", "http://example.com");
  14040. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14042. EXPECT_EQ(StatusCode::OK_200, res->status);
  14043. }
  14044. TEST(HttpToHttpsRedirectTest, CertFile) {
  14045. auto ssl_port = PORT + 1;
  14046. Server svr;
  14047. ASSERT_TRUE(svr.is_valid());
  14048. svr.Get("/index", [&](const Request &, Response &res) {
  14049. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14050. "/index");
  14051. svr.stop();
  14052. });
  14053. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14054. ASSERT_TRUE(ssl_svr.is_valid());
  14055. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14056. res.set_content("test", "text/plain");
  14057. ssl_svr.stop();
  14058. });
  14059. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14060. thread t2 =
  14061. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14062. auto se = detail::scope_exit([&] {
  14063. t2.join();
  14064. t.join();
  14065. ASSERT_FALSE(svr.is_running());
  14066. });
  14067. svr.wait_until_ready();
  14068. ssl_svr.wait_until_ready();
  14069. Client cli("127.0.0.1", PORT);
  14070. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14071. cli.enable_server_certificate_verification(true);
  14072. cli.set_follow_location(true);
  14073. cli.set_connection_timeout(30);
  14074. auto res = cli.Get("/index");
  14075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14076. ASSERT_EQ(StatusCode::OK_200, res->status);
  14077. }
  14078. TEST(SSLClientRedirectTest, CertFile) {
  14079. auto ssl_port = PORT + 1;
  14080. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14081. ASSERT_TRUE(ssl_svr1.is_valid());
  14082. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14083. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14084. "/index");
  14085. ssl_svr1.stop();
  14086. });
  14087. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14088. ASSERT_TRUE(ssl_svr2.is_valid());
  14089. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14090. res.set_content("test", "text/plain");
  14091. ssl_svr2.stop();
  14092. });
  14093. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14094. thread t2 =
  14095. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14096. auto se = detail::scope_exit([&] {
  14097. t2.join();
  14098. t.join();
  14099. ASSERT_FALSE(ssl_svr1.is_running());
  14100. });
  14101. ssl_svr1.wait_until_ready();
  14102. ssl_svr2.wait_until_ready();
  14103. SSLClient cli("127.0.0.1", PORT);
  14104. std::string cert;
  14105. read_file(SERVER_CERT2_FILE, cert);
  14106. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14107. cli.enable_server_certificate_verification(true);
  14108. cli.set_follow_location(true);
  14109. cli.set_connection_timeout(30);
  14110. auto res = cli.Get("/index");
  14111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14112. ASSERT_EQ(StatusCode::OK_200, res->status);
  14113. }
  14114. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14115. // another port, so the client follows it with a new client.
  14116. static Result GetThroughTlsRedirectToDifferentPort(
  14117. const std::function<void(SSLClient &)> &setup,
  14118. const char *target_cert = SERVER_CERT2_FILE) {
  14119. auto ssl_port = PORT + 1;
  14120. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14121. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14122. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14123. "/index");
  14124. });
  14125. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14126. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14127. res.set_content("test", "text/plain");
  14128. });
  14129. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14130. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14131. auto se = detail::scope_exit([&] {
  14132. ssl_svr2.stop();
  14133. ssl_svr1.stop();
  14134. t2.join();
  14135. t.join();
  14136. });
  14137. ssl_svr1.wait_until_ready();
  14138. ssl_svr2.wait_until_ready();
  14139. SSLClient cli("127.0.0.1", PORT);
  14140. cli.set_follow_location(true);
  14141. cli.set_connection_timeout(30);
  14142. setup(cli);
  14143. return cli.Get("/index");
  14144. }
  14145. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14146. auto calls = 0;
  14147. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14148. cli.enable_server_certificate_verification(false);
  14149. // Accept the first server only.
  14150. cli.set_session_verifier([&](tls::session_t) {
  14151. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14152. : SSLVerifierResponse::CertificateRejected;
  14153. });
  14154. });
  14155. EXPECT_FALSE(res);
  14156. EXPECT_EQ(2, calls);
  14157. }
  14158. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14159. std::string pinned;
  14160. auto res = GetThroughTlsRedirectToDifferentPort(
  14161. [&](SSLClient &cli) {
  14162. cli.enable_server_certificate_verification(false);
  14163. // Pin the first certificate seen.
  14164. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14165. if (pinned.empty()) { pinned = ctx.serial(); }
  14166. return ctx.serial() == pinned;
  14167. });
  14168. },
  14169. // A certificate other than the first server's.
  14170. SERVER_CERT_FILE);
  14171. EXPECT_FALSE(res);
  14172. EXPECT_FALSE(pinned.empty());
  14173. }
  14174. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14175. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14176. std::string cert;
  14177. read_file(SERVER_CERT2_FILE, cert);
  14178. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14179. });
  14180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14181. EXPECT_EQ(StatusCode::OK_200, res->status);
  14182. }
  14183. #endif
  14184. #ifdef CPPHTTPLIB_SSL_ENABLED
  14185. // Test that set_ca_cert_store() skips system certs (consistent with
  14186. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14187. // should be trusted - system certs should NOT be loaded.
  14188. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14189. // Load a specific cert that is NOT a system CA cert
  14190. std::string cert;
  14191. read_file(SERVER_CERT2_FILE, cert);
  14192. SSLClient cli("google.com");
  14193. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14194. cli.enable_server_certificate_verification(true);
  14195. // This should FAIL because:
  14196. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14197. // 2. System certs should NOT be loaded when custom store is set
  14198. // If system certs WERE loaded, this would succeed
  14199. auto res = cli.Get("/");
  14200. ASSERT_FALSE(res);
  14201. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14202. }
  14203. // Same as above, but through the native store handle path. Regression test:
  14204. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14205. // merged system certs into the user-provided store.
  14206. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14207. std::string cert;
  14208. read_file(SERVER_CERT2_FILE, cert);
  14209. SSLClient cli("google.com");
  14210. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14211. cli.enable_server_certificate_verification(true);
  14212. auto res = cli.Get("/");
  14213. ASSERT_FALSE(res);
  14214. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14215. }
  14216. // A custom store set via the native handle must still verify a server whose
  14217. // cert it does contain.
  14218. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14219. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14220. ASSERT_TRUE(svr.is_valid());
  14221. svr.Get("/test", [&](const Request &, Response &res) {
  14222. res.set_content("test", "text/plain");
  14223. });
  14224. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14225. auto se = detail::scope_exit([&] {
  14226. svr.stop();
  14227. t.join();
  14228. ASSERT_FALSE(svr.is_running());
  14229. });
  14230. svr.wait_until_ready();
  14231. SSLClient cli("127.0.0.1", PORT);
  14232. std::string cert;
  14233. read_file(SERVER_CERT2_FILE, cert);
  14234. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14235. cli.enable_server_certificate_verification(true);
  14236. cli.set_connection_timeout(30);
  14237. auto res = cli.Get("/test");
  14238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14239. ASSERT_EQ(StatusCode::OK_200, res->status);
  14240. }
  14241. // CA certs loaded through the universal Client must be transferred to the
  14242. // client created internally for following an HTTPS redirect. Regression test:
  14243. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14244. // the CA data for redirect transfer.
  14245. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14246. auto ssl_port = PORT + 1;
  14247. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14248. ASSERT_TRUE(ssl_svr1.is_valid());
  14249. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14250. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14251. "/index");
  14252. });
  14253. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14254. ASSERT_TRUE(ssl_svr2.is_valid());
  14255. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14256. res.set_content("test", "text/plain");
  14257. });
  14258. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14259. thread t2 =
  14260. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14261. auto se = detail::scope_exit([&] {
  14262. ssl_svr2.stop();
  14263. ssl_svr1.stop();
  14264. t2.join();
  14265. t.join();
  14266. ASSERT_FALSE(ssl_svr1.is_running());
  14267. });
  14268. ssl_svr1.wait_until_ready();
  14269. ssl_svr2.wait_until_ready();
  14270. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14271. std::string cert;
  14272. read_file(SERVER_CERT2_FILE, cert);
  14273. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14274. cli.enable_server_certificate_verification(true);
  14275. cli.set_follow_location(true);
  14276. cli.set_connection_timeout(30);
  14277. auto res = cli.Get("/index");
  14278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14279. ASSERT_EQ(StatusCode::OK_200, res->status);
  14280. }
  14281. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14282. // so a host signed by a system CA verifies even though a custom CA is set
  14283. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14284. std::string cert;
  14285. read_file(SERVER_CERT2_FILE, cert);
  14286. SSLClient cli("google.com");
  14287. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14288. cli.enable_system_ca(true);
  14289. cli.enable_server_certificate_verification(true);
  14290. auto res = cli.Get("/");
  14291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14292. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14293. }
  14294. // The custom CA remains effective when combined with the system CA
  14295. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14296. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14297. ASSERT_TRUE(svr.is_valid());
  14298. svr.Get("/test", [&](const Request &, Response &res) {
  14299. res.set_content("test", "text/plain");
  14300. });
  14301. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14302. auto se = detail::scope_exit([&] {
  14303. svr.stop();
  14304. t.join();
  14305. ASSERT_FALSE(svr.is_running());
  14306. });
  14307. svr.wait_until_ready();
  14308. SSLClient cli("127.0.0.1", PORT);
  14309. std::string cert;
  14310. read_file(SERVER_CERT2_FILE, cert);
  14311. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14312. cli.enable_system_ca(true);
  14313. cli.enable_server_certificate_verification(true);
  14314. cli.set_connection_timeout(30);
  14315. auto res = cli.Get("/test");
  14316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14317. ASSERT_EQ(StatusCode::OK_200, res->status);
  14318. }
  14319. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14320. // skip chain verification entirely (only the certificate identity was
  14321. // checked), so a server presenting an untrusted certificate with a matching
  14322. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14323. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14324. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14325. ASSERT_TRUE(svr.is_valid());
  14326. svr.Get("/test", [&](const Request &, Response &res) {
  14327. res.set_content("test", "text/plain");
  14328. });
  14329. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14330. auto se = detail::scope_exit([&] {
  14331. svr.stop();
  14332. t.join();
  14333. ASSERT_FALSE(svr.is_running());
  14334. });
  14335. svr.wait_until_ready();
  14336. SSLClient cli("127.0.0.1", PORT);
  14337. std::string cert;
  14338. // A trusted CA that did not sign the server certificate. The server cert
  14339. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14340. // this connection.
  14341. read_file(CLIENT_CA_CERT_FILE, cert);
  14342. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14343. cli.enable_server_certificate_verification(true);
  14344. cli.set_connection_timeout(30);
  14345. auto res = cli.Get("/test");
  14346. ASSERT_FALSE(res);
  14347. }
  14348. // enable_system_ca(false) prevents system CA loading entirely
  14349. TEST(SSLClientTest, DisableSystemCa_Online) {
  14350. SSLClient cli("google.com");
  14351. cli.enable_system_ca(false);
  14352. cli.enable_server_certificate_verification(true);
  14353. auto res = cli.Get("/");
  14354. ASSERT_FALSE(res);
  14355. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14356. // itself when the CA chain is empty
  14357. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14358. res.error() == Error::SSLConnection);
  14359. }
  14360. // The universal Client forwards enable_system_ca()
  14361. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14362. std::string cert;
  14363. read_file(SERVER_CERT2_FILE, cert);
  14364. Client cli("https://google.com");
  14365. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14366. cli.enable_system_ca(true);
  14367. cli.enable_server_certificate_verification(true);
  14368. auto res = cli.Get("/");
  14369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14370. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14371. }
  14372. // The system CA policy must carry over to the client created internally for
  14373. // following a cross-host HTTPS redirect
  14374. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14375. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14376. ASSERT_TRUE(svr.is_valid());
  14377. svr.Get("/index", [&](const Request &, Response &res) {
  14378. res.set_redirect("https://www.google.com/");
  14379. });
  14380. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14381. auto se = detail::scope_exit([&] {
  14382. svr.stop();
  14383. t.join();
  14384. ASSERT_FALSE(svr.is_running());
  14385. });
  14386. svr.wait_until_ready();
  14387. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14388. std::string cert;
  14389. read_file(SERVER_CERT2_FILE, cert);
  14390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14391. cli.enable_system_ca(true);
  14392. cli.enable_server_certificate_verification(true);
  14393. cli.set_follow_location(true);
  14394. cli.set_connection_timeout(30);
  14395. // Receiving any response proves the redirect client completed the TLS
  14396. // handshake with a system-CA-signed host
  14397. auto res = cli.Get("/index");
  14398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14399. }
  14400. TEST(MultipartFormDataTest, LargeData) {
  14401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14402. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14403. const ContentReader &content_reader) {
  14404. if (req.is_multipart_form_data()) {
  14405. std::vector<FormData> items;
  14406. content_reader(
  14407. [&](const FormData &file) {
  14408. items.push_back(file);
  14409. return true;
  14410. },
  14411. [&](const char *data, size_t data_length) {
  14412. items.back().content.append(data, data_length);
  14413. return true;
  14414. });
  14415. EXPECT_TRUE(std::string(items[0].name) == "document");
  14416. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14417. EXPECT_TRUE(items[0].filename == "2MB_data");
  14418. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14419. EXPECT_TRUE(items[1].name == "hello");
  14420. EXPECT_TRUE(items[1].content == "world");
  14421. EXPECT_TRUE(items[1].filename == "");
  14422. EXPECT_TRUE(items[1].content_type == "");
  14423. } else {
  14424. std::string body;
  14425. content_reader([&](const char *data, size_t data_length) {
  14426. body.append(data, data_length);
  14427. return true;
  14428. });
  14429. }
  14430. });
  14431. auto port = svr.bind_to_any_port(HOST);
  14432. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14433. auto se = detail::scope_exit([&] {
  14434. svr.stop();
  14435. t.join();
  14436. ASSERT_FALSE(svr.is_running());
  14437. });
  14438. svr.wait_until_ready();
  14439. {
  14440. std::string data(1024 * 1024 * 2, '.');
  14441. std::stringstream buffer;
  14442. buffer << data;
  14443. SSLClient cli(HOST, port);
  14444. cli.enable_server_certificate_verification(false);
  14445. UploadFormDataItems items{
  14446. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14447. {"hello", "world", "", ""},
  14448. };
  14449. auto res = cli.Post("/post", items);
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. ASSERT_EQ(StatusCode::OK_200, res->status);
  14452. }
  14453. }
  14454. TEST(MultipartFormDataTest, DataProviderItems) {
  14455. std::random_device seed_gen;
  14456. std::mt19937 random(seed_gen());
  14457. std::string rand1;
  14458. rand1.resize(1000);
  14459. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14460. std::string rand2;
  14461. rand2.resize(3000);
  14462. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14464. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14465. const ContentReader &content_reader) {
  14466. ASSERT_FALSE(req.is_multipart_form_data());
  14467. std::string body;
  14468. content_reader([&](const char *data, size_t data_length) {
  14469. body.append(data, data_length);
  14470. return true;
  14471. });
  14472. EXPECT_EQ(body, "");
  14473. });
  14474. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14475. const ContentReader &content_reader) {
  14476. ASSERT_TRUE(req.is_multipart_form_data());
  14477. std::vector<FormData> items;
  14478. content_reader(
  14479. [&](const FormData &file) {
  14480. items.push_back(file);
  14481. return true;
  14482. },
  14483. [&](const char *data, size_t data_length) {
  14484. items.back().content.append(data, data_length);
  14485. return true;
  14486. });
  14487. ASSERT_TRUE(items.size() == 2);
  14488. EXPECT_EQ(std::string(items[0].name), "name1");
  14489. EXPECT_EQ(items[0].content, "Testing123");
  14490. EXPECT_EQ(items[0].filename, "filename1");
  14491. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14492. EXPECT_EQ(items[1].name, "name2");
  14493. EXPECT_EQ(items[1].content, "Testing456");
  14494. EXPECT_EQ(items[1].filename, "");
  14495. EXPECT_EQ(items[1].content_type, "");
  14496. });
  14497. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14498. const ContentReader &content_reader) {
  14499. ASSERT_TRUE(req.is_multipart_form_data());
  14500. std::vector<FormData> items;
  14501. content_reader(
  14502. [&](const FormData &file) {
  14503. items.push_back(file);
  14504. return true;
  14505. },
  14506. [&](const char *data, size_t data_length) {
  14507. items.back().content.append(data, data_length);
  14508. return true;
  14509. });
  14510. ASSERT_TRUE(items.size() == 2);
  14511. EXPECT_EQ(items[0].name, "name3");
  14512. EXPECT_EQ(items[0].content, rand1);
  14513. EXPECT_EQ(items[0].filename, "filename3");
  14514. EXPECT_EQ(items[0].content_type, "");
  14515. EXPECT_EQ(items[1].name, "name4");
  14516. EXPECT_EQ(items[1].content, rand2);
  14517. EXPECT_EQ(items[1].filename, "filename4");
  14518. EXPECT_EQ(items[1].content_type, "");
  14519. });
  14520. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14521. const ContentReader &content_reader) {
  14522. ASSERT_TRUE(req.is_multipart_form_data());
  14523. std::vector<FormData> items;
  14524. content_reader(
  14525. [&](const FormData &file) {
  14526. items.push_back(file);
  14527. return true;
  14528. },
  14529. [&](const char *data, size_t data_length) {
  14530. items.back().content.append(data, data_length);
  14531. return true;
  14532. });
  14533. ASSERT_TRUE(items.size() == 4);
  14534. EXPECT_EQ(std::string(items[0].name), "name1");
  14535. EXPECT_EQ(items[0].content, "Testing123");
  14536. EXPECT_EQ(items[0].filename, "filename1");
  14537. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14538. EXPECT_EQ(items[1].name, "name2");
  14539. EXPECT_EQ(items[1].content, "Testing456");
  14540. EXPECT_EQ(items[1].filename, "");
  14541. EXPECT_EQ(items[1].content_type, "");
  14542. EXPECT_EQ(items[2].name, "name3");
  14543. EXPECT_EQ(items[2].content, rand1);
  14544. EXPECT_EQ(items[2].filename, "filename3");
  14545. EXPECT_EQ(items[2].content_type, "");
  14546. EXPECT_EQ(items[3].name, "name4");
  14547. EXPECT_EQ(items[3].content, rand2);
  14548. EXPECT_EQ(items[3].filename, "filename4");
  14549. EXPECT_EQ(items[3].content_type, "");
  14550. });
  14551. auto port = svr.bind_to_any_port("localhost");
  14552. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14553. auto se = detail::scope_exit([&] {
  14554. svr.stop();
  14555. t.join();
  14556. ASSERT_FALSE(svr.is_running());
  14557. });
  14558. svr.wait_until_ready();
  14559. {
  14560. SSLClient cli("localhost", port);
  14561. cli.enable_server_certificate_verification(false);
  14562. UploadFormDataItems items{
  14563. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14564. {"name2", "Testing456", "", ""}, // not a file
  14565. };
  14566. {
  14567. auto res = cli.Post("/post-none", {}, {}, {});
  14568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14569. ASSERT_EQ(StatusCode::OK_200, res->status);
  14570. }
  14571. FormDataProviderItems providers;
  14572. {
  14573. auto res =
  14574. cli.Post("/post-items", {}, items, providers); // empty providers
  14575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14576. ASSERT_EQ(StatusCode::OK_200, res->status);
  14577. }
  14578. providers.push_back({"name3",
  14579. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14580. // test the offset is given correctly at each step
  14581. if (!offset)
  14582. sink.os.write(rand1.data(), 30);
  14583. else if (offset == 30)
  14584. sink.os.write(rand1.data() + 30, 300);
  14585. else if (offset == 330)
  14586. sink.os.write(rand1.data() + 330, 670);
  14587. else if (offset == rand1.size())
  14588. sink.done();
  14589. return true;
  14590. },
  14591. "filename3",
  14592. {}});
  14593. providers.push_back({"name4",
  14594. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14595. // test the offset is given correctly at each step
  14596. if (!offset)
  14597. sink.os.write(rand2.data(), 2000);
  14598. else if (offset == 2000)
  14599. sink.os.write(rand2.data() + 2000, 1);
  14600. else if (offset == 2001)
  14601. sink.os.write(rand2.data() + 2001, 999);
  14602. else if (offset == rand2.size())
  14603. sink.done();
  14604. return true;
  14605. },
  14606. "filename4",
  14607. {}});
  14608. {
  14609. auto res = cli.Post("/post-providers", {}, {}, providers);
  14610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14611. ASSERT_EQ(StatusCode::OK_200, res->status);
  14612. }
  14613. {
  14614. auto res = cli.Post("/post-both", {}, items, providers);
  14615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14616. ASSERT_EQ(StatusCode::OK_200, res->status);
  14617. }
  14618. }
  14619. }
  14620. TEST(MultipartFormDataTest, BadHeader) {
  14621. Server svr;
  14622. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14623. res.set_content("ok", "text/plain");
  14624. });
  14625. thread t = thread([&] { svr.listen(HOST, PORT); });
  14626. auto se = detail::scope_exit([&] {
  14627. svr.stop();
  14628. t.join();
  14629. ASSERT_FALSE(svr.is_running());
  14630. });
  14631. svr.wait_until_ready();
  14632. const std::string body =
  14633. "This is the preamble. It is to be ignored, though it\r\n"
  14634. "is a handy place for composition agents to include an\r\n"
  14635. "explanatory note to non-MIME conformant readers.\r\n"
  14636. "\r\n"
  14637. "\r\n"
  14638. "--simple boundary\r\n"
  14639. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14640. ": BAD...\r\n"
  14641. "\r\n"
  14642. "value1\r\n"
  14643. "--simple boundary\r\n"
  14644. "Content-Disposition: form-data; name=\"field2\"; "
  14645. "filename=\"example.txt\"\r\n"
  14646. "\r\n"
  14647. "value2\r\n"
  14648. "--simple boundary--\r\n"
  14649. "This is the epilogue. It is also to be ignored.\r\n";
  14650. std::string content_type =
  14651. R"(multipart/form-data; boundary="simple boundary")";
  14652. Client cli(HOST, PORT);
  14653. auto res = cli.Post("/post", body, content_type.c_str());
  14654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14655. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14656. }
  14657. TEST(MultipartFormDataTest, WithPreamble) {
  14658. Server svr;
  14659. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14660. res.set_content("ok", "text/plain");
  14661. });
  14662. thread t = thread([&] { svr.listen(HOST, PORT); });
  14663. auto se = detail::scope_exit([&] {
  14664. svr.stop();
  14665. t.join();
  14666. ASSERT_FALSE(svr.is_running());
  14667. });
  14668. svr.wait_until_ready();
  14669. const std::string body =
  14670. "This is the preamble. It is to be ignored, though it\r\n"
  14671. "is a handy place for composition agents to include an\r\n"
  14672. "explanatory note to non-MIME conformant readers.\r\n"
  14673. "\r\n"
  14674. "\r\n"
  14675. "--simple boundary\r\n"
  14676. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14677. "\r\n"
  14678. "value1\r\n"
  14679. "--simple boundary\r\n"
  14680. "Content-Disposition: form-data; name=\"field2\"; "
  14681. "filename=\"example.txt\"\r\n"
  14682. "\r\n"
  14683. "value2\r\n"
  14684. "--simple boundary--\r\n"
  14685. "This is the epilogue. It is also to be ignored.\r\n";
  14686. std::string content_type =
  14687. R"(multipart/form-data; boundary="simple boundary")";
  14688. Client cli(HOST, PORT);
  14689. auto res = cli.Post("/post", body, content_type.c_str());
  14690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14691. EXPECT_EQ(StatusCode::OK_200, res->status);
  14692. }
  14693. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14695. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14696. const ContentReader &content_reader) {
  14697. if (req.is_multipart_form_data()) {
  14698. std::vector<FormData> items;
  14699. content_reader(
  14700. [&](const FormData &file) {
  14701. items.push_back(file);
  14702. return true;
  14703. },
  14704. [&](const char *data, size_t data_length) {
  14705. items.back().content.append(data, data_length);
  14706. return true;
  14707. });
  14708. EXPECT_TRUE(std::string(items[0].name) == "document");
  14709. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14710. EXPECT_TRUE(items[0].filename == "2MB_data");
  14711. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14712. EXPECT_TRUE(items[1].name == "hello");
  14713. EXPECT_TRUE(items[1].content == "world");
  14714. EXPECT_TRUE(items[1].filename == "");
  14715. EXPECT_TRUE(items[1].content_type == "");
  14716. } else {
  14717. std::string body;
  14718. content_reader([&](const char *data, size_t data_length) {
  14719. body.append(data, data_length);
  14720. return true;
  14721. });
  14722. }
  14723. });
  14724. auto port = svr.bind_to_any_port("localhost");
  14725. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14726. auto se = detail::scope_exit([&] {
  14727. svr.stop();
  14728. t.join();
  14729. ASSERT_FALSE(svr.is_running());
  14730. });
  14731. svr.wait_until_ready();
  14732. {
  14733. std::string data(1024 * 1024 * 2, '.');
  14734. std::stringstream buffer;
  14735. buffer << data;
  14736. SSLClient cli("localhost", port);
  14737. cli.enable_server_certificate_verification(false);
  14738. UploadFormDataItems items{
  14739. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14740. {"hello", "world", "", ""},
  14741. };
  14742. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14744. ASSERT_EQ(StatusCode::OK_200, res->status);
  14745. }
  14746. }
  14747. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14748. std::string data(1024 * 1024 * 2, '&');
  14749. std::stringstream buffer;
  14750. buffer << data;
  14751. Client cli("https://localhost:8080");
  14752. UploadFormDataItems items{
  14753. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14754. {"hello", "world", "", ""},
  14755. };
  14756. for (const char &c : " \t\r\n") {
  14757. auto res =
  14758. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14759. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14760. ASSERT_FALSE(res);
  14761. }
  14762. }
  14763. TEST(MultipartFormDataTest, PutFormData) {
  14764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14765. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14766. const ContentReader &content_reader) {
  14767. if (req.is_multipart_form_data()) {
  14768. std::vector<FormData> items;
  14769. content_reader(
  14770. [&](const FormData &file) {
  14771. items.push_back(file);
  14772. return true;
  14773. },
  14774. [&](const char *data, size_t data_length) {
  14775. items.back().content.append(data, data_length);
  14776. return true;
  14777. });
  14778. EXPECT_TRUE(std::string(items[0].name) == "document");
  14779. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14780. EXPECT_TRUE(items[0].filename == "2MB_data");
  14781. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14782. EXPECT_TRUE(items[1].name == "hello");
  14783. EXPECT_TRUE(items[1].content == "world");
  14784. EXPECT_TRUE(items[1].filename == "");
  14785. EXPECT_TRUE(items[1].content_type == "");
  14786. } else {
  14787. std::string body;
  14788. content_reader([&](const char *data, size_t data_length) {
  14789. body.append(data, data_length);
  14790. return true;
  14791. });
  14792. }
  14793. });
  14794. auto port = svr.bind_to_any_port("localhost");
  14795. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14796. auto se = detail::scope_exit([&] {
  14797. svr.stop();
  14798. t.join();
  14799. ASSERT_FALSE(svr.is_running());
  14800. });
  14801. svr.wait_until_ready();
  14802. {
  14803. std::string data(1024 * 1024 * 2, '&');
  14804. std::stringstream buffer;
  14805. buffer << data;
  14806. SSLClient cli("localhost", port);
  14807. cli.enable_server_certificate_verification(false);
  14808. UploadFormDataItems items{
  14809. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14810. {"hello", "world", "", ""},
  14811. };
  14812. auto res = cli.Put("/put", items);
  14813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14814. ASSERT_EQ(StatusCode::OK_200, res->status);
  14815. }
  14816. }
  14817. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14819. svr.Put("/put_customboundary",
  14820. [&](const Request &req, const Response & /*res*/,
  14821. const ContentReader &content_reader) {
  14822. if (req.is_multipart_form_data()) {
  14823. std::vector<FormData> items;
  14824. content_reader(
  14825. [&](const FormData &file) {
  14826. items.push_back(file);
  14827. return true;
  14828. },
  14829. [&](const char *data, size_t data_length) {
  14830. items.back().content.append(data, data_length);
  14831. return true;
  14832. });
  14833. EXPECT_TRUE(std::string(items[0].name) == "document");
  14834. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14835. EXPECT_TRUE(items[0].filename == "2MB_data");
  14836. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14837. EXPECT_TRUE(items[1].name == "hello");
  14838. EXPECT_TRUE(items[1].content == "world");
  14839. EXPECT_TRUE(items[1].filename == "");
  14840. EXPECT_TRUE(items[1].content_type == "");
  14841. } else {
  14842. std::string body;
  14843. content_reader([&](const char *data, size_t data_length) {
  14844. body.append(data, data_length);
  14845. return true;
  14846. });
  14847. }
  14848. });
  14849. auto port = svr.bind_to_any_port("localhost");
  14850. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14851. auto se = detail::scope_exit([&] {
  14852. svr.stop();
  14853. t.join();
  14854. ASSERT_FALSE(svr.is_running());
  14855. });
  14856. svr.wait_until_ready();
  14857. {
  14858. std::string data(1024 * 1024 * 2, '&');
  14859. std::stringstream buffer;
  14860. buffer << data;
  14861. SSLClient cli("localhost", port);
  14862. cli.enable_server_certificate_verification(false);
  14863. UploadFormDataItems items{
  14864. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14865. {"hello", "world", "", ""},
  14866. };
  14867. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14869. ASSERT_EQ(StatusCode::OK_200, res->status);
  14870. }
  14871. }
  14872. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14873. std::string data(1024 * 1024 * 2, '&');
  14874. std::stringstream buffer;
  14875. buffer << data;
  14876. Client cli("https://localhost:8080");
  14877. cli.enable_server_certificate_verification(false);
  14878. UploadFormDataItems items{
  14879. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14880. {"hello", "world", "", ""},
  14881. };
  14882. for (const char &c : " \t\r\n") {
  14883. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14884. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14885. ASSERT_FALSE(res);
  14886. }
  14887. }
  14888. TEST(MultipartFormDataTest, AlternateFilename) {
  14889. auto handled = false;
  14890. Server svr;
  14891. svr.Post("/test", [&](const Request &req, Response &res) {
  14892. ASSERT_EQ(2u, req.form.files.size());
  14893. ASSERT_EQ(1u, req.form.fields.size());
  14894. // Test files
  14895. const auto &file1 = req.form.get_file("file1");
  14896. ASSERT_EQ("file1", file1.name);
  14897. ASSERT_EQ("A.txt", file1.filename);
  14898. ASSERT_EQ("text/plain", file1.content_type);
  14899. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14900. const auto &file2 = req.form.get_file("file2");
  14901. ASSERT_EQ("file2", file2.name);
  14902. ASSERT_EQ("a.html", file2.filename);
  14903. ASSERT_EQ("text/html", file2.content_type);
  14904. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14905. file2.content);
  14906. // Test text field
  14907. const auto &text = req.form.get_field("text");
  14908. ASSERT_EQ("text default", text);
  14909. res.set_content("ok", "text/plain");
  14910. handled = true;
  14911. });
  14912. thread t = thread([&] { svr.listen(HOST, PORT); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. t.join();
  14916. ASSERT_FALSE(svr.is_running());
  14917. ASSERT_TRUE(handled);
  14918. });
  14919. svr.wait_until_ready();
  14920. auto req = "POST /test HTTP/1.1\r\n"
  14921. "Host: localhost\r\n"
  14922. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14923. "Content-Length: 399\r\n"
  14924. "\r\n"
  14925. "----------\r\n"
  14926. "Content-Disposition: form-data; name=\"text\"\r\n"
  14927. "\r\n"
  14928. "text default\r\n"
  14929. "----------\r\n"
  14930. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14931. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14932. "Content-Type: text/plain\r\n"
  14933. "\r\n"
  14934. "Content of a.txt.\r\n"
  14935. "\r\n"
  14936. "----------\r\n"
  14937. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14938. "\"a.html\"\r\n"
  14939. "Content-Type: text/html\r\n"
  14940. "\r\n"
  14941. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14942. "\r\n"
  14943. "------------\r\n";
  14944. ASSERT_TRUE(send_request(1, req));
  14945. }
  14946. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14947. auto handled = false;
  14948. Server svr;
  14949. svr.Post("/test", [&](const Request &req, Response &res) {
  14950. // Case-insensitive "utf-8''" prefix with a long value
  14951. const auto &file = req.form.get_file("file1");
  14952. ASSERT_EQ("file1", file.name);
  14953. // 8000 chars exercises both the Content-Disposition parser and the
  14954. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14955. // Prior to the fix, std::regex_match on this header would cause O(N)
  14956. // stack recursion in libstdc++, leading to SIGSEGV.
  14957. std::string expected_filename(8000, 'A');
  14958. ASSERT_EQ(expected_filename, file.filename);
  14959. res.set_content("ok", "text/plain");
  14960. handled = true;
  14961. });
  14962. thread t = thread([&] { svr.listen(HOST, PORT); });
  14963. auto se = detail::scope_exit([&] {
  14964. svr.stop();
  14965. t.join();
  14966. ASSERT_FALSE(svr.is_running());
  14967. ASSERT_TRUE(handled);
  14968. });
  14969. svr.wait_until_ready();
  14970. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14971. // Regression test for GHSA-qq6v-r583-3h69
  14972. std::string long_filename(8000, 'A');
  14973. std::string body = "----------\r\n"
  14974. "Content-Disposition: form-data; name=\"file1\"; "
  14975. "filename*=\"Utf-8''" +
  14976. long_filename +
  14977. "\"\r\n"
  14978. "\r\n"
  14979. "hello\r\n"
  14980. "------------\r\n";
  14981. auto req = "POST /test HTTP/1.1\r\n"
  14982. "Host: localhost\r\n"
  14983. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14984. "Content-Length: " +
  14985. std::to_string(body.size()) + "\r\n\r\n" + body;
  14986. ASSERT_TRUE(send_request(1, req));
  14987. }
  14988. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14989. auto handled = false;
  14990. Server svr;
  14991. svr.Post("/test", [&](const Request &req, Response &) {
  14992. ASSERT_EQ(2u, req.form.fields.size());
  14993. const auto &text1 = req.form.get_field("text1");
  14994. ASSERT_EQ("text1", text1);
  14995. const auto &text2 = req.form.get_field("text2");
  14996. ASSERT_EQ("text2", text2);
  14997. handled = true;
  14998. });
  14999. thread t = thread([&] { svr.listen(HOST, PORT); });
  15000. auto se = detail::scope_exit([&] {
  15001. svr.stop();
  15002. t.join();
  15003. ASSERT_FALSE(svr.is_running());
  15004. ASSERT_TRUE(handled);
  15005. });
  15006. svr.wait_until_ready();
  15007. auto req = "POST /test HTTP/1.1\r\n"
  15008. "Host: localhost\r\n"
  15009. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15010. "Content-Length: 146\r\n"
  15011. "\r\n----------\r\n"
  15012. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15013. "\r\n"
  15014. "text1"
  15015. "\r\n----------\r\n"
  15016. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15017. "\r\n"
  15018. "text2"
  15019. "\r\n------------";
  15020. std::string response;
  15021. ASSERT_TRUE(send_request(1, req, &response));
  15022. ASSERT_EQ("200", response.substr(9, 3));
  15023. }
  15024. TEST(MultipartFormDataTest, ContentLength) {
  15025. auto handled = false;
  15026. Server svr;
  15027. svr.Post("/test", [&](const Request &req, Response &) {
  15028. ASSERT_EQ(2u, req.form.fields.size());
  15029. const auto &text1 = req.form.get_field("text1");
  15030. ASSERT_EQ("text1", text1);
  15031. const auto &text2 = req.form.get_field("text2");
  15032. ASSERT_EQ("text2", text2);
  15033. handled = true;
  15034. });
  15035. thread t = thread([&] { svr.listen(HOST, PORT); });
  15036. auto se = detail::scope_exit([&] {
  15037. svr.stop();
  15038. t.join();
  15039. ASSERT_FALSE(svr.is_running());
  15040. ASSERT_TRUE(handled);
  15041. });
  15042. svr.wait_until_ready();
  15043. auto req = "POST /test HTTP/1.1\r\n"
  15044. "Host: localhost\r\n"
  15045. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15046. "Content-Length: 167\r\n"
  15047. "\r\n----------\r\n"
  15048. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15049. "Content-Length: 5\r\n"
  15050. "\r\n"
  15051. "text1"
  15052. "\r\n----------\r\n"
  15053. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15054. "\r\n"
  15055. "text2"
  15056. "\r\n------------\r\n";
  15057. std::string response;
  15058. ASSERT_TRUE(send_request(1, req, &response));
  15059. ASSERT_EQ("200", response.substr(9, 3));
  15060. }
  15061. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15062. auto handled = false;
  15063. Server svr;
  15064. svr.Post("/test", [&](const Request &req, Response &) {
  15065. ASSERT_EQ(2u, req.form.fields.size());
  15066. const auto &text1 = req.form.get_field("text1");
  15067. ASSERT_EQ("text1", text1);
  15068. // TODO: Add header access for text fields if needed
  15069. const auto &text2 = req.form.get_field("text2");
  15070. ASSERT_EQ("text2", text2);
  15071. // TODO: Header access for text fields needs to be implemented
  15072. // auto &headers = it->second.headers;
  15073. // ASSERT_EQ(3U, headers.size());
  15074. // auto custom_header = headers.find("x-whatever");
  15075. // ASSERT_TRUE(custom_header != headers.end());
  15076. // ASSERT_NE("customvalue", custom_header->second);
  15077. // ASSERT_EQ("CustomValue", custom_header->second);
  15078. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15079. handled = true;
  15080. });
  15081. thread t = thread([&] { svr.listen(HOST, PORT); });
  15082. auto se = detail::scope_exit([&] {
  15083. svr.stop();
  15084. t.join();
  15085. ASSERT_FALSE(svr.is_running());
  15086. ASSERT_TRUE(handled);
  15087. });
  15088. svr.wait_until_ready();
  15089. auto req = "POST /test HTTP/1.1\r\n"
  15090. "Host: localhost\r\n"
  15091. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15092. "Content-Length: 232\r\n"
  15093. "\r\n----------\r\n"
  15094. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15095. "Content-Length: 5\r\n"
  15096. "X-Test: 1\r\n"
  15097. "\r\n"
  15098. "text1"
  15099. "\r\n----------\r\n"
  15100. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15101. "Content-Type: text/plain\r\n"
  15102. "X-Whatever: CustomValue\r\n"
  15103. "\r\n"
  15104. "text2"
  15105. "\r\n------------\r\n"
  15106. "That should be disregarded. Not even read";
  15107. std::string response;
  15108. ASSERT_TRUE(send_request(1, req, &response));
  15109. ASSERT_EQ("200", response.substr(9, 3));
  15110. }
  15111. TEST(MultipartFormDataTest, LargeHeader) {
  15112. auto handled = false;
  15113. Server svr;
  15114. svr.Post("/test", [&](const Request &req, Response &) {
  15115. ASSERT_EQ(1u, req.form.fields.size());
  15116. const auto &text = req.form.get_field("name1");
  15117. ASSERT_EQ("text1", text);
  15118. handled = true;
  15119. });
  15120. thread t = thread([&] { svr.listen(HOST, PORT); });
  15121. auto se = detail::scope_exit([&] {
  15122. svr.stop();
  15123. t.join();
  15124. ASSERT_FALSE(svr.is_running());
  15125. ASSERT_TRUE(handled);
  15126. });
  15127. svr.wait_until_ready();
  15128. auto boundary = std::string("cpp-httplib-multipart-data");
  15129. std::string content = "--" + boundary +
  15130. "\r\n"
  15131. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15132. "\r\n"
  15133. "text1\r\n"
  15134. "--" +
  15135. boundary + "--\r\n";
  15136. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15137. "Host: localhost\r\n"
  15138. "Content-Type: multipart/form-data;boundary=" +
  15139. boundary +
  15140. "\r\n"
  15141. "Content-Length: " +
  15142. std::to_string(content.size()) +
  15143. "\r\n"
  15144. "Dummy-Header: ";
  15145. std::string header_suffix = "\r\n"
  15146. "\r\n";
  15147. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15148. size_t header_dummy_size =
  15149. read_buff_size -
  15150. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15151. auto header_dummy = std::string(header_dummy_size, '@');
  15152. auto req = header_prefix + header_dummy + header_suffix + content;
  15153. std::string response;
  15154. ASSERT_TRUE(send_request(1, req, &response));
  15155. ASSERT_EQ("200", response.substr(9, 3));
  15156. }
  15157. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15158. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15159. // (not chunked Transfer-Encoding) after the streaming refactor.
  15160. auto handled = false;
  15161. Server svr;
  15162. svr.Post("/upload", [&](const Request &req, Response &res) {
  15163. auto cl_it = req.headers.find("Content-Length");
  15164. EXPECT_TRUE(cl_it != req.headers.end());
  15165. auto te_it = req.headers.find("Transfer-Encoding");
  15166. EXPECT_TRUE(te_it == req.headers.end());
  15167. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15168. res.set_content("ok", "text/plain");
  15169. handled = true;
  15170. });
  15171. auto port = svr.bind_to_any_port(HOST);
  15172. auto t = thread([&] { svr.listen_after_bind(); });
  15173. auto se = detail::scope_exit([&] {
  15174. svr.stop();
  15175. t.join();
  15176. ASSERT_FALSE(svr.is_running());
  15177. ASSERT_TRUE(handled);
  15178. });
  15179. svr.wait_until_ready();
  15180. UploadFormDataItems items = {
  15181. {"field1", "hello", "", "text/plain"},
  15182. {"file1", "world", "test.txt", "application/octet-stream"},
  15183. };
  15184. Client cli(HOST, port);
  15185. auto res = cli.Post("/upload", {}, items);
  15186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15187. EXPECT_EQ(StatusCode::OK_200, res->status);
  15188. }
  15189. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15190. // Verify that make_multipart_content_provider coalesces many small segments
  15191. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15192. constexpr size_t kItemCount = 1000;
  15193. UploadFormDataItems items;
  15194. items.reserve(kItemCount);
  15195. for (size_t i = 0; i < kItemCount; i++) {
  15196. items.push_back(
  15197. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15198. }
  15199. const std::string boundary = "----test-boundary";
  15200. auto content_length = detail::get_multipart_content_length(items, boundary);
  15201. auto provider = detail::make_multipart_content_provider(items, boundary);
  15202. // Drive the provider the same way write_content_with_progress does
  15203. size_t write_count = 0;
  15204. size_t total_bytes = 0;
  15205. DataSink sink;
  15206. size_t offset = 0;
  15207. sink.write = [&](const char *d, size_t l) -> bool {
  15208. (void)d;
  15209. write_count++;
  15210. total_bytes += l;
  15211. offset += l;
  15212. return true;
  15213. };
  15214. sink.is_writable = []() -> bool { return true; };
  15215. while (offset < content_length) {
  15216. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15217. }
  15218. EXPECT_EQ(content_length, total_bytes);
  15219. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15220. // With buffering into 64KB blocks, write_count should be much smaller.
  15221. auto segment_count = 3 * kItemCount + 1;
  15222. EXPECT_LT(write_count, segment_count / 10);
  15223. }
  15224. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15225. // Integration test: send many UploadFormDataItems and verify the server
  15226. // receives all of them correctly (#2410).
  15227. constexpr size_t kItemCount = 500;
  15228. auto handled = false;
  15229. Server svr;
  15230. svr.Post("/upload", [&](const Request &req, Response &res) {
  15231. EXPECT_EQ(kItemCount, req.form.fields.size());
  15232. for (size_t i = 0; i < kItemCount; i++) {
  15233. auto key = "field" + std::to_string(i);
  15234. auto val = "value" + std::to_string(i);
  15235. auto it = req.form.fields.find(key);
  15236. if (it != req.form.fields.end()) {
  15237. EXPECT_EQ(val, it->second.content);
  15238. } else {
  15239. ADD_FAILURE() << "Missing field: " << key;
  15240. }
  15241. }
  15242. res.set_content("ok", "text/plain");
  15243. handled = true;
  15244. });
  15245. auto port = svr.bind_to_any_port(HOST);
  15246. auto t = thread([&] { svr.listen_after_bind(); });
  15247. auto se = detail::scope_exit([&] {
  15248. svr.stop();
  15249. t.join();
  15250. ASSERT_FALSE(svr.is_running());
  15251. ASSERT_TRUE(handled);
  15252. });
  15253. svr.wait_until_ready();
  15254. UploadFormDataItems items;
  15255. items.reserve(kItemCount);
  15256. for (size_t i = 0; i < kItemCount; i++) {
  15257. items.push_back(
  15258. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15259. }
  15260. Client cli(HOST, port);
  15261. auto res = cli.Post("/upload", items);
  15262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15263. EXPECT_EQ(StatusCode::OK_200, res->status);
  15264. }
  15265. TEST(MultipartFormDataTest, MakeFileProvider) {
  15266. // Verify make_file_provider sends a file's contents correctly.
  15267. const std::string file_content(4096, 'Z');
  15268. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15269. {
  15270. std::ofstream ofs(tmp_path, std::ios::binary);
  15271. ofs.write(file_content.data(),
  15272. static_cast<std::streamsize>(file_content.size()));
  15273. }
  15274. auto handled = false;
  15275. Server svr;
  15276. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15277. const ContentReader &content_reader) {
  15278. ASSERT_TRUE(req.is_multipart_form_data());
  15279. std::vector<FormData> items;
  15280. content_reader(
  15281. [&](const FormData &file) {
  15282. items.push_back(file);
  15283. return true;
  15284. },
  15285. [&](const char *data, size_t data_length) {
  15286. items.back().content.append(data, data_length);
  15287. return true;
  15288. });
  15289. ASSERT_EQ(1u, items.size());
  15290. EXPECT_EQ("myfile", items[0].name);
  15291. EXPECT_EQ("data.bin", items[0].filename);
  15292. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15293. EXPECT_EQ(file_content, items[0].content);
  15294. handled = true;
  15295. });
  15296. auto port = svr.bind_to_any_port(HOST);
  15297. auto t = thread([&] { svr.listen_after_bind(); });
  15298. auto se = detail::scope_exit([&] {
  15299. svr.stop();
  15300. t.join();
  15301. ASSERT_FALSE(svr.is_running());
  15302. ASSERT_TRUE(handled);
  15303. std::remove(tmp_path.c_str());
  15304. });
  15305. svr.wait_until_ready();
  15306. FormDataProviderItems providers;
  15307. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15308. "application/octet-stream"));
  15309. Client cli(HOST, port);
  15310. auto res = cli.Post("/upload", {}, {}, providers);
  15311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15312. EXPECT_EQ(StatusCode::OK_200, res->status);
  15313. }
  15314. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15315. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15316. // (100) headers is rejected with a 400 Bad Request response.
  15317. Server svr;
  15318. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15319. res.set_content("ok", "text/plain");
  15320. });
  15321. thread t = thread([&] { svr.listen(HOST, PORT); });
  15322. auto se = detail::scope_exit([&] {
  15323. svr.stop();
  15324. t.join();
  15325. ASSERT_FALSE(svr.is_running());
  15326. });
  15327. svr.wait_until_ready();
  15328. // Build a multipart part with 101 custom headers (exceeding
  15329. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15330. std::stringstream body;
  15331. body << "--simpleboundary\r\n"
  15332. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15333. for (int i = 0; i < 101; i++) {
  15334. body << "X-Custom-Header-" << i << ": value\r\n";
  15335. }
  15336. body << "\r\n"
  15337. << "value1\r\n"
  15338. << "--simpleboundary--\r\n";
  15339. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15340. Client cli(HOST, PORT);
  15341. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15343. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15344. }
  15345. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15346. // A body that never contains the declared boundary must not be accumulated
  15347. // while the parser waits for it. Buffering it would also make every read
  15348. // rescan everything seen so far, which is quadratic in the body size.
  15349. Server svr;
  15350. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15351. res.set_content("ok", "text/plain");
  15352. });
  15353. auto port = svr.bind_to_any_port(HOST);
  15354. thread t = thread([&] { svr.listen_after_bind(); });
  15355. auto se = detail::scope_exit([&] {
  15356. svr.stop();
  15357. t.join();
  15358. ASSERT_FALSE(svr.is_running());
  15359. });
  15360. svr.wait_until_ready();
  15361. Client cli(HOST, port);
  15362. cli.set_read_timeout(60, 0);
  15363. cli.set_write_timeout(60, 0);
  15364. // '-' is the worst case: it matches the first character of the boundary, so
  15365. // every position has to be checked against it.
  15366. auto post_dashes = [&](size_t size) {
  15367. const std::string body(size, '-');
  15368. auto start = std::chrono::steady_clock::now();
  15369. auto res =
  15370. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15371. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15372. std::chrono::steady_clock::now() - start)
  15373. .count();
  15374. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15375. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15376. return ms;
  15377. };
  15378. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15379. // Windows.
  15380. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15381. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15382. // Comparing the two sizes rather than checking an absolute duration keeps
  15383. // this meaningful across build types and CI load, both of which move the
  15384. // absolute numbers by more than an order of magnitude. Four times the bytes
  15385. // costs about four times the time when parsing is linear, and about sixteen
  15386. // times when the body is buffered and rescanned.
  15387. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15388. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15389. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15390. << "ms, which suggests the body is being buffered and rescanned";
  15391. }
  15392. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15393. // A boundary can only be followed by CRLF or by "--", so anything else is
  15394. // malformed no matter what comes next. The parser must say so right away
  15395. // instead of buffering the rest of the declared body.
  15396. Server svr;
  15397. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15398. res.set_content("ok", "text/plain");
  15399. });
  15400. auto port = svr.bind_to_any_port(HOST);
  15401. thread t = thread([&] { svr.listen_after_bind(); });
  15402. auto se = detail::scope_exit([&] {
  15403. svr.stop();
  15404. t.join();
  15405. ASSERT_FALSE(svr.is_running());
  15406. });
  15407. svr.wait_until_ready();
  15408. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15409. // buffers instead of failing would still be waiting for the remaining bytes.
  15410. const std::string body = "--zzzz\r\n"
  15411. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15412. "\r\n"
  15413. "text1"
  15414. "\r\n--zzzzXX";
  15415. const std::string req = "POST /post HTTP/1.1\r\n"
  15416. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15417. "Content-Length: 1048576\r\n"
  15418. "\r\n" +
  15419. body;
  15420. std::string response;
  15421. ASSERT_TRUE(send_request(3, req, &response, port));
  15422. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15423. EXPECT_EQ("400", response.substr(9, 3));
  15424. }
  15425. // Posts a multipart body split into two writes, so that the server sees the
  15426. // split at whatever offset the caller chose, and expects the single "text1"
  15427. // field to come through.
  15428. static void expect_split_multipart_ok(const std::string &body1,
  15429. const std::string &body2) {
  15430. auto handled = false;
  15431. Server svr;
  15432. svr.Post("/post", [&](const Request &req, Response &) {
  15433. EXPECT_EQ(1u, req.form.fields.size());
  15434. EXPECT_EQ("text1", req.form.get_field("text1"));
  15435. handled = true;
  15436. });
  15437. auto port = svr.bind_to_any_port(HOST);
  15438. thread t = thread([&] { svr.listen_after_bind(); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. ASSERT_FALSE(svr.is_running());
  15443. ASSERT_TRUE(handled);
  15444. });
  15445. svr.wait_until_ready();
  15446. // "Connection: close" makes the server close once it has answered, so the
  15447. // response drain ends immediately instead of idling until the read timeout.
  15448. const std::string head =
  15449. "POST /post HTTP/1.1\r\n"
  15450. "Host: localhost\r\n"
  15451. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15452. "Connection: close\r\n"
  15453. "Content-Length: " +
  15454. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15455. std::string response;
  15456. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15457. ASSERT_GE(response.size(), 12u) << "no response";
  15458. EXPECT_EQ("200", response.substr(9, 3));
  15459. }
  15460. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15461. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15462. // ignored, including when it does not arrive in the same read as the
  15463. // close-delimiter itself.
  15464. expect_split_multipart_ok("--zzzz\r\n"
  15465. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15466. "\r\n"
  15467. "text1"
  15468. "\r\n--zzzz--",
  15469. "\r\nthis epilogue must be ignored\r\n");
  15470. }
  15471. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15472. // The initial boundary may be preceded by a preamble of any length and may
  15473. // straddle a read boundary. Discarding data while waiting for it must not
  15474. // throw away a partial boundary sitting at the end of the buffer.
  15475. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15476. "zz\r\n"
  15477. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15478. "\r\n"
  15479. "text1"
  15480. "\r\n--zzzz--\r\n");
  15481. }
  15482. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15483. // The received boundary was only checked for being non-empty, so it could be
  15484. // as long as a header is allowed to be. The parser scans the body for
  15485. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15486. // costs a nearly full comparison at nearly every position, making the
  15487. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15488. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15489. Server svr;
  15490. svr.Post("/post", [](const Request &req, Response &res) {
  15491. EXPECT_EQ(1u, req.form.fields.size());
  15492. EXPECT_EQ("text1", req.form.get_field("text1"));
  15493. res.set_content("ok", "text/plain");
  15494. });
  15495. auto port = svr.bind_to_any_port(HOST);
  15496. thread t = thread([&] { svr.listen_after_bind(); });
  15497. auto se = detail::scope_exit([&] {
  15498. svr.stop();
  15499. t.join();
  15500. ASSERT_FALSE(svr.is_running());
  15501. });
  15502. svr.wait_until_ready();
  15503. Client cli(HOST, port);
  15504. auto post_with_boundary_of_length = [&](size_t len) {
  15505. const std::string boundary(len, 'a');
  15506. const std::string body =
  15507. "--" + boundary +
  15508. "\r\n"
  15509. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15510. "\r\n"
  15511. "text1"
  15512. "\r\n--" +
  15513. boundary + "--\r\n";
  15514. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15515. };
  15516. auto res = post_with_boundary_of_length(70);
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. EXPECT_EQ(StatusCode::OK_200, res->status);
  15519. res = post_with_boundary_of_length(71);
  15520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15521. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15522. }
  15523. TEST(MakeFileBodyTest, Basic) {
  15524. const std::string file_content(4096, 'Z');
  15525. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15526. {
  15527. std::ofstream ofs(tmp_path, std::ios::binary);
  15528. ofs.write(file_content.data(),
  15529. static_cast<std::streamsize>(file_content.size()));
  15530. }
  15531. auto handled = false;
  15532. Server svr;
  15533. svr.Post("/upload", [&](const Request &req, Response &res) {
  15534. EXPECT_EQ(file_content, req.body);
  15535. handled = true;
  15536. res.status = StatusCode::OK_200;
  15537. });
  15538. auto port = svr.bind_to_any_port(HOST);
  15539. auto t = thread([&] { svr.listen_after_bind(); });
  15540. auto se = detail::scope_exit([&] {
  15541. svr.stop();
  15542. t.join();
  15543. ASSERT_FALSE(svr.is_running());
  15544. ASSERT_TRUE(handled);
  15545. std::remove(tmp_path.c_str());
  15546. });
  15547. svr.wait_until_ready();
  15548. auto fb = make_file_body(tmp_path);
  15549. ASSERT_GT(fb.first, 0u);
  15550. Client cli(HOST, port);
  15551. auto res =
  15552. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15554. EXPECT_EQ(StatusCode::OK_200, res->status);
  15555. }
  15556. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15557. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15558. {
  15559. std::ofstream ofs(path, std::ios::binary);
  15560. const std::string content(100, 'A');
  15561. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15562. }
  15563. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15564. auto body = make_file_body(path);
  15565. ASSERT_EQ(100u, body.first);
  15566. ASSERT_TRUE(static_cast<bool>(body.second));
  15567. // Rewritten shorter after its length was measured - and, on a server, after
  15568. // that length has already gone out as Content-Length.
  15569. {
  15570. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15571. const std::string content(10, 'A');
  15572. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15573. }
  15574. std::string written;
  15575. DataSink sink;
  15576. sink.write = [&](const char *d, size_t l) {
  15577. written.append(d, l);
  15578. return true;
  15579. };
  15580. // The provider has to report failure. write_content_with_progress() advances
  15581. // its offset only by what was written, so a provider that returns true
  15582. // without completing the length it promised is called again straight away,
  15583. // and again.
  15584. EXPECT_FALSE(body.second(0, body.first, sink));
  15585. EXPECT_EQ(std::string(10, 'A'), written);
  15586. }
  15587. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15588. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15589. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15590. {
  15591. std::ofstream ofs(path, std::ios::binary);
  15592. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15593. }
  15594. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15595. auto body = make_file_body(path);
  15596. ASSERT_EQ(content.size(), body.first);
  15597. ASSERT_TRUE(static_cast<bool>(body.second));
  15598. std::string written;
  15599. DataSink sink;
  15600. sink.write = [&](const char *d, size_t l) {
  15601. written.append(d, l);
  15602. return true;
  15603. };
  15604. EXPECT_TRUE(body.second(0, body.first, sink));
  15605. EXPECT_EQ(content, written);
  15606. }
  15607. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15608. static constexpr unsigned int number_of_tasks{1000000};
  15609. std::atomic_uint count{0};
  15610. std::unique_ptr<TaskQueue> task_queue{
  15611. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15612. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15613. auto queued = task_queue->enqueue(
  15614. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15615. EXPECT_TRUE(queued);
  15616. }
  15617. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15618. task_queue->shutdown();
  15619. #else
  15620. EXPECT_NO_THROW(task_queue->shutdown());
  15621. #endif
  15622. EXPECT_EQ(number_of_tasks, count.load());
  15623. }
  15624. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15625. static constexpr unsigned int number_of_tasks{1000000};
  15626. static constexpr unsigned int qlimit{2};
  15627. unsigned int queued_count{0};
  15628. std::atomic_uint count{0};
  15629. std::unique_ptr<TaskQueue> task_queue{
  15630. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15631. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15632. if (task_queue->enqueue(
  15633. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15634. queued_count++;
  15635. }
  15636. }
  15637. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15638. task_queue->shutdown();
  15639. #else
  15640. EXPECT_NO_THROW(task_queue->shutdown());
  15641. #endif
  15642. EXPECT_EQ(queued_count, count.load());
  15643. EXPECT_TRUE(queued_count <= number_of_tasks);
  15644. EXPECT_TRUE(queued_count >= qlimit);
  15645. }
  15646. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15647. // Use a short idle timeout so a dynamic thread spawns, times out and
  15648. // exits during the test, and the pool keeps working afterwards.
  15649. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15650. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15651. /*idle_timeout_sec=*/1}};
  15652. std::atomic_uint count{0};
  15653. std::condition_variable cv;
  15654. std::mutex mtx;
  15655. bool release = false;
  15656. // Block the base thread so the second task spawns a dynamic thread.
  15657. EXPECT_TRUE(task_queue->enqueue([&] {
  15658. std::unique_lock<std::mutex> lock(mtx);
  15659. while (!release) {
  15660. cv.wait(lock);
  15661. }
  15662. count++;
  15663. }));
  15664. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15665. // Let the dynamic thread finish its task and exceed the idle timeout.
  15666. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15667. {
  15668. std::unique_lock<std::mutex> lock(mtx);
  15669. release = true;
  15670. }
  15671. cv.notify_all();
  15672. // The pool must still accept and run tasks after the dynamic thread exited.
  15673. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15674. task_queue->shutdown();
  15675. EXPECT_EQ(3u, count.load());
  15676. }
  15677. TEST(TaskQueueTest, MaxQueuedRequests) {
  15678. static constexpr unsigned int qlimit{3};
  15679. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15680. std::condition_variable sem_cv;
  15681. std::mutex sem_mtx;
  15682. int credits = 0;
  15683. bool queued;
  15684. /* Fill up the queue with tasks that will block until we give them credits to
  15685. * complete. */
  15686. for (unsigned int n = 0; n <= qlimit;) {
  15687. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15688. std::unique_lock<std::mutex> lock(sem_mtx);
  15689. while (credits <= 0) {
  15690. sem_cv.wait(lock);
  15691. }
  15692. /* Consume the credit and signal the test code if they are all gone. */
  15693. if (--credits == 0) { sem_cv.notify_one(); }
  15694. });
  15695. if (n < qlimit) {
  15696. /* The first qlimit enqueues must succeed. */
  15697. EXPECT_TRUE(queued);
  15698. } else {
  15699. /* The last one will succeed only when the worker thread
  15700. * starts and dequeues the first blocking task. Although
  15701. * not necessary for the correctness of this test, we sleep for
  15702. * a short while to avoid busy waiting. */
  15703. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15704. }
  15705. if (queued) { n++; }
  15706. }
  15707. /* Further enqueues must fail since the queue is full. */
  15708. for (auto i = 0; i < 4; i++) {
  15709. queued = task_queue->enqueue([] {});
  15710. EXPECT_FALSE(queued);
  15711. }
  15712. /* Give the credits to allow the previous tasks to complete. */
  15713. {
  15714. std::unique_lock<std::mutex> lock(sem_mtx);
  15715. credits += qlimit + 1;
  15716. }
  15717. sem_cv.notify_all();
  15718. /* Wait for all the credits to be consumed. */
  15719. {
  15720. std::unique_lock<std::mutex> lock(sem_mtx);
  15721. while (credits > 0) {
  15722. sem_cv.wait(lock);
  15723. }
  15724. }
  15725. /* Check that we are able again to enqueue at least qlimit tasks. */
  15726. for (unsigned int i = 0; i < qlimit; i++) {
  15727. queued = task_queue->enqueue([] {});
  15728. EXPECT_TRUE(queued);
  15729. }
  15730. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15731. task_queue->shutdown();
  15732. #else
  15733. EXPECT_NO_THROW(task_queue->shutdown());
  15734. #endif
  15735. }
  15736. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15737. Server svr;
  15738. std::string method;
  15739. std::string body;
  15740. auto has_content_length = false;
  15741. auto has_transfer_encoding = false;
  15742. std::atomic<int> bad_requests{0};
  15743. // Leftover body bytes get parsed as a malformed request and answered with
  15744. // 400
  15745. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15746. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15747. });
  15748. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15749. res.set_redirect("/down", StatusCode::SeeOther_303);
  15750. });
  15751. svr.Get("/down", [&](const Request &req, Response &res) {
  15752. method = req.method;
  15753. body = req.body;
  15754. has_content_length = req.has_header("Content-Length");
  15755. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15756. res.set_content("ok", "text/plain");
  15757. });
  15758. auto port = svr.bind_to_any_port(HOST);
  15759. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15760. auto se = detail::scope_exit([&] {
  15761. svr.stop();
  15762. thread.join();
  15763. ASSERT_FALSE(svr.is_running());
  15764. });
  15765. svr.wait_until_ready();
  15766. const std::string payload = "SECRET-BODY";
  15767. auto check = [&](Client &cli, const Result &res) {
  15768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15769. EXPECT_EQ(StatusCode::OK_200, res->status);
  15770. EXPECT_EQ("ok", res->body);
  15771. EXPECT_EQ("GET", method);
  15772. EXPECT_TRUE(body.empty());
  15773. EXPECT_FALSE(has_content_length);
  15774. EXPECT_FALSE(has_transfer_encoding);
  15775. // Nothing of the original body may be left on the connection
  15776. auto res2 = cli.Get("/down");
  15777. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15778. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15779. EXPECT_EQ("ok", res2->body);
  15780. EXPECT_EQ(0, bad_requests);
  15781. };
  15782. // With content length
  15783. {
  15784. Client cli(HOST, port);
  15785. cli.set_keep_alive(true);
  15786. cli.set_follow_location(true);
  15787. auto res = cli.Post(
  15788. "/up", payload.size(),
  15789. [&](size_t offset, size_t length, DataSink &sink) {
  15790. return sink.write(payload.data() + offset, length);
  15791. },
  15792. "text/plain");
  15793. check(cli, res);
  15794. }
  15795. // Without content length (chunked)
  15796. {
  15797. Client cli(HOST, port);
  15798. cli.set_keep_alive(true);
  15799. cli.set_follow_location(true);
  15800. auto res = cli.Post(
  15801. "/up",
  15802. [&](size_t /*offset*/, DataSink &sink) {
  15803. sink.write(payload.data(), payload.size());
  15804. sink.done();
  15805. return true;
  15806. },
  15807. "text/plain");
  15808. check(cli, res);
  15809. }
  15810. }
  15811. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15812. Server svr;
  15813. std::string target;
  15814. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15815. // Echo the still-encoded name back in the Location
  15816. const std::string prefix = "/start/";
  15817. res.status = StatusCode::Found_302;
  15818. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15819. });
  15820. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15821. target = req.target;
  15822. res.set_content("ok", "text/plain");
  15823. });
  15824. auto port = svr.bind_to_any_port(HOST);
  15825. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15826. auto se = detail::scope_exit([&] {
  15827. svr.stop();
  15828. thread.join();
  15829. ASSERT_FALSE(svr.is_running());
  15830. });
  15831. svr.wait_until_ready();
  15832. // Decoding the Location path would turn the first four into a path
  15833. // separator, a query delimiter, a fragment delimiter and a different
  15834. // percent-encoded octet. The rest must keep reaching the server as they are.
  15835. const std::vector<std::string> names = {
  15836. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15837. };
  15838. for (auto path_encode : {true, false}) {
  15839. Client cli(HOST, port);
  15840. cli.set_follow_location(true);
  15841. cli.set_path_encode(path_encode);
  15842. for (const auto &name : names) {
  15843. target.clear();
  15844. auto res = cli.Get("/start/" + name);
  15845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15846. EXPECT_EQ(StatusCode::OK_200, res->status);
  15847. EXPECT_EQ("/dest/" + name, target);
  15848. }
  15849. }
  15850. }
  15851. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15852. Server svr;
  15853. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15854. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15855. });
  15856. svr.Get("/hello", [](const Request &req, Response &res) {
  15857. res.set_content(req.get_param_value("key"), "text/plain");
  15858. });
  15859. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15860. auto se = detail::scope_exit([&] {
  15861. svr.stop();
  15862. thread.join();
  15863. ASSERT_FALSE(svr.is_running());
  15864. });
  15865. svr.wait_until_ready();
  15866. {
  15867. Client cli(HOST, PORT);
  15868. cli.set_follow_location(true);
  15869. auto res = cli.Get("/");
  15870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15871. EXPECT_EQ(StatusCode::OK_200, res->status);
  15872. EXPECT_EQ("val&key2=val2", res->body);
  15873. }
  15874. }
  15875. #endif
  15876. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15877. Server svr;
  15878. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15879. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15880. });
  15881. svr.Get("/hello", [](const Request &req, Response &res) {
  15882. res.set_content(req.get_param_value("key"), "text/plain");
  15883. });
  15884. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15885. auto se = detail::scope_exit([&] {
  15886. svr.stop();
  15887. thread.join();
  15888. ASSERT_FALSE(svr.is_running());
  15889. });
  15890. svr.wait_until_ready();
  15891. {
  15892. Client cli(HOST, PORT);
  15893. cli.set_follow_location(true);
  15894. auto res = cli.Get("/");
  15895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15896. EXPECT_EQ(StatusCode::OK_200, res->status);
  15897. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15898. }
  15899. }
  15900. TEST(RedirectTest, RedirectWithPlusInPath) {
  15901. Server svr;
  15902. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15903. res.set_redirect("/a+b");
  15904. });
  15905. // Route pattern uses regex; escape + as \\+
  15906. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15907. res.set_content(req.path, "text/plain");
  15908. });
  15909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15910. auto se = detail::scope_exit([&] {
  15911. svr.stop();
  15912. thread.join();
  15913. ASSERT_FALSE(svr.is_running());
  15914. });
  15915. svr.wait_until_ready();
  15916. {
  15917. Client cli(HOST, PORT);
  15918. cli.set_follow_location(true);
  15919. auto res = cli.Get("/");
  15920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15921. EXPECT_EQ(StatusCode::OK_200, res->status);
  15922. EXPECT_EQ("/a+b", res->body);
  15923. }
  15924. }
  15925. TEST(RedirectTest, ResolveRelativeLocation) {
  15926. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15927. const std::vector<std::pair<std::string, std::string>> cases = {
  15928. {"g", "/b/c/g"},
  15929. {"./g", "/b/c/g"},
  15930. {"g/", "/b/c/g/"},
  15931. {"?y", "/b/c/d;p?y"},
  15932. {"g?y", "/b/c/g?y"},
  15933. {"#s", "/b/c/d;p?q#s"},
  15934. {"g#s", "/b/c/g#s"},
  15935. {"g?y#s", "/b/c/g?y#s"},
  15936. {";x", "/b/c/;x"},
  15937. {"g;x", "/b/c/g;x"},
  15938. {".", "/b/c/"},
  15939. {"./", "/b/c/"},
  15940. {"..", "/b/"},
  15941. {"../", "/b/"},
  15942. {"../g", "/b/g"},
  15943. {"../..", "/"},
  15944. {"../../", "/"},
  15945. {"../../g", "/g"},
  15946. {"../../../g", "/g"},
  15947. {"g.", "/b/c/g."},
  15948. {".g", "/b/c/.g"},
  15949. {"g..", "/b/c/g.."},
  15950. {"..g", "/b/c/..g"},
  15951. {"./../g", "/b/g"},
  15952. {"./g/.", "/b/c/g/"},
  15953. {"g/./h", "/b/c/g/h"},
  15954. {"g/../h", "/b/c/h"},
  15955. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15956. {"g;x=1/../y", "/b/c/y"},
  15957. {"g?y/./x", "/b/c/g?y/./x"},
  15958. {"g#s/../x", "/b/c/g#s/../x"},
  15959. // Not relative-path references, so left for parse_url.
  15960. {"/g", "/g"},
  15961. {"//g", "//g"},
  15962. {"http://g/x", "http://g/x"},
  15963. {"g:h", "g:h"},
  15964. };
  15965. for (const auto &c : cases) {
  15966. EXPECT_EQ(c.second,
  15967. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15968. << c.first;
  15969. }
  15970. }
  15971. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15972. Server svr;
  15973. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15974. res.set_redirect(req.get_param_value("to"));
  15975. });
  15976. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15977. res.set_content(req.target, "text/plain");
  15978. });
  15979. svr.Get("/other", [](const Request &req, Response &res) {
  15980. res.set_content(req.target, "text/plain");
  15981. });
  15982. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15983. auto se = detail::scope_exit([&] {
  15984. svr.stop();
  15985. thread.join();
  15986. ASSERT_FALSE(svr.is_running());
  15987. });
  15988. svr.wait_until_ready();
  15989. const std::vector<std::pair<std::string, std::string>> cases = {
  15990. {"next", "/dir/next"},
  15991. {"./next?x=1", "/dir/next?x=1"},
  15992. {"../other", "/other"},
  15993. };
  15994. for (const auto &c : cases) {
  15995. Client cli(HOST, PORT);
  15996. cli.set_follow_location(true);
  15997. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15998. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15999. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16000. EXPECT_EQ(c.second, res->body) << c.first;
  16001. }
  16002. }
  16003. #ifdef CPPHTTPLIB_SSL_ENABLED
  16004. TEST(RedirectTest, Issue2185_Online) {
  16005. SSLClient client("github.com");
  16006. client.set_follow_location(true);
  16007. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16008. "Coollab-Windows.zip");
  16009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16010. EXPECT_EQ(StatusCode::OK_200, res->status);
  16011. EXPECT_EQ(9920427U, res->body.size());
  16012. }
  16013. #endif
  16014. TEST(VulnerabilityTest, CRLFInjection) {
  16015. Server svr;
  16016. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16017. res.set_content("Hello 1", "text/plain");
  16018. });
  16019. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16020. res.set_content("Hello 2", "text/plain");
  16021. });
  16022. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16023. res.set_content("Hello 3", "text/plain");
  16024. });
  16025. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16026. res.set_content("Hello 4", "text/plain");
  16027. });
  16028. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16029. for (const auto &x : req.headers) {
  16030. auto key = x.first;
  16031. EXPECT_STRNE("evil", key.c_str());
  16032. }
  16033. });
  16034. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16035. auto se = detail::scope_exit([&] {
  16036. svr.stop();
  16037. thread.join();
  16038. ASSERT_FALSE(svr.is_running());
  16039. });
  16040. svr.wait_until_ready();
  16041. {
  16042. Client cli(HOST, PORT);
  16043. cli.Post("/test1", "A=B",
  16044. "application/x-www-form-urlencoded\r\nevil: hello1");
  16045. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16046. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16047. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16048. }
  16049. }
  16050. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16051. auto server_thread = std::thread([] {
  16052. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16053. default_socket_options(srv);
  16054. sockaddr_in addr{};
  16055. addr.sin_family = AF_INET;
  16056. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16057. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16058. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16059. ::listen(srv, 1);
  16060. sockaddr_in cli_addr{};
  16061. socklen_t cli_len = sizeof(cli_addr);
  16062. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16063. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16064. std::string buf_all;
  16065. char buf[2048];
  16066. ssize_t n;
  16067. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16068. buf_all.append(buf, static_cast<size_t>(n));
  16069. size_t pos;
  16070. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16071. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16072. auto e = request_block.find("\r\n");
  16073. if (e != std::string::npos) {
  16074. auto request_line = request_block.substr(0, e);
  16075. std::string msg =
  16076. "CRLF injection detected in request line: '" + request_line + "'";
  16077. EXPECT_FALSE(true) << msg;
  16078. }
  16079. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16080. ::send(cli,
  16081. #ifdef _WIN32
  16082. static_cast<const char *>(resp.c_str()),
  16083. static_cast<int>(resp.size()),
  16084. #else
  16085. resp.c_str(), resp.size(),
  16086. #endif
  16087. 0);
  16088. buf_all.erase(0, pos + 4);
  16089. }
  16090. }
  16091. detail::close_socket(cli);
  16092. detail::close_socket(srv);
  16093. });
  16094. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16095. auto cli = Client("127.0.0.1", PORT + 1);
  16096. auto headers = Headers{
  16097. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16098. {"Connection", "keep-alive"}};
  16099. auto res = cli.Get("/hi", headers);
  16100. EXPECT_FALSE(res);
  16101. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16102. server_thread.join();
  16103. }
  16104. // A request rejected before any byte reaches the socket must fail right away
  16105. // instead of waiting for a response the server will never send.
  16106. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16107. // The kernel completes the TCP handshake from the listen backlog, so the
  16108. // client connects, but nothing ever reads, responds or closes.
  16109. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16110. default_socket_options(srv);
  16111. sockaddr_in addr{};
  16112. addr.sin_family = AF_INET;
  16113. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16115. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16116. ASSERT_EQ(0, ::listen(srv, 8));
  16117. auto cli = Client("127.0.0.1", PORT + 1);
  16118. cli.set_read_timeout(10, 0);
  16119. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16120. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16121. std::chrono::steady_clock::now() - start)
  16122. .count();
  16123. };
  16124. {
  16125. Request req;
  16126. req.method = "GE T";
  16127. req.path = "/";
  16128. auto start = std::chrono::steady_clock::now();
  16129. auto res = cli.send(req);
  16130. EXPECT_FALSE(res);
  16131. EXPECT_EQ(Error::Write, res.error());
  16132. EXPECT_LT(elapsed_ms(start), 1000);
  16133. }
  16134. {
  16135. auto start = std::chrono::steady_clock::now();
  16136. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16137. EXPECT_FALSE(res);
  16138. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16139. EXPECT_LT(elapsed_ms(start), 1000);
  16140. }
  16141. EXPECT_FALSE(cli.is_socket_open());
  16142. detail::close_socket(srv);
  16143. }
  16144. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16145. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16146. default_socket_options(srv);
  16147. sockaddr_in addr{};
  16148. addr.sin_family = AF_INET;
  16149. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16150. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16151. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16152. ASSERT_EQ(0, ::listen(srv, 1));
  16153. std::string received;
  16154. auto server_thread = std::thread([&] {
  16155. auto sock = ::accept(srv, nullptr, nullptr);
  16156. if (sock == INVALID_SOCKET) { return; }
  16157. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16158. char buf[2048];
  16159. ssize_t n;
  16160. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16161. received.append(buf, static_cast<size_t>(n));
  16162. }
  16163. detail::close_socket(sock);
  16164. });
  16165. {
  16166. auto cli = Client("127.0.0.1", PORT + 1);
  16167. // "Z" sorts after the default headers, so writing straight to the socket
  16168. // would have sent the request line and those headers before the rejection.
  16169. auto handle =
  16170. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16171. EXPECT_FALSE(handle.is_valid());
  16172. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16173. }
  16174. server_thread.join();
  16175. detail::close_socket(srv);
  16176. EXPECT_TRUE(received.empty()) << received;
  16177. }
  16178. TEST(PathParamsTest, StaticMatch) {
  16179. const auto pattern = "/users/all";
  16180. detail::PathParamsMatcher matcher(pattern);
  16181. Request request;
  16182. request.path = "/users/all";
  16183. ASSERT_TRUE(matcher.match(request));
  16184. std::unordered_map<std::string, std::string> expected_params = {};
  16185. EXPECT_EQ(request.path_params, expected_params);
  16186. }
  16187. TEST(PathParamsTest, StaticMismatch) {
  16188. const auto pattern = "/users/all";
  16189. detail::PathParamsMatcher matcher(pattern);
  16190. Request request;
  16191. request.path = "/users/1";
  16192. ASSERT_FALSE(matcher.match(request));
  16193. }
  16194. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16195. const auto pattern = "/users/:id/subscriptions";
  16196. detail::PathParamsMatcher matcher(pattern);
  16197. Request request;
  16198. request.path = "/users/42/subscriptions";
  16199. ASSERT_TRUE(matcher.match(request));
  16200. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16201. EXPECT_EQ(request.path_params, expected_params);
  16202. }
  16203. TEST(PathParamsTest, SingleParamInTheEnd) {
  16204. const auto pattern = "/users/:id";
  16205. detail::PathParamsMatcher matcher(pattern);
  16206. Request request;
  16207. request.path = "/users/24";
  16208. ASSERT_TRUE(matcher.match(request));
  16209. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16210. EXPECT_EQ(request.path_params, expected_params);
  16211. }
  16212. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16213. const auto pattern = "/users/:id/";
  16214. detail::PathParamsMatcher matcher(pattern);
  16215. Request request;
  16216. request.path = "/users/42/";
  16217. ASSERT_TRUE(matcher.match(request));
  16218. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16219. EXPECT_EQ(request.path_params, expected_params);
  16220. }
  16221. TEST(PathParamsTest, EmptyParam) {
  16222. const auto pattern = "/users/:id/";
  16223. detail::PathParamsMatcher matcher(pattern);
  16224. Request request;
  16225. request.path = "/users//";
  16226. ASSERT_TRUE(matcher.match(request));
  16227. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16228. EXPECT_EQ(request.path_params, expected_params);
  16229. }
  16230. TEST(PathParamsTest, FragmentMismatch) {
  16231. const auto pattern = "/users/:id/";
  16232. detail::PathParamsMatcher matcher(pattern);
  16233. Request request;
  16234. request.path = "/admins/24/";
  16235. ASSERT_FALSE(matcher.match(request));
  16236. }
  16237. TEST(PathParamsTest, ExtraFragments) {
  16238. const auto pattern = "/users/:id";
  16239. detail::PathParamsMatcher matcher(pattern);
  16240. Request request;
  16241. request.path = "/users/42/subscriptions";
  16242. ASSERT_FALSE(matcher.match(request));
  16243. }
  16244. TEST(PathParamsTest, MissingTrailingParam) {
  16245. const auto pattern = "/users/:id";
  16246. detail::PathParamsMatcher matcher(pattern);
  16247. Request request;
  16248. request.path = "/users";
  16249. ASSERT_FALSE(matcher.match(request));
  16250. }
  16251. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16252. const auto pattern = "/users/:id/subscriptions";
  16253. detail::PathParamsMatcher matcher(pattern);
  16254. Request request;
  16255. request.path = "/users/subscriptions";
  16256. ASSERT_FALSE(matcher.match(request));
  16257. }
  16258. TEST(PathParamsTest, MultipleParams) {
  16259. const auto pattern = "/users/:userid/subscriptions/:subid";
  16260. detail::PathParamsMatcher matcher(pattern);
  16261. Request request;
  16262. request.path = "/users/42/subscriptions/2";
  16263. ASSERT_TRUE(matcher.match(request));
  16264. std::unordered_map<std::string, std::string> expected_params = {
  16265. {"userid", "42"}, {"subid", "2"}};
  16266. EXPECT_EQ(request.path_params, expected_params);
  16267. }
  16268. TEST(PathParamsTest, SequenceOfParams) {
  16269. const auto pattern = "/values/:x/:y/:z";
  16270. detail::PathParamsMatcher matcher(pattern);
  16271. Request request;
  16272. request.path = "/values/1/2/3";
  16273. ASSERT_TRUE(matcher.match(request));
  16274. std::unordered_map<std::string, std::string> expected_params = {
  16275. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16276. EXPECT_EQ(request.path_params, expected_params);
  16277. }
  16278. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16279. const auto pattern = "/prefix:suffix";
  16280. detail::PathParamsMatcher matcher(pattern);
  16281. Request request;
  16282. request.path = "/prefix:suffix";
  16283. ASSERT_TRUE(matcher.match(request));
  16284. const std::unordered_map<std::string, std::string> expected_params = {};
  16285. EXPECT_EQ(request.path_params, expected_params);
  16286. }
  16287. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16288. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16289. // calling thread's stack on a long enough path for a quantified pattern;
  16290. // RegexMatcher must refuse to run regex matching on paths beyond
  16291. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16292. detail::RegexMatcher matcher("/files/(.*)");
  16293. Request within_limit;
  16294. within_limit.path = "/files/" + std::string(10, 'A');
  16295. EXPECT_TRUE(matcher.match(within_limit));
  16296. Request over_limit;
  16297. over_limit.path =
  16298. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16299. EXPECT_FALSE(matcher.match(over_limit));
  16300. }
  16301. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16302. Server svr;
  16303. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16304. res.set_content("ok", "text/plain");
  16305. });
  16306. auto port = svr.bind_to_any_port(HOST);
  16307. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16308. auto se = detail::scope_exit([&] {
  16309. svr.stop();
  16310. thread.join();
  16311. ASSERT_FALSE(svr.is_running());
  16312. });
  16313. svr.wait_until_ready();
  16314. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16315. // request URI limit; this used to be able to crash the process.
  16316. std::string path =
  16317. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16318. std::string req = "GET " + path +
  16319. " HTTP/1.1\r\n"
  16320. "Host: " +
  16321. std::string(HOST) + ":" + std::to_string(port) +
  16322. "\r\n"
  16323. "Connection: close\r\n"
  16324. "\r\n";
  16325. std::string response;
  16326. ASSERT_TRUE(send_request(5, req, &response, port));
  16327. EXPECT_NE(std::string::npos, response.find("404"));
  16328. }
  16329. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16330. Server svr;
  16331. auto handler = [](const Request & /*req*/, Response &res) {
  16332. res.set_content("hit", "text/plain");
  16333. };
  16334. // No regex metacharacter, so this one is compared literally
  16335. svr.Get("/literal/route", handler);
  16336. // '.' is a regex metacharacter, so this one must keep regex semantics
  16337. svr.Get("/a.c", handler);
  16338. auto port = svr.bind_to_any_port(HOST);
  16339. std::thread t([&]() { svr.listen_after_bind(); });
  16340. auto se = detail::scope_exit([&] {
  16341. svr.stop();
  16342. t.join();
  16343. ASSERT_FALSE(svr.is_running());
  16344. });
  16345. svr.wait_until_ready();
  16346. Client cli(HOST, port);
  16347. struct {
  16348. const char *path;
  16349. int status;
  16350. } cases[] = {
  16351. {"/literal/route", StatusCode::OK_200},
  16352. {"/literal/routes", StatusCode::NotFound_404},
  16353. {"/literal/rout", StatusCode::NotFound_404},
  16354. {"/abc", StatusCode::OK_200},
  16355. {"/a.c", StatusCode::OK_200},
  16356. };
  16357. for (const auto &x : cases) {
  16358. auto res = cli.Get(x.path);
  16359. ASSERT_TRUE(res) << x.path;
  16360. EXPECT_EQ(x.status, res->status) << x.path;
  16361. }
  16362. }
  16363. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16364. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16365. // from exhausting the stack, so it must only constrain routes that actually
  16366. // run a regular expression. A literal route is matched by comparison and
  16367. // stays usable at any length.
  16368. Server svr;
  16369. const std::string pattern =
  16370. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16371. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16372. res.set_content("hit", "text/plain");
  16373. });
  16374. auto port = svr.bind_to_any_port(HOST);
  16375. std::thread t([&]() { svr.listen_after_bind(); });
  16376. auto se = detail::scope_exit([&] {
  16377. svr.stop();
  16378. t.join();
  16379. ASSERT_FALSE(svr.is_running());
  16380. });
  16381. svr.wait_until_ready();
  16382. Client cli(HOST, port);
  16383. auto res = cli.Get(pattern);
  16384. ASSERT_TRUE(res);
  16385. EXPECT_EQ(StatusCode::OK_200, res->status);
  16386. }
  16387. TEST(ParseUrlTest, VariousPatterns) {
  16388. {
  16389. detail::UrlComponents uc;
  16390. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16391. EXPECT_EQ("http", uc.scheme);
  16392. EXPECT_EQ("example.com", uc.host);
  16393. EXPECT_EQ("8080", uc.port);
  16394. EXPECT_EQ("/path", uc.path);
  16395. EXPECT_EQ("?q=1", uc.query);
  16396. }
  16397. {
  16398. detail::UrlComponents uc;
  16399. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16400. EXPECT_EQ("https", uc.scheme);
  16401. EXPECT_EQ("example.com", uc.host);
  16402. EXPECT_TRUE(uc.port.empty());
  16403. EXPECT_EQ("/path", uc.path);
  16404. }
  16405. {
  16406. detail::UrlComponents uc;
  16407. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16408. EXPECT_EQ("::1", uc.host);
  16409. EXPECT_EQ("8080", uc.port);
  16410. EXPECT_EQ("/path", uc.path);
  16411. }
  16412. {
  16413. detail::UrlComponents uc;
  16414. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16415. }
  16416. {
  16417. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16418. // the path while the connection still targets the bracketed host.
  16419. detail::UrlComponents uc;
  16420. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16421. }
  16422. {
  16423. detail::UrlComponents uc;
  16424. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16425. }
  16426. {
  16427. detail::UrlComponents uc;
  16428. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16429. EXPECT_EQ("::1", uc.host);
  16430. EXPECT_TRUE(uc.port.empty());
  16431. EXPECT_EQ("/path", uc.path);
  16432. }
  16433. {
  16434. detail::UrlComponents uc;
  16435. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16436. EXPECT_TRUE(uc.scheme.empty());
  16437. EXPECT_EQ("example.com", uc.host);
  16438. EXPECT_EQ("/path", uc.path);
  16439. EXPECT_EQ("?q=1", uc.query);
  16440. }
  16441. {
  16442. detail::UrlComponents uc;
  16443. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16444. EXPECT_TRUE(uc.host.empty());
  16445. EXPECT_EQ("/path", uc.path);
  16446. EXPECT_EQ("?q=1", uc.query);
  16447. }
  16448. {
  16449. detail::UrlComponents uc;
  16450. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16451. EXPECT_EQ("example.com", uc.host);
  16452. EXPECT_EQ("8080", uc.port);
  16453. }
  16454. {
  16455. // Unix socket path — must not be parsed as host
  16456. detail::UrlComponents uc;
  16457. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16458. EXPECT_TRUE(uc.host.empty());
  16459. }
  16460. {
  16461. detail::UrlComponents uc;
  16462. ASSERT_TRUE(detail::parse_url("", uc));
  16463. EXPECT_TRUE(uc.host.empty());
  16464. EXPECT_TRUE(uc.path.empty());
  16465. }
  16466. {
  16467. detail::UrlComponents uc;
  16468. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16469. }
  16470. {
  16471. detail::UrlComponents uc;
  16472. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16473. }
  16474. {
  16475. // Accepted by parse_url; callers restrict to http/https
  16476. detail::UrlComponents uc;
  16477. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16478. EXPECT_EQ("ftp", uc.scheme);
  16479. }
  16480. {
  16481. detail::UrlComponents uc;
  16482. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16483. }
  16484. {
  16485. detail::UrlComponents uc;
  16486. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16487. }
  16488. }
  16489. TEST(ParseUrlTest, FragmentHandling) {
  16490. {
  16491. detail::UrlComponents uc;
  16492. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16493. EXPECT_EQ("/path", uc.path);
  16494. EXPECT_TRUE(uc.query.empty());
  16495. }
  16496. {
  16497. detail::UrlComponents uc;
  16498. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16499. EXPECT_TRUE(uc.path.empty());
  16500. EXPECT_TRUE(uc.query.empty());
  16501. }
  16502. }
  16503. TEST(ParseUrlTest, UserinfoHandling) {
  16504. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16505. // '/', would see evil.com where the host used to be the whole authority.
  16506. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16507. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16508. for (auto url : urls) {
  16509. detail::UrlComponents uc;
  16510. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16511. }
  16512. }
  16513. TEST(ParseUrlTest, IPv6EdgeCases) {
  16514. {
  16515. detail::UrlComponents uc;
  16516. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16517. EXPECT_TRUE(uc.scheme.empty());
  16518. EXPECT_EQ("::1", uc.host);
  16519. EXPECT_EQ("8080", uc.port);
  16520. }
  16521. {
  16522. // Zone ID '%25' is not in [a-fA-F0-9:]
  16523. detail::UrlComponents uc;
  16524. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16525. }
  16526. }
  16527. TEST(ParseUrlTest, SchemeEdgeCases) {
  16528. {
  16529. detail::UrlComponents uc;
  16530. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16531. }
  16532. {
  16533. detail::UrlComponents uc;
  16534. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16535. }
  16536. {
  16537. detail::UrlComponents uc;
  16538. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16539. }
  16540. }
  16541. TEST(ParseUrlTest, PortEdgeCases) {
  16542. {
  16543. detail::UrlComponents uc;
  16544. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16545. EXPECT_TRUE(uc.port.empty());
  16546. EXPECT_EQ("/path", uc.path);
  16547. }
  16548. {
  16549. // parse_url accepts any port string; validation is done by parse_port
  16550. detail::UrlComponents uc;
  16551. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16552. EXPECT_EQ("abc", uc.port);
  16553. }
  16554. }
  16555. TEST(ParseUrlTest, WebSocketPatterns) {
  16556. {
  16557. detail::UrlComponents uc;
  16558. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16559. EXPECT_EQ("ws", uc.scheme);
  16560. EXPECT_EQ("echo.example.com", uc.host);
  16561. EXPECT_EQ("8080", uc.port);
  16562. EXPECT_EQ("/ws", uc.path);
  16563. }
  16564. {
  16565. detail::UrlComponents uc;
  16566. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16567. EXPECT_EQ("wss", uc.scheme);
  16568. EXPECT_EQ("echo.example.com", uc.host);
  16569. EXPECT_TRUE(uc.port.empty());
  16570. EXPECT_EQ("/ws", uc.path);
  16571. }
  16572. }
  16573. TEST(ParseUrlTest, QueryOnly) {
  16574. detail::UrlComponents uc;
  16575. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16576. EXPECT_TRUE(uc.host.empty());
  16577. EXPECT_TRUE(uc.path.empty());
  16578. EXPECT_EQ("?q=1&r=2", uc.query);
  16579. }
  16580. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16581. detail::UrlComponents uc;
  16582. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16583. EXPECT_TRUE(uc.scheme.empty());
  16584. EXPECT_EQ("example.com", uc.host);
  16585. EXPECT_EQ("443", uc.port);
  16586. EXPECT_EQ("/path", uc.path);
  16587. }
  16588. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16589. // If ipv6 regex working, regex match codepath is taken.
  16590. // else port will default to 80 in Client impl
  16591. int clientImplMagicPort = 80;
  16592. int port = 4321;
  16593. // above ports must be different to avoid false negative
  16594. EXPECT_NE(clientImplMagicPort, port);
  16595. std::string ipV6TestURL = "http://[ff06::c3]";
  16596. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16597. CLIENT_PRIVATE_KEY_FILE);
  16598. EXPECT_EQ(cli.port(), port);
  16599. }
  16600. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16601. auto file_path = "./www/dir/index.html";
  16602. auto dir_path = "./www/dir";
  16603. detail::FileStat stat_file(file_path);
  16604. EXPECT_TRUE(stat_file.is_file());
  16605. EXPECT_FALSE(stat_file.is_dir());
  16606. detail::FileStat stat_dir(dir_path);
  16607. EXPECT_FALSE(stat_dir.is_file());
  16608. EXPECT_TRUE(stat_dir.is_dir());
  16609. }
  16610. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16611. // IPv4 with default HTTP port (80)
  16612. EXPECT_EQ("example.com",
  16613. detail::make_host_and_port_string("example.com", 80, false));
  16614. // IPv4 with default HTTPS port (443)
  16615. EXPECT_EQ("example.com",
  16616. detail::make_host_and_port_string("example.com", 443, true));
  16617. // IPv4 with non-default HTTP port
  16618. EXPECT_EQ("example.com:8080",
  16619. detail::make_host_and_port_string("example.com", 8080, false));
  16620. // IPv4 with non-default HTTPS port
  16621. EXPECT_EQ("example.com:8443",
  16622. detail::make_host_and_port_string("example.com", 8443, true));
  16623. // IPv6 with default HTTP port (80)
  16624. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16625. // IPv6 with default HTTPS port (443)
  16626. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16627. // IPv6 with non-default HTTP port
  16628. EXPECT_EQ("[::1]:8080",
  16629. detail::make_host_and_port_string("::1", 8080, false));
  16630. // IPv6 with non-default HTTPS port
  16631. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16632. // IPv6 full address with default port
  16633. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16634. detail::make_host_and_port_string(
  16635. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16636. // IPv6 full address with non-default port
  16637. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16638. detail::make_host_and_port_string(
  16639. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16640. // IPv6 localhost with non-default port
  16641. EXPECT_EQ("[::1]:3000",
  16642. detail::make_host_and_port_string("::1", 3000, false));
  16643. // IPv6 with zone ID (link-local address) with default port
  16644. EXPECT_EQ("[fe80::1%eth0]",
  16645. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16646. // IPv6 with zone ID (link-local address) with non-default port
  16647. EXPECT_EQ("[fe80::1%eth0]:8080",
  16648. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16649. // Edge case: Port 443 with is_ssl=false (should add port)
  16650. EXPECT_EQ("example.com:443",
  16651. detail::make_host_and_port_string("example.com", 443, false));
  16652. // Edge case: Port 80 with is_ssl=true (should add port)
  16653. EXPECT_EQ("example.com:80",
  16654. detail::make_host_and_port_string("example.com", 80, true));
  16655. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16656. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16657. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16658. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16659. // Security fix: Already bracketed IPv6 should not get double brackets
  16660. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16661. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16662. EXPECT_EQ("[::1]:8080",
  16663. detail::make_host_and_port_string("[::1]", 8080, false));
  16664. EXPECT_EQ("[2001:db8::1]:8080",
  16665. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16666. EXPECT_EQ("[fe80::1%eth0]",
  16667. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16668. EXPECT_EQ("[fe80::1%eth0]:8080",
  16669. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16670. // Edge case: Empty host (should return as-is)
  16671. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16672. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16673. // This is a known limitation but shouldn't crash
  16674. EXPECT_EQ("[host:name]",
  16675. detail::make_host_and_port_string("host:name", 80, false));
  16676. // Port number edge cases (no validation, but should not crash)
  16677. EXPECT_EQ("example.com:0",
  16678. detail::make_host_and_port_string("example.com", 0, false));
  16679. EXPECT_EQ("example.com:-1",
  16680. detail::make_host_and_port_string("example.com", -1, false));
  16681. EXPECT_EQ("example.com:65535",
  16682. detail::make_host_and_port_string("example.com", 65535, false));
  16683. EXPECT_EQ("example.com:65536",
  16684. detail::make_host_and_port_string("example.com", 65536, false));
  16685. }
  16686. #ifdef CPPHTTPLIB_SSL_ENABLED
  16687. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16688. httplib::SSLClient cli("roblox.com", 443);
  16689. cli.set_follow_location(true);
  16690. auto res = cli.Get("/");
  16691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16692. EXPECT_EQ(StatusCode::OK_200, res->status);
  16693. }
  16694. #endif
  16695. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16696. Server svr;
  16697. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16698. EXPECT_EQ(res.status, 400);
  16699. });
  16700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16701. auto se = detail::scope_exit([&] {
  16702. svr.stop();
  16703. thread.join();
  16704. ASSERT_FALSE(svr.is_running());
  16705. });
  16706. svr.wait_until_ready();
  16707. Client cli(HOST, PORT);
  16708. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16709. }
  16710. TEST(InvalidHeaderCharsTest, is_field_name) {
  16711. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16712. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16713. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16714. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16715. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16716. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16717. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16718. EXPECT_FALSE(detail::fields::is_field_name(""));
  16719. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16720. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16721. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16722. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16723. }
  16724. TEST(InvalidHeaderCharsTest, is_field_value) {
  16725. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16726. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16727. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16728. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16729. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16730. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16731. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16732. EXPECT_TRUE(detail::fields::is_field_value(""));
  16733. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16734. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16735. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16736. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16737. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16738. }
  16739. TEST(InvalidHeaderCharsTest, OnServer) {
  16740. Server svr;
  16741. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16742. std::string header = "Not Set";
  16743. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16744. res.set_header(header, "value");
  16745. res.set_content("Page Content Page Content", "text/plain");
  16746. });
  16747. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16748. std::string header = "Not Set";
  16749. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16750. res.set_header("X-Test", header);
  16751. res.set_content("Page Content Page Content", "text/plain");
  16752. });
  16753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16754. auto se = detail::scope_exit([&] {
  16755. svr.stop();
  16756. thread.join();
  16757. ASSERT_FALSE(svr.is_running());
  16758. });
  16759. svr.wait_until_ready();
  16760. Client cli(HOST, PORT);
  16761. {
  16762. auto res = cli.Get(
  16763. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16765. EXPECT_EQ("Page Content Page Content", res->body);
  16766. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16767. }
  16768. {
  16769. auto res = cli.Get(
  16770. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16772. EXPECT_EQ("Page Content Page Content", res->body);
  16773. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16774. }
  16775. }
  16776. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16777. auto handled = false;
  16778. Server svr;
  16779. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16780. thread t = thread([&] { svr.listen(HOST, PORT); });
  16781. auto se = detail::scope_exit([&] {
  16782. svr.stop();
  16783. t.join();
  16784. ASSERT_FALSE(svr.is_running());
  16785. ASSERT_FALSE(handled);
  16786. });
  16787. svr.wait_until_ready();
  16788. auto req = "POST /test HTTP/1.1\r\n"
  16789. "Content-Length: x\r\n"
  16790. "\r\n";
  16791. std::string response;
  16792. ASSERT_TRUE(send_request(1, req, &response));
  16793. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16794. response.substr(0, response.find("\r\n")));
  16795. }
  16796. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16797. // case-insensitive, and a server that receives a 100-continue expectation in
  16798. // an HTTP/1.0 request MUST ignore it.
  16799. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16800. std::string response;
  16801. ASSERT_TRUE(send_request(1, req, &response, port));
  16802. *got_100 = response.find("100 Continue") != std::string::npos;
  16803. }
  16804. class ExpectTokenTest : public ::testing::Test {
  16805. protected:
  16806. void SetUp() override {
  16807. svr_.Post("/p", [](const Request &, Response &res) {
  16808. res.set_content("ok", "text/plain");
  16809. });
  16810. port_ = svr_.bind_to_any_port(HOST);
  16811. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16812. svr_.wait_until_ready();
  16813. }
  16814. void TearDown() override {
  16815. svr_.stop();
  16816. if (thread_.joinable()) { thread_.join(); }
  16817. }
  16818. std::string request(const char *version, const char *expect_value) const {
  16819. return std::string("POST /p ") + version +
  16820. "\r\n"
  16821. "Host: localhost\r\n"
  16822. "Content-Length: 2\r\n"
  16823. "Connection: close\r\n"
  16824. "Expect: " +
  16825. expect_value +
  16826. "\r\n"
  16827. "\r\n"
  16828. "hi";
  16829. }
  16830. Server svr_;
  16831. int port_ = 0;
  16832. thread thread_;
  16833. };
  16834. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16835. bool got_100 = false;
  16836. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16837. EXPECT_TRUE(got_100);
  16838. }
  16839. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16840. bool got_100 = true;
  16841. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16842. EXPECT_FALSE(got_100);
  16843. }
  16844. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16845. bool got_100 = false;
  16846. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16847. EXPECT_TRUE(got_100);
  16848. }
  16849. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16850. bool got_100 = false;
  16851. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16852. EXPECT_TRUE(got_100);
  16853. }
  16854. // `100 Continue` is sent only when the server starts reading the body, so a
  16855. // request rejected before that never invites the client to send it. The
  16856. // requests below carry the expectation but withhold the body, as a client
  16857. // waiting for `100 Continue` would.
  16858. // A POST that expects `100 Continue` and withholds its two-byte body.
  16859. static std::string expect_headers_only(const std::string &path) {
  16860. return "POST " + path +
  16861. " HTTP/1.1\r\n"
  16862. "Host: localhost\r\n"
  16863. "Content-Length: 2\r\n"
  16864. "Expect: 100-continue\r\n"
  16865. "\r\n";
  16866. }
  16867. class ExpectLazyContinueTest : public ::testing::Test {
  16868. protected:
  16869. void SetUp() override {
  16870. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16871. if (req.path == "/pre-routing") {
  16872. res.status = StatusCode::Unauthorized_401;
  16873. return Server::HandlerResponse::Handled;
  16874. }
  16875. return Server::HandlerResponse::Unhandled;
  16876. });
  16877. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16878. if (req.matched_route == "/pre-request") {
  16879. res.status = StatusCode::Forbidden_403;
  16880. return Server::HandlerResponse::Handled;
  16881. }
  16882. return Server::HandlerResponse::Unhandled;
  16883. });
  16884. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16885. res.set_content("ok", "text/plain");
  16886. });
  16887. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16888. res.set_content("ok", "text/plain");
  16889. });
  16890. svr_.Post("/reader-used", [](const Request &, Response &res,
  16891. const ContentReader &content_reader) {
  16892. std::string body;
  16893. content_reader([&](const char *data, size_t len) {
  16894. body.append(data, len);
  16895. return true;
  16896. });
  16897. res.set_content(body, "text/plain");
  16898. });
  16899. svr_.Post("/reader-unused",
  16900. [](const Request &, Response &res, const ContentReader &) {
  16901. res.set_content("ignored", "text/plain");
  16902. });
  16903. port_ = svr_.bind_to_any_port(HOST);
  16904. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16905. svr_.wait_until_ready();
  16906. }
  16907. void TearDown() override {
  16908. svr_.stop();
  16909. if (thread_.joinable()) { thread_.join(); }
  16910. }
  16911. // Sends `req` and reads until the server closes the connection. Returns
  16912. // false if the read had to wait for the client-side timeout instead.
  16913. bool send_until_closed(const std::string &req, std::string *resp) const {
  16914. auto start = std::chrono::steady_clock::now();
  16915. if (!send_request(3, req, resp, port_)) { return false; }
  16916. auto elapsed = std::chrono::steady_clock::now() - start;
  16917. return elapsed < std::chrono::seconds(2);
  16918. }
  16919. // The final response comes without `100 Continue`, and the server closes
  16920. // the connection since the body may or may not follow.
  16921. void expect_final_without_interim(const std::string &path,
  16922. const char *status_line) const {
  16923. std::string resp;
  16924. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16925. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16926. EXPECT_EQ(0u, resp.find(status_line));
  16927. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16928. }
  16929. Server svr_;
  16930. int port_ = 0;
  16931. thread thread_;
  16932. };
  16933. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16934. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16935. }
  16936. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16937. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16938. }
  16939. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16940. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16941. }
  16942. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16943. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16944. }
  16945. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16946. // The body follows once `100 Continue` has had time to arrive.
  16947. auto req = expect_headers_only("/reader-used");
  16948. req.insert(req.size() - 2, "Connection: close\r\n");
  16949. std::string resp;
  16950. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16951. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16952. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16953. EXPECT_NE(std::string::npos, resp.find("hi"));
  16954. }
  16955. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16956. // Large enough for the client to add `Expect: 100-continue` itself.
  16957. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16958. std::atomic<bool> body_sent{false};
  16959. Client cli(HOST, port_);
  16960. auto res = cli.Post(
  16961. "/pre-request", length,
  16962. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16963. body_sent = true;
  16964. std::string chunk(len, 'x');
  16965. sink.write(chunk.data(), chunk.size());
  16966. return true;
  16967. },
  16968. "application/octet-stream");
  16969. ASSERT_TRUE(res);
  16970. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16971. EXPECT_FALSE(body_sent);
  16972. }
  16973. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16974. Server svr;
  16975. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16976. return StatusCode::ExpectationFailed_417;
  16977. });
  16978. svr.Post("/p", [](const Request &, Response &res) {
  16979. res.set_content("ok", "text/plain");
  16980. });
  16981. auto port = svr.bind_to_any_port(HOST);
  16982. thread t = thread([&] { svr.listen_after_bind(); });
  16983. auto se = detail::scope_exit([&] {
  16984. svr.stop();
  16985. t.join();
  16986. });
  16987. svr.wait_until_ready();
  16988. std::string resp;
  16989. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16990. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16991. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16992. // Exactly one response: the route handler must not run after the 417.
  16993. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16994. }
  16995. #ifndef _WIN32
  16996. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16997. static constexpr char reject[] = "Unauthorized";
  16998. static constexpr char accept[] = "Upload accepted";
  16999. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17000. Server svr;
  17001. svr.set_expect_100_continue_handler(
  17002. [](const Request & /*req*/, Response &res) {
  17003. res.status = StatusCode::Unauthorized_401;
  17004. res.set_content(reject, "text/plain");
  17005. return res.status;
  17006. });
  17007. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17008. res.set_content(accept, "text/plain");
  17009. });
  17010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17011. auto se = detail::scope_exit([&] {
  17012. svr.stop();
  17013. thread.join();
  17014. ASSERT_FALSE(svr.is_running());
  17015. });
  17016. svr.wait_until_ready();
  17017. {
  17018. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17019. curl_easy_init(), &curl_easy_cleanup};
  17020. ASSERT_NE(curl, nullptr);
  17021. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17022. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17023. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17024. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17025. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17026. &curl_slist_free_all};
  17027. ASSERT_NE(list, nullptr);
  17028. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17029. struct read_data {
  17030. size_t read_size;
  17031. size_t total_size;
  17032. } data = {0, total_size};
  17033. using read_callback_t =
  17034. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17035. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17036. void *userdata) -> size_t {
  17037. read_data *d = (read_data *)userdata;
  17038. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17039. std::fill_n(ptr, size * nmemb, 'A');
  17040. d->read_size += size * nmemb;
  17041. return size * nmemb;
  17042. };
  17043. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17044. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17045. std::vector<char> buffer;
  17046. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17047. using write_callback_t =
  17048. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17049. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17050. void *userdata) -> size_t {
  17051. std::vector<char> *buf = (std::vector<char> *)userdata;
  17052. buf->reserve(buf->size() + size * nmemb + 1);
  17053. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17054. return size * nmemb;
  17055. };
  17056. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17057. {
  17058. const auto res = curl_easy_perform(curl.get());
  17059. ASSERT_EQ(res, CURLE_OK);
  17060. }
  17061. {
  17062. auto response_code = long{};
  17063. const auto res =
  17064. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17065. ASSERT_EQ(res, CURLE_OK);
  17066. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17067. }
  17068. {
  17069. auto dl = curl_off_t{};
  17070. const auto res =
  17071. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17072. ASSERT_EQ(res, CURLE_OK);
  17073. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17074. }
  17075. {
  17076. buffer.push_back('\0');
  17077. ASSERT_STRCASEEQ(buffer.data(), reject);
  17078. }
  17079. }
  17080. }
  17081. #endif
  17082. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17083. // Regression test for #2458.
  17084. //
  17085. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17086. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17087. // ticket can make the client socket spuriously readable during the
  17088. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17089. // the client withholds the body and then blocks reading a response that never
  17090. // comes, failing with `Failed to read connection`.
  17091. //
  17092. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17093. // within the timeout. This raw OpenSSL server deliberately never sends
  17094. // `100 Continue`; the client must still deliver the body and receive 200.
  17095. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17096. signal(SIGPIPE, SIG_IGN);
  17097. const auto port = PORT + 4;
  17098. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17099. ASSERT_NE(srv, INVALID_SOCKET);
  17100. int opt = 1;
  17101. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17102. sockaddr_in addr{};
  17103. addr.sin_family = AF_INET;
  17104. addr.sin_port = htons(static_cast<uint16_t>(port));
  17105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17106. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17107. ASSERT_EQ(0, ::listen(srv, 1));
  17108. std::atomic<size_t> server_body_bytes{0};
  17109. auto server_thread = std::thread([&] {
  17110. sockaddr_in cli_addr{};
  17111. socklen_t cli_len = sizeof(cli_addr);
  17112. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17113. if (cli == INVALID_SOCKET) { return; }
  17114. // Bound the lifetime of the server side so a buggy client (which never
  17115. // sends the body) cannot make this thread block forever on join.
  17116. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17117. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17118. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17119. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17120. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17121. SSL *ssl = SSL_new(ctx);
  17122. SSL_set_fd(ssl, static_cast<int>(cli));
  17123. if (SSL_accept(ssl) > 0) {
  17124. // Read the request headers. Reading here also flushes the TLS 1.3
  17125. // session tickets to the client. Deliberately do NOT send
  17126. // `100 Continue`.
  17127. std::string buf;
  17128. char tmp[1024];
  17129. while (buf.find("\r\n\r\n") == std::string::npos) {
  17130. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17131. if (n <= 0) { break; }
  17132. buf.append(tmp, static_cast<size_t>(n));
  17133. }
  17134. // A correct client sends the body now; count what arrives.
  17135. auto pos = buf.find("\r\n\r\n");
  17136. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17137. while (body < 4096) {
  17138. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17139. if (n <= 0) { break; }
  17140. body += static_cast<size_t>(n);
  17141. }
  17142. server_body_bytes = body;
  17143. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17144. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17145. SSL_shutdown(ssl);
  17146. }
  17147. SSL_free(ssl);
  17148. detail::close_socket(cli);
  17149. SSL_CTX_free(ctx);
  17150. });
  17151. auto se = detail::scope_exit([&] {
  17152. server_thread.join();
  17153. detail::close_socket(srv);
  17154. });
  17155. SSLClient cli("127.0.0.1", port);
  17156. cli.enable_server_certificate_verification(false);
  17157. cli.set_connection_timeout(5, 0);
  17158. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17159. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17160. std::string body(4096, 'A');
  17161. auto res = cli.Put("/api/test", body, "application/json");
  17162. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17163. EXPECT_EQ(StatusCode::OK_200, res->status);
  17164. EXPECT_EQ(body.size(), server_body_bytes.load());
  17165. }
  17166. #endif
  17167. template <typename S, typename C>
  17168. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17169. svr.Get("/stream", [&](const Request &, Response &res) {
  17170. auto data = new std::string("01234567890123456789");
  17171. res.set_content_provider(
  17172. data->size(), "text/plain",
  17173. [&, data](size_t offset, size_t length, DataSink &sink) {
  17174. const size_t DATA_CHUNK_SIZE = 4;
  17175. const auto &d = *data;
  17176. std::this_thread::sleep_for(std::chrono::seconds(1));
  17177. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17178. return true;
  17179. },
  17180. [data](bool success) {
  17181. EXPECT_FALSE(success);
  17182. delete data;
  17183. });
  17184. });
  17185. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17186. auto i = new size_t(0);
  17187. res.set_content_provider(
  17188. "text/plain",
  17189. [i](size_t, DataSink &sink) {
  17190. if (*i < 5) {
  17191. std::this_thread::sleep_for(std::chrono::seconds(1));
  17192. sink.write("abcd", 4);
  17193. (*i)++;
  17194. } else {
  17195. sink.done();
  17196. }
  17197. return true;
  17198. },
  17199. [i](bool success) {
  17200. EXPECT_FALSE(success);
  17201. delete i;
  17202. });
  17203. });
  17204. svr.Get("/chunked", [&](const Request &, Response &res) {
  17205. auto i = new size_t(0);
  17206. res.set_chunked_content_provider(
  17207. "text/plain",
  17208. [i](size_t, DataSink &sink) {
  17209. if (*i < 5) {
  17210. std::this_thread::sleep_for(std::chrono::seconds(1));
  17211. sink.os << "abcd";
  17212. (*i)++;
  17213. } else {
  17214. sink.done();
  17215. }
  17216. return true;
  17217. },
  17218. [i](bool success) {
  17219. EXPECT_FALSE(success);
  17220. delete i;
  17221. });
  17222. });
  17223. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17224. auto se = detail::scope_exit([&] {
  17225. svr.stop();
  17226. listen_thread.join();
  17227. ASSERT_FALSE(svr.is_running());
  17228. });
  17229. svr.wait_until_ready();
  17230. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17231. {
  17232. auto start = std::chrono::steady_clock::now();
  17233. auto res = cli.Get("/stream");
  17234. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17235. std::chrono::steady_clock::now() - start)
  17236. .count();
  17237. ASSERT_FALSE(res);
  17238. EXPECT_EQ(Error::Read, res.error());
  17239. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17240. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17241. }
  17242. {
  17243. auto start = std::chrono::steady_clock::now();
  17244. auto res = cli.Get("/stream_without_length");
  17245. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17246. std::chrono::steady_clock::now() - start)
  17247. .count();
  17248. ASSERT_FALSE(res);
  17249. EXPECT_EQ(Error::Read, res.error());
  17250. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17251. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17252. }
  17253. {
  17254. auto start = std::chrono::steady_clock::now();
  17255. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17256. EXPECT_EQ("abcd", string(data, data_length));
  17257. return true;
  17258. });
  17259. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17260. std::chrono::steady_clock::now() - start)
  17261. .count();
  17262. ASSERT_FALSE(res);
  17263. EXPECT_EQ(Error::Read, res.error());
  17264. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17265. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17266. }
  17267. }
  17268. TEST(MaxTimeoutTest, ContentStream) {
  17269. time_t timeout = 2000;
  17270. time_t threshold = 200;
  17271. Server svr;
  17272. Client cli("localhost", PORT);
  17273. max_timeout_test(svr, cli, timeout, threshold);
  17274. }
  17275. #ifdef CPPHTTPLIB_SSL_ENABLED
  17276. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17277. time_t timeout = 2000;
  17278. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17279. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17280. SSLClient cli("localhost", PORT);
  17281. cli.enable_server_certificate_verification(false);
  17282. max_timeout_test(svr, cli, timeout, threshold);
  17283. }
  17284. #endif
  17285. class EventDispatcher {
  17286. public:
  17287. EventDispatcher() {}
  17288. bool wait_event(DataSink *sink) {
  17289. unique_lock<mutex> lk(m_);
  17290. int id = id_;
  17291. // Wait with timeout to prevent hanging if client disconnects
  17292. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17293. [&] { return cid_ == id; })) {
  17294. return false; // Timeout occurred
  17295. }
  17296. sink->write(message_.data(), message_.size());
  17297. return true;
  17298. }
  17299. void send_event(const string &message) {
  17300. lock_guard<mutex> lk(m_);
  17301. cid_ = id_++;
  17302. message_ = message;
  17303. cv_.notify_all();
  17304. }
  17305. private:
  17306. mutex m_;
  17307. condition_variable cv_;
  17308. atomic_int id_{0};
  17309. atomic_int cid_{-1};
  17310. string message_;
  17311. };
  17312. TEST(ClientInThreadTest, Issue2068) {
  17313. EventDispatcher ed;
  17314. Server svr;
  17315. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17316. res.set_chunked_content_provider("text/event-stream",
  17317. [&](size_t /*offset*/, DataSink &sink) {
  17318. return ed.wait_event(&sink);
  17319. });
  17320. });
  17321. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17322. svr.wait_until_ready();
  17323. thread event_thread([&] {
  17324. int id = 0;
  17325. while (svr.is_running()) {
  17326. this_thread::sleep_for(chrono::milliseconds(500));
  17327. std::stringstream ss;
  17328. ss << "data: " << id << "\n\n";
  17329. ed.send_event(ss.str());
  17330. id++;
  17331. }
  17332. });
  17333. auto se = detail::scope_exit([&] {
  17334. svr.stop();
  17335. listen_thread.join();
  17336. event_thread.join();
  17337. ASSERT_FALSE(svr.is_running());
  17338. });
  17339. {
  17340. auto client = detail::make_unique<Client>(HOST, PORT);
  17341. client->set_read_timeout(std::chrono::minutes(10));
  17342. std::atomic<bool> stop{false};
  17343. std::thread t([&] {
  17344. client->Get("/event1",
  17345. [&](const char *, size_t) -> bool { return !stop; });
  17346. });
  17347. std::this_thread::sleep_for(std::chrono::seconds(2));
  17348. stop = true;
  17349. client->stop();
  17350. t.join();
  17351. // Reset client after thread has finished
  17352. client.reset();
  17353. }
  17354. }
  17355. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17356. auto handled = false;
  17357. Server svr;
  17358. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17359. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17360. auto se = detail::scope_exit([&] {
  17361. svr.stop();
  17362. t.join();
  17363. ASSERT_FALSE(svr.is_running());
  17364. ASSERT_FALSE(handled);
  17365. });
  17366. svr.wait_until_ready();
  17367. // Two Content-Length headers with different values — must be rejected
  17368. auto req = "POST /test HTTP/1.1\r\n"
  17369. "Content-Length: 5\r\n"
  17370. "Content-Length: 10\r\n"
  17371. "\r\n"
  17372. "hello";
  17373. std::string response;
  17374. ASSERT_TRUE(send_request(1, req, &response));
  17375. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17376. response.substr(0, response.find("\r\n")));
  17377. }
  17378. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17379. auto handled = false;
  17380. Server svr;
  17381. svr.Post("/test", [&](const Request &, Response &res) {
  17382. handled = true;
  17383. res.set_content("ok", "text/plain");
  17384. });
  17385. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17386. auto se = detail::scope_exit([&] {
  17387. svr.stop();
  17388. t.join();
  17389. ASSERT_FALSE(svr.is_running());
  17390. ASSERT_TRUE(handled);
  17391. });
  17392. svr.wait_until_ready();
  17393. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17394. auto req = "POST /test HTTP/1.1\r\n"
  17395. "Host: localhost\r\n"
  17396. "Content-Length: 5\r\n"
  17397. "Content-Length: 5\r\n"
  17398. "\r\n"
  17399. "hello";
  17400. std::string response;
  17401. ASSERT_TRUE(send_request(1, req, &response));
  17402. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17403. }
  17404. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17405. Server svr;
  17406. svr.Get("/test", [](const Request &, Response &res) {
  17407. res.set_content("ok", "text/plain");
  17408. });
  17409. auto port = svr.bind_to_any_port(HOST);
  17410. thread t = thread([&] { svr.listen_after_bind(); });
  17411. auto se = detail::scope_exit([&] {
  17412. svr.stop();
  17413. t.join();
  17414. ASSERT_FALSE(svr.is_running());
  17415. });
  17416. svr.wait_until_ready();
  17417. auto status_line = [&](const std::string &host_lines) {
  17418. std::string res;
  17419. send_request(
  17420. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17421. &res, port);
  17422. return res.substr(0, res.find("\r\n"));
  17423. };
  17424. const char *accepted[] = {
  17425. "Host: localhost\r\n",
  17426. "Host: a.example:8080\r\n",
  17427. "Host: my_service\r\n",
  17428. "Host: [::1]:8080\r\n",
  17429. "Host: [fe80::1%25eth0]\r\n",
  17430. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17431. };
  17432. for (auto host_lines : accepted) {
  17433. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17434. }
  17435. const char *rejected[] = {
  17436. "Host: a.example\r\nHost: b.example\r\n",
  17437. "Host: a.example\r\nHost: a.example\r\n",
  17438. "Host: a@b.example\r\n",
  17439. "Host: a.example/b\r\n",
  17440. "Host: a.example\\b\r\n",
  17441. "Host: a.example?b\r\n",
  17442. "Host: a.example#b\r\n",
  17443. "Host: a.example b.example\r\n",
  17444. };
  17445. for (auto host_lines : rejected) {
  17446. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17447. << host_lines;
  17448. }
  17449. }
  17450. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17451. Server svr;
  17452. svr.Get("/", [](const Request &req, Response &res) {
  17453. EXPECT_EQ(2U, req.trailers.size());
  17454. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17455. // Denied
  17456. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17457. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17458. // Accepted
  17459. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17460. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17461. EXPECT_TRUE(req.has_trailer("X-World"));
  17462. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17463. res.set_content("ok", "text/plain");
  17464. });
  17465. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17466. auto se = detail::scope_exit([&] {
  17467. svr.stop();
  17468. t.join();
  17469. ASSERT_FALSE(svr.is_running());
  17470. });
  17471. svr.wait_until_ready();
  17472. const std::string req = "GET / HTTP/1.1\r\n"
  17473. "Transfer-Encoding: chunked\r\n"
  17474. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17475. "\r\n"
  17476. "0\r\n"
  17477. "Content-Length: 10\r\n"
  17478. "Host: internal.local\r\n"
  17479. "Content-Type: malicious/content\r\n"
  17480. "Cookie: any\r\n"
  17481. "Set-Cookie: any\r\n"
  17482. "X-Forwarded-For: attacker.com\r\n"
  17483. "X-Real-Ip: 1.1.1.1\r\n"
  17484. "X-Hello: hello\r\n"
  17485. "X-World: world\r\n"
  17486. "\r\n";
  17487. std::string res;
  17488. ASSERT_TRUE(send_request(1, req, &res));
  17489. }
  17490. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17491. // several field lines, and the combined value is what has to be parsed. A
  17492. // Trailer field split across lines therefore declares every name it lists;
  17493. // reading only the first line silently drops the trailers the later lines
  17494. // declare. The prohibited-trailer filter still applies to every line.
  17495. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17496. Server svr;
  17497. size_t observed_trailer_count = 0;
  17498. std::string observed_hello;
  17499. std::string observed_world;
  17500. bool observed_content_length = true;
  17501. svr.Get("/", [&](const Request &req, Response &res) {
  17502. observed_trailer_count = req.trailers.size();
  17503. observed_hello = req.get_trailer_value("X-Hello");
  17504. observed_world = req.get_trailer_value("X-World");
  17505. observed_content_length = req.has_trailer("Content-Length");
  17506. res.set_content("ok", "text/plain");
  17507. });
  17508. auto port = svr.bind_to_any_port(HOST);
  17509. thread t = thread([&]() { svr.listen_after_bind(); });
  17510. auto se = detail::scope_exit([&] {
  17511. svr.stop();
  17512. t.join();
  17513. ASSERT_FALSE(svr.is_running());
  17514. });
  17515. svr.wait_until_ready();
  17516. const std::string req = "GET / HTTP/1.1\r\n"
  17517. "Host: localhost\r\n"
  17518. "Transfer-Encoding: chunked\r\n"
  17519. "Trailer: X-Hello\r\n"
  17520. "Trailer: X-World, Content-Length\r\n"
  17521. "\r\n"
  17522. "0\r\n"
  17523. "X-Hello: hello\r\n"
  17524. "X-World: world\r\n"
  17525. "Content-Length: 10\r\n"
  17526. "\r\n";
  17527. std::string res;
  17528. ASSERT_TRUE(send_request(1, req, &res, port));
  17529. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17530. // Accepted: both field lines contribute to the declared set
  17531. EXPECT_EQ(2U, observed_trailer_count);
  17532. EXPECT_EQ(observed_hello, "hello");
  17533. EXPECT_EQ(observed_world, "world");
  17534. // Denied: a prohibited name stays prohibited on a later field line
  17535. EXPECT_FALSE(observed_content_length);
  17536. }
  17537. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17538. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17539. // unbounded run of fields that are never declared, because the counter would
  17540. // only advance for declared fields.
  17541. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17542. Server svr;
  17543. bool handler_called = false;
  17544. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17545. handler_called = true;
  17546. res.set_content("ok", "text/plain");
  17547. });
  17548. auto port = svr.bind_to_any_port(HOST);
  17549. thread t = thread([&]() { svr.listen_after_bind(); });
  17550. auto se = detail::scope_exit([&] {
  17551. svr.stop();
  17552. t.join();
  17553. ASSERT_FALSE(svr.is_running());
  17554. });
  17555. svr.wait_until_ready();
  17556. // Declare nothing, then send far more undeclared trailer fields than the
  17557. // header-count limit. Parsing must stop and reject the request rather than
  17558. // read every line.
  17559. std::string req = "GET / HTTP/1.1\r\n"
  17560. "Transfer-Encoding: chunked\r\n"
  17561. "\r\n"
  17562. "0\r\n";
  17563. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17564. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17565. }
  17566. req += "\r\n";
  17567. std::string res;
  17568. ASSERT_TRUE(send_request(1, req, &res, port));
  17569. // The request is rejected before the handler runs.
  17570. EXPECT_FALSE(handler_called);
  17571. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17572. }
  17573. // The set of declared trailer names is capped so a peer cannot grow it without
  17574. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17575. // declared past the cap is not honored, even if the field is actually sent.
  17576. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17577. Server svr;
  17578. // One name inside the cap and one past it, so the test tracks the cap rather
  17579. // than a fixed count.
  17580. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17581. const std::string within_cap_name = "X-T-0";
  17582. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17583. bool observed_within_cap = false;
  17584. bool observed_past_cap = false;
  17585. svr.Get("/", [&](const Request &req, Response &res) {
  17586. observed_within_cap = req.has_trailer(within_cap_name);
  17587. observed_past_cap = req.has_trailer(past_cap_name);
  17588. res.set_content("ok", "text/plain");
  17589. });
  17590. auto port = svr.bind_to_any_port(HOST);
  17591. thread t = thread([&]() { svr.listen_after_bind(); });
  17592. auto se = detail::scope_exit([&] {
  17593. svr.stop();
  17594. t.join();
  17595. ASSERT_FALSE(svr.is_running());
  17596. });
  17597. svr.wait_until_ready();
  17598. // Declare more trailer names than the cap in a single Trailer field, then
  17599. // actually send the first (within the cap) and the last (past it).
  17600. std::string trailer_decl = "Trailer: ";
  17601. for (int i = 0; i < declared_count; i++) {
  17602. if (i != 0) { trailer_decl += ", "; }
  17603. trailer_decl += "X-T-" + std::to_string(i);
  17604. }
  17605. trailer_decl += "\r\n";
  17606. const std::string req = "GET / HTTP/1.1\r\n"
  17607. "Host: localhost\r\n"
  17608. "Transfer-Encoding: chunked\r\n" +
  17609. trailer_decl +
  17610. "\r\n"
  17611. "0\r\n" +
  17612. within_cap_name + ": a\r\n" + past_cap_name +
  17613. ": b\r\n"
  17614. "\r\n";
  17615. std::string res;
  17616. ASSERT_TRUE(send_request(1, req, &res, port));
  17617. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17618. // A name within the cap is honored; one declared past the cap is dropped.
  17619. EXPECT_TRUE(observed_within_cap);
  17620. EXPECT_FALSE(observed_past_cap);
  17621. }
  17622. // A direct client that is not listed in trusted_proxies must not be able to
  17623. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17624. // the peer address on the actual TCP connection determines whether the
  17625. // header is honored.
  17626. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17627. Server svr;
  17628. // Deliberately does NOT include the loopback address the test client
  17629. // actually connects from, so the direct connection is not a trusted proxy.
  17630. svr.set_trusted_proxies({"203.0.113.66"});
  17631. std::string observed_remote_addr;
  17632. svr.Get("/ip", [&](const Request &req, Response &res) {
  17633. observed_remote_addr = req.remote_addr;
  17634. res.set_content("ok", "text/plain");
  17635. });
  17636. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17637. auto se = detail::scope_exit([&] {
  17638. svr.stop();
  17639. t.join();
  17640. ASSERT_FALSE(svr.is_running());
  17641. });
  17642. svr.wait_until_ready();
  17643. Client cli(HOST, PORT);
  17644. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17646. EXPECT_EQ(StatusCode::OK_200, res->status);
  17647. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17648. // ignored entirely and the real connection-level address retained.
  17649. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17650. observed_remote_addr == "127.0.0.1");
  17651. }
  17652. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17653. Server svr;
  17654. std::string observed_remote_addr;
  17655. std::string observed_xff;
  17656. svr.Get("/ip", [&](const Request &req, Response &res) {
  17657. observed_remote_addr = req.remote_addr;
  17658. observed_xff = req.get_header_value("X-Forwarded-For");
  17659. res.set_content("ok", "text/plain");
  17660. });
  17661. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17662. auto se = detail::scope_exit([&] {
  17663. svr.stop();
  17664. t.join();
  17665. ASSERT_FALSE(svr.is_running());
  17666. });
  17667. svr.wait_until_ready();
  17668. Client cli(HOST, PORT);
  17669. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17671. EXPECT_EQ(StatusCode::OK_200, res->status);
  17672. EXPECT_EQ(observed_xff, "203.0.113.66");
  17673. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17674. observed_remote_addr == "127.0.0.1");
  17675. }
  17676. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17677. Server svr;
  17678. svr.set_trusted_proxies({"203.0.113.66"});
  17679. std::string observed_remote_addr;
  17680. std::string observed_xff;
  17681. svr.Get("/ip", [&](const Request &req, Response &res) {
  17682. observed_remote_addr = req.remote_addr;
  17683. observed_xff = req.get_header_value("X-Forwarded-For");
  17684. res.set_content("ok", "text/plain");
  17685. });
  17686. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17687. auto se = detail::scope_exit([&] {
  17688. svr.stop();
  17689. t.join();
  17690. ASSERT_FALSE(svr.is_running());
  17691. });
  17692. svr.wait_until_ready();
  17693. Client cli(HOST, PORT);
  17694. auto res = cli.Get("/ip");
  17695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17696. EXPECT_EQ(StatusCode::OK_200, res->status);
  17697. EXPECT_EQ(observed_xff, "");
  17698. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17699. observed_remote_addr == "127.0.0.1");
  17700. }
  17701. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17702. Server svr;
  17703. // Include the loopback address the test client actually connects from, so
  17704. // the direct connection itself is recognized as the trusted proxy hop.
  17705. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17706. std::string observed_remote_addr;
  17707. std::string observed_xff;
  17708. svr.Get("/ip", [&](const Request &req, Response &res) {
  17709. observed_remote_addr = req.remote_addr;
  17710. observed_xff = req.get_header_value("X-Forwarded-For");
  17711. res.set_content("ok", "text/plain");
  17712. });
  17713. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17714. auto se = detail::scope_exit([&] {
  17715. svr.stop();
  17716. t.join();
  17717. ASSERT_FALSE(svr.is_running());
  17718. });
  17719. svr.wait_until_ready();
  17720. Client cli(HOST, PORT);
  17721. auto res = cli.Get(
  17722. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17724. EXPECT_EQ(StatusCode::OK_200, res->status);
  17725. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17726. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17727. }
  17728. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17729. Server svr;
  17730. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17731. std::string observed_remote_addr;
  17732. std::string observed_xff;
  17733. svr.Get("/ip", [&](const Request &req, Response &res) {
  17734. observed_remote_addr = req.remote_addr;
  17735. observed_xff = req.get_header_value("X-Forwarded-For");
  17736. res.set_content("ok", "text/plain");
  17737. });
  17738. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17739. auto se = detail::scope_exit([&] {
  17740. svr.stop();
  17741. t.join();
  17742. ASSERT_FALSE(svr.is_running());
  17743. });
  17744. svr.wait_until_ready();
  17745. Client cli(HOST, PORT);
  17746. auto res = cli.Get(
  17747. "/ip",
  17748. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17750. EXPECT_EQ(StatusCode::OK_200, res->status);
  17751. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17752. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17753. }
  17754. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17755. Server svr;
  17756. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17757. std::string observed_remote_addr;
  17758. std::string observed_xff;
  17759. svr.Get("/ip", [&](const Request &req, Response &res) {
  17760. observed_remote_addr = req.remote_addr;
  17761. observed_xff = req.get_header_value("X-Forwarded-For");
  17762. res.set_content("ok", "text/plain");
  17763. });
  17764. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17765. auto se = detail::scope_exit([&] {
  17766. svr.stop();
  17767. t.join();
  17768. ASSERT_FALSE(svr.is_running());
  17769. });
  17770. svr.wait_until_ready();
  17771. Client cli(HOST, PORT);
  17772. auto res = cli.Get(
  17773. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17775. EXPECT_EQ(StatusCode::OK_200, res->status);
  17776. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17777. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17778. // and must not be selected.
  17779. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17780. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17781. }
  17782. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17783. Server svr;
  17784. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17785. std::string observed_remote_addr;
  17786. svr.Get("/ip", [&](const Request &req, Response &res) {
  17787. observed_remote_addr = req.remote_addr;
  17788. res.set_content("ok", "text/plain");
  17789. });
  17790. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17791. auto se = detail::scope_exit([&] {
  17792. svr.stop();
  17793. t.join();
  17794. ASSERT_FALSE(svr.is_running());
  17795. });
  17796. svr.wait_until_ready();
  17797. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17798. // a forged address and the trusted proxy's own address; the forged value must
  17799. // not win over the address the trusted proxy actually recorded.
  17800. Client cli(HOST, PORT);
  17801. auto res = cli.Get(
  17802. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17804. EXPECT_EQ(StatusCode::OK_200, res->status);
  17805. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17806. }
  17807. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17808. Server svr;
  17809. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17810. std::string observed_remote_addr;
  17811. std::string observed_xff;
  17812. svr.Get("/ip", [&](const Request &req, Response &res) {
  17813. observed_remote_addr = req.remote_addr;
  17814. observed_xff = req.get_header_value("X-Forwarded-For");
  17815. res.set_content("ok", "text/plain");
  17816. });
  17817. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17818. auto se = detail::scope_exit([&] {
  17819. svr.stop();
  17820. t.join();
  17821. ASSERT_FALSE(svr.is_running());
  17822. });
  17823. svr.wait_until_ready();
  17824. Client cli(HOST, PORT);
  17825. auto res = cli.Get(
  17826. "/ip",
  17827. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17829. EXPECT_EQ(StatusCode::OK_200, res->status);
  17830. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17831. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17832. }
  17833. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17834. Server svr;
  17835. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17836. std::string observed_remote_addr;
  17837. std::string observed_xff;
  17838. svr.Get("/ip", [&](const Request &req, Response &res) {
  17839. observed_remote_addr = req.remote_addr;
  17840. observed_xff = req.get_header_value("X-Forwarded-For");
  17841. res.set_content("ok", "text/plain");
  17842. });
  17843. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17844. auto se = detail::scope_exit([&] {
  17845. svr.stop();
  17846. t.join();
  17847. ASSERT_FALSE(svr.is_running());
  17848. });
  17849. svr.wait_until_ready();
  17850. std::string raw_req =
  17851. "GET /ip HTTP/1.1\r\n"
  17852. "Host: localhost\r\n"
  17853. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17854. "Connection: close\r\n"
  17855. "\r\n";
  17856. std::string out;
  17857. ASSERT_TRUE(send_request(5, raw_req, &out));
  17858. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17859. // Header parser trims surrounding whitespace of the header value
  17860. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17861. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17862. }
  17863. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17864. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17865. // their own X-Forwarded-For as a separate field line rather than extending the
  17866. // one the client sent, so every occurrence has to be taken into account.
  17867. // Reading only the first one hands back the address the client chose.
  17868. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17869. Server svr;
  17870. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17871. std::string observed_remote_addr;
  17872. size_t observed_xff_count = 0;
  17873. svr.Get("/ip", [&](const Request &req, Response &res) {
  17874. observed_remote_addr = req.remote_addr;
  17875. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17876. res.set_content("ok", "text/plain");
  17877. });
  17878. auto port = svr.bind_to_any_port(HOST);
  17879. thread t = thread([&]() { svr.listen_after_bind(); });
  17880. auto se = detail::scope_exit([&] {
  17881. svr.stop();
  17882. t.join();
  17883. ASSERT_FALSE(svr.is_running());
  17884. });
  17885. svr.wait_until_ready();
  17886. // The client supplies the first field line; the trusted proxy appends the
  17887. // address it observed as a second one.
  17888. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17889. "Host: localhost\r\n"
  17890. "X-Forwarded-For: 1.2.3.4\r\n"
  17891. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17892. "Connection: close\r\n"
  17893. "\r\n";
  17894. std::string out;
  17895. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17896. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17897. EXPECT_EQ(observed_xff_count, 2U);
  17898. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17899. // The same chain spread over one field line per hop derives the same client
  17900. // address, i.e. the split and the comma-joined representations agree.
  17901. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17902. "Host: localhost\r\n"
  17903. "X-Forwarded-For: 1.2.3.4\r\n"
  17904. "X-Forwarded-For: 198.51.100.23\r\n"
  17905. "X-Forwarded-For: 192.0.2.45\r\n"
  17906. "Connection: close\r\n"
  17907. "\r\n";
  17908. out.clear();
  17909. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17910. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17911. EXPECT_EQ(observed_xff_count, 3U);
  17912. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17913. }
  17914. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17915. // crash the server (it used to call front() on an empty vector inside
  17916. // get_client_ip). The connection-level remote address must be retained instead.
  17917. static void run_malformed_xff_test(const std::string &xff_value) {
  17918. Server svr;
  17919. svr.set_trusted_proxies({"192.0.2.45"});
  17920. std::string observed_remote_addr;
  17921. svr.Get("/ip", [&](const Request &req, Response &res) {
  17922. observed_remote_addr = req.remote_addr;
  17923. res.set_content("ok", "text/plain");
  17924. });
  17925. int port = 0;
  17926. thread t = thread([&]() {
  17927. port = svr.bind_to_any_port(HOST);
  17928. svr.listen_after_bind();
  17929. });
  17930. auto se = detail::scope_exit([&] {
  17931. svr.stop();
  17932. t.join();
  17933. ASSERT_FALSE(svr.is_running());
  17934. });
  17935. svr.wait_until_ready();
  17936. Client cli(HOST, port);
  17937. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17939. EXPECT_EQ(StatusCode::OK_200, res->status);
  17940. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17941. observed_remote_addr == "127.0.0.1");
  17942. }
  17943. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17944. run_malformed_xff_test("");
  17945. }
  17946. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17947. run_malformed_xff_test(",");
  17948. }
  17949. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17950. run_malformed_xff_test(", , ,");
  17951. }
  17952. // The same rule applies to Accept: a request whose acceptable types are spread
  17953. // over several field lines must be negotiated against all of them.
  17954. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17955. // case-insensitive connection options. Comparing the whole field value against
  17956. // one option misses a client that sends several of them, and misses every
  17957. // casing but the one written in the comparison.
  17958. //
  17959. // Sends req, reads the response, then reuses the same socket for a second
  17960. // request to find out whether the server kept the connection.
  17961. static void probe_connection_reuse(int port, const std::string &req,
  17962. bool *announced_close, bool *reusable) {
  17963. auto error = Error::Success;
  17964. auto sock = detail::create_client_socket(
  17965. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17966. /*connection_timeout_sec=*/5, 0,
  17967. /*read_timeout_sec=*/1, 0,
  17968. /*write_timeout_sec=*/5, 0, std::string(), error);
  17969. ASSERT_NE(sock, INVALID_SOCKET);
  17970. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17971. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17972. "Host: localhost\r\n"
  17973. "Connection: close\r\n"
  17974. "\r\n";
  17975. std::string first_response;
  17976. std::string second_response;
  17977. detail::process_client_socket(
  17978. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17979. [&](Stream &strm) {
  17980. if (strm.write(req.data(), req.size()) !=
  17981. static_cast<ssize_t>(req.size())) {
  17982. return false;
  17983. }
  17984. char buf[512];
  17985. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17986. // Headers plus the two-byte body of the handler below
  17987. while (reader.getline()) {
  17988. first_response += reader.ptr();
  17989. if (first_response.find("ok") != std::string::npos) { break; }
  17990. }
  17991. if (strm.write(second.data(), second.size()) !=
  17992. static_cast<ssize_t>(second.size())) {
  17993. return true;
  17994. }
  17995. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17996. while (reader2.getline()) {
  17997. second_response += reader2.ptr();
  17998. if (second_response.find("ok") != std::string::npos) { break; }
  17999. }
  18000. return true;
  18001. });
  18002. *announced_close =
  18003. first_response.find("Connection: close") != std::string::npos;
  18004. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18005. }
  18006. class ConnectionTokenTest : public ::testing::Test {
  18007. protected:
  18008. void SetUp() override {
  18009. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18010. res.set_content("ok", "text/plain");
  18011. });
  18012. port_ = svr_.bind_to_any_port(HOST);
  18013. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18014. svr_.wait_until_ready();
  18015. }
  18016. void TearDown() override {
  18017. svr_.stop();
  18018. if (thread_.joinable()) { thread_.join(); }
  18019. }
  18020. Server svr_;
  18021. int port_ = 0;
  18022. thread thread_;
  18023. };
  18024. // "close" alongside another option still closes the connection, and the
  18025. // response says so rather than leaving the peer to discover it.
  18026. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18027. bool announced_close = false;
  18028. bool reusable = true;
  18029. probe_connection_reuse(port_,
  18030. "GET /keepalive HTTP/1.1\r\n"
  18031. "Host: localhost\r\n"
  18032. "Connection: keep-alive, close\r\n"
  18033. "\r\n",
  18034. &announced_close, &reusable);
  18035. EXPECT_TRUE(announced_close);
  18036. EXPECT_FALSE(reusable);
  18037. }
  18038. // "close" split over two field lines is the same list, so it is honored too.
  18039. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18040. bool announced_close = false;
  18041. bool reusable = true;
  18042. probe_connection_reuse(port_,
  18043. "GET /keepalive HTTP/1.1\r\n"
  18044. "Host: localhost\r\n"
  18045. "Connection: keep-alive\r\n"
  18046. "Connection: close\r\n"
  18047. "\r\n",
  18048. &announced_close, &reusable);
  18049. EXPECT_TRUE(announced_close);
  18050. EXPECT_FALSE(reusable);
  18051. }
  18052. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18053. // keep-alive in the spelling everyone actually sends keeps its connection.
  18054. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18055. bool announced_close = false;
  18056. bool reusable = false;
  18057. probe_connection_reuse(port_,
  18058. "GET /keepalive HTTP/1.0\r\n"
  18059. "Host: localhost\r\n"
  18060. "Connection: keep-alive\r\n"
  18061. "\r\n",
  18062. &announced_close, &reusable);
  18063. EXPECT_FALSE(announced_close);
  18064. EXPECT_TRUE(reusable);
  18065. }
  18066. // A token the value merely contains is not the token itself.
  18067. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18068. bool announced_close = false;
  18069. bool reusable = false;
  18070. probe_connection_reuse(port_,
  18071. "GET /keepalive HTTP/1.1\r\n"
  18072. "Host: localhost\r\n"
  18073. "Connection: notclose\r\n"
  18074. "\r\n",
  18075. &announced_close, &reusable);
  18076. EXPECT_FALSE(announced_close);
  18077. EXPECT_TRUE(reusable);
  18078. }
  18079. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18080. Server svr;
  18081. std::vector<std::string> observed_types;
  18082. svr.Get("/", [&](const Request &req, Response &res) {
  18083. observed_types = req.accept_content_types;
  18084. res.set_content("ok", "text/plain");
  18085. });
  18086. auto port = svr.bind_to_any_port(HOST);
  18087. thread t = thread([&]() { svr.listen_after_bind(); });
  18088. auto se = detail::scope_exit([&] {
  18089. svr.stop();
  18090. t.join();
  18091. ASSERT_FALSE(svr.is_running());
  18092. });
  18093. svr.wait_until_ready();
  18094. Client cli(HOST, port);
  18095. Headers headers;
  18096. headers.emplace("Accept", "text/plain;q=0.5");
  18097. headers.emplace("Accept", "application/json");
  18098. auto res = cli.Get("/", headers);
  18099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18100. EXPECT_EQ(StatusCode::OK_200, res->status);
  18101. // Sorted by q-value, so the second field line's type comes first
  18102. ASSERT_EQ(2U, observed_types.size());
  18103. EXPECT_EQ("application/json", observed_types[0]);
  18104. EXPECT_EQ("text/plain", observed_types[1]);
  18105. }
  18106. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18107. // empty field line must not contribute a bare comma to the combined value.
  18108. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18109. Server svr;
  18110. std::vector<std::string> observed_types;
  18111. svr.Get("/", [&](const Request &req, Response &res) {
  18112. observed_types = req.accept_content_types;
  18113. res.set_content("ok", "text/plain");
  18114. });
  18115. auto port = svr.bind_to_any_port(HOST);
  18116. thread t = thread([&]() { svr.listen_after_bind(); });
  18117. auto se = detail::scope_exit([&] {
  18118. svr.stop();
  18119. t.join();
  18120. ASSERT_FALSE(svr.is_running());
  18121. });
  18122. svr.wait_until_ready();
  18123. // Empty first field line, then a real one
  18124. std::string raw_req = "GET / HTTP/1.1\r\n"
  18125. "Host: localhost\r\n"
  18126. "Accept:\r\n"
  18127. "Accept: application/json\r\n"
  18128. "Connection: close\r\n"
  18129. "\r\n";
  18130. std::string out;
  18131. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18132. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18133. ASSERT_EQ(1U, observed_types.size());
  18134. EXPECT_EQ("application/json", observed_types[0]);
  18135. }
  18136. // The skip in get_combined_header_value() is what keeps an empty field line
  18137. // from contributing a bare comma. Only a trailing empty field line exercises
  18138. // it: a leading one is already covered by the "combined is still empty" check,
  18139. // and parse_accept_header() now ignores the empty element either way, so the
  18140. // request-level test above can no longer tell the two apart.
  18141. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18142. Headers headers;
  18143. headers.emplace("Accept", "text/html");
  18144. headers.emplace("Accept", "");
  18145. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18146. headers.clear();
  18147. headers.emplace("Accept", "");
  18148. headers.emplace("Accept", "application/json");
  18149. EXPECT_EQ("application/json",
  18150. detail::get_combined_header_value(headers, "Accept"));
  18151. }
  18152. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18153. // An encoding offered on a later Accept-Encoding field line is still offered.
  18154. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18155. Server svr;
  18156. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18157. res.set_content(std::string(1024, 'x'), "text/plain");
  18158. });
  18159. auto port = svr.bind_to_any_port(HOST);
  18160. thread t = thread([&]() { svr.listen_after_bind(); });
  18161. auto se = detail::scope_exit([&] {
  18162. svr.stop();
  18163. t.join();
  18164. ASSERT_FALSE(svr.is_running());
  18165. });
  18166. svr.wait_until_ready();
  18167. Client cli(HOST, port);
  18168. cli.set_decompress(false);
  18169. Headers headers;
  18170. headers.emplace("Accept-Encoding", "identity");
  18171. headers.emplace("Accept-Encoding", "gzip");
  18172. auto res = cli.Get("/", headers);
  18173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18174. EXPECT_EQ(StatusCode::OK_200, res->status);
  18175. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18176. }
  18177. #endif
  18178. #ifndef _WIN32
  18179. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18180. Server svr;
  18181. svr.Post("/post", [&](const Request &req, Response &res) {
  18182. res.set_content(req.body, "text/plain");
  18183. });
  18184. svr.Put("/put", [&](const Request &req, Response &res) {
  18185. res.set_content(req.body, "text/plain");
  18186. });
  18187. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18188. res.set_content(req.body, "text/plain");
  18189. });
  18190. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18191. res.set_content(req.body, "text/plain");
  18192. });
  18193. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18194. auto se = detail::scope_exit([&] {
  18195. svr.stop();
  18196. t.join();
  18197. ASSERT_FALSE(svr.is_running());
  18198. });
  18199. svr.wait_until_ready();
  18200. std::string resp;
  18201. // POST without Content-Length
  18202. ASSERT_TRUE(send_request(5,
  18203. "POST /post HTTP/1.1\r\n"
  18204. "Host: localhost\r\n"
  18205. "Connection: close\r\n"
  18206. "\r\n",
  18207. &resp));
  18208. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18209. // PUT without Content-Length
  18210. resp.clear();
  18211. ASSERT_TRUE(send_request(5,
  18212. "PUT /put HTTP/1.1\r\n"
  18213. "Host: localhost\r\n"
  18214. "Connection: close\r\n"
  18215. "\r\n",
  18216. &resp));
  18217. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18218. // PATCH without Content-Length
  18219. resp.clear();
  18220. ASSERT_TRUE(send_request(5,
  18221. "PATCH /patch HTTP/1.1\r\n"
  18222. "Host: localhost\r\n"
  18223. "Connection: close\r\n"
  18224. "\r\n",
  18225. &resp));
  18226. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18227. // DELETE without Content-Length
  18228. resp.clear();
  18229. ASSERT_TRUE(send_request(5,
  18230. "DELETE /delete HTTP/1.1\r\n"
  18231. "Host: localhost\r\n"
  18232. "Connection: close\r\n"
  18233. "\r\n",
  18234. &resp));
  18235. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18236. }
  18237. #endif
  18238. //==============================================================================
  18239. // open_stream() Tests
  18240. //==============================================================================
  18241. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18242. std::string result;
  18243. char buf[8192];
  18244. ssize_t n;
  18245. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18246. result.append(buf, static_cast<size_t>(n));
  18247. }
  18248. return result;
  18249. }
  18250. // Mock stream for unit tests
  18251. class MockStream : public Stream {
  18252. public:
  18253. std::string data;
  18254. size_t pos = 0;
  18255. ssize_t error_after = -1; // -1 = no error
  18256. explicit MockStream(const std::string &d, ssize_t err = -1)
  18257. : data(d), error_after(err) {}
  18258. bool is_readable() const override { return true; }
  18259. bool wait_readable() const override { return true; }
  18260. bool wait_writable() const override { return true; }
  18261. ssize_t read(char *ptr, size_t size) override {
  18262. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18263. if (pos >= data.size()) return 0;
  18264. size_t limit =
  18265. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18266. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18267. std::memcpy(ptr, data.data() + pos, to_read);
  18268. pos += to_read;
  18269. return static_cast<ssize_t>(to_read);
  18270. }
  18271. ssize_t write(const char *, size_t) override { return -1; }
  18272. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18273. ip = "127.0.0.1";
  18274. port = 0;
  18275. }
  18276. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18277. ip = "127.0.0.1";
  18278. port = 0;
  18279. }
  18280. socket_t socket() const override { return INVALID_SOCKET; }
  18281. time_t duration() const override { return 0; }
  18282. };
  18283. TEST(StreamHandleTest, Basic) {
  18284. ClientImpl::StreamHandle handle;
  18285. EXPECT_FALSE(handle.is_valid());
  18286. handle.response = detail::make_unique<Response>();
  18287. handle.error = Error::Connection;
  18288. EXPECT_FALSE(handle.is_valid());
  18289. handle.error = Error::Success;
  18290. EXPECT_TRUE(handle.is_valid());
  18291. }
  18292. TEST(BodyReaderTest, Basic) {
  18293. MockStream stream("Hello, World!");
  18294. detail::BodyReader reader;
  18295. reader.stream = &stream;
  18296. reader.content_length = 13;
  18297. char buf[32];
  18298. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18299. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18300. EXPECT_TRUE(reader.eof);
  18301. }
  18302. TEST(BodyReaderTest, NoStream) {
  18303. detail::BodyReader reader;
  18304. char buf[32];
  18305. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18306. EXPECT_EQ(Error::Connection, reader.last_error);
  18307. }
  18308. TEST(BodyReaderTest, Error) {
  18309. MockStream stream("Hello, World!", 5);
  18310. detail::BodyReader reader;
  18311. reader.stream = &stream;
  18312. reader.content_length = 13;
  18313. char buf[32];
  18314. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18315. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18316. EXPECT_EQ(Error::Read, reader.last_error);
  18317. }
  18318. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18319. // Mock-based StreamHandle tests relying on private internals are removed.
  18320. class OpenStreamTest : public ::testing::Test {
  18321. protected:
  18322. void SetUp() override {
  18323. svr_.Get("/hello", [](const Request &, Response &res) {
  18324. res.set_content("Hello World!", "text/plain");
  18325. });
  18326. svr_.Get("/large", [](const Request &, Response &res) {
  18327. res.set_content(std::string(10000, 'X'), "text/plain");
  18328. });
  18329. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18330. res.set_content("Hello World!", "image/jpeg");
  18331. res.set_header("Content-Encoding", "UTF-8");
  18332. });
  18333. svr_.Get("/chunked", [](const Request &, Response &res) {
  18334. res.set_chunked_content_provider("text/plain",
  18335. [](size_t offset, DataSink &sink) {
  18336. if (offset < 15) {
  18337. sink.write("chunk", 5);
  18338. return true;
  18339. }
  18340. sink.done();
  18341. return true;
  18342. });
  18343. });
  18344. svr_.Get("/compressible", [](const Request &, Response &res) {
  18345. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18346. DataSink &sink) {
  18347. if (offset < 100 * 1024) {
  18348. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18349. sink.write(chunk.data(), chunk.size());
  18350. return true;
  18351. }
  18352. sink.done();
  18353. return true;
  18354. });
  18355. });
  18356. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18357. [](const Request & /*req*/, Response &res) {
  18358. auto i = new int(0);
  18359. res.set_header("Trailer", "Content-Length, X-Allowed");
  18360. res.set_chunked_content_provider(
  18361. "text/plain",
  18362. [i](size_t /*offset*/, DataSink &sink) {
  18363. switch (*i) {
  18364. case 0: sink.os << "123"; break;
  18365. case 1: sink.os << "456"; break;
  18366. case 2: sink.os << "789"; break;
  18367. case 3: {
  18368. sink.done_with_trailer(
  18369. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18370. } break;
  18371. }
  18372. (*i)++;
  18373. return true;
  18374. },
  18375. [i](bool success) {
  18376. EXPECT_TRUE(success);
  18377. delete i;
  18378. });
  18379. });
  18380. // Echo headers endpoint for header-related tests
  18381. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18382. std::string body;
  18383. for (const auto &h : req.headers) {
  18384. body.append(h.first);
  18385. body.push_back(':');
  18386. body.append(h.second);
  18387. body.push_back('\n');
  18388. }
  18389. res.set_content(body, "text/plain");
  18390. });
  18391. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18392. std::string body;
  18393. for (const auto &h : req.headers) {
  18394. body.append(h.first);
  18395. body.push_back(':');
  18396. body.append(h.second);
  18397. body.push_back('\n');
  18398. }
  18399. res.set_content(body, "text/plain");
  18400. });
  18401. port_ = svr_.bind_to_any_port("127.0.0.1");
  18402. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18403. svr_.wait_until_ready();
  18404. }
  18405. void TearDown() override {
  18406. svr_.stop();
  18407. if (thread_.joinable()) thread_.join();
  18408. }
  18409. Server svr_;
  18410. std::thread thread_;
  18411. int port_ = 0;
  18412. };
  18413. TEST_F(OpenStreamTest, Basic) {
  18414. Client cli("127.0.0.1", port_);
  18415. auto handle = cli.open_stream("GET", "/hello");
  18416. EXPECT_TRUE(handle.is_valid());
  18417. EXPECT_EQ("Hello World!", read_all(handle));
  18418. }
  18419. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18420. Client cli("127.0.0.1", port_);
  18421. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18422. ASSERT_TRUE(handle.is_valid());
  18423. EXPECT_EQ("Hello World!", read_all(handle));
  18424. }
  18425. TEST_F(OpenStreamTest, SmallBuffer) {
  18426. Client cli("127.0.0.1", port_);
  18427. auto handle = cli.open_stream("GET", "/hello");
  18428. std::string result;
  18429. char buf[4];
  18430. ssize_t n;
  18431. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18432. result.append(buf, static_cast<size_t>(n));
  18433. EXPECT_EQ("Hello World!", result);
  18434. }
  18435. TEST_F(OpenStreamTest, DefaultHeaders) {
  18436. Client cli("127.0.0.1", port_);
  18437. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18438. {
  18439. auto handle = cli.open_stream("GET", "/echo-headers");
  18440. ASSERT_TRUE(handle.is_valid());
  18441. auto body = read_all(handle);
  18442. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18443. std::string::npos);
  18444. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18445. std::string::npos);
  18446. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18447. }
  18448. // open_stream POST with body and no explicit content_type should NOT add
  18449. // text/plain Content-Type (behavior differs from non-streaming path), but
  18450. // should include Content-Length
  18451. {
  18452. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18453. ASSERT_TRUE(handle.is_valid());
  18454. auto body = read_all(handle);
  18455. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18456. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18457. }
  18458. // open_stream POST with explicit Content-Type should preserve it
  18459. {
  18460. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18461. {{"Content-Type", "application/custom"}},
  18462. "{}", "application/custom");
  18463. ASSERT_TRUE(handle.is_valid());
  18464. auto body = read_all(handle);
  18465. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18466. }
  18467. // User-specified User-Agent must not be overwritten for stream API
  18468. {
  18469. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18470. {{"User-Agent", "MyAgent/1.2"}});
  18471. ASSERT_TRUE(handle.is_valid());
  18472. auto body = read_all(handle);
  18473. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18474. }
  18475. }
  18476. TEST_F(OpenStreamTest, Large) {
  18477. Client cli("127.0.0.1", port_);
  18478. auto handle = cli.open_stream("GET", "/large");
  18479. EXPECT_EQ(10000u, read_all(handle).size());
  18480. }
  18481. TEST_F(OpenStreamTest, ConnectionError) {
  18482. Client cli("127.0.0.1", 9999);
  18483. auto handle = cli.open_stream("GET", "/hello");
  18484. EXPECT_FALSE(handle.is_valid());
  18485. }
  18486. TEST_F(OpenStreamTest, Chunked) {
  18487. Client cli("127.0.0.1", port_);
  18488. auto handle = cli.open_stream("GET", "/chunked");
  18489. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18490. "Transfer-Encoding") == "chunked");
  18491. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18492. }
  18493. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18494. Client cli("127.0.0.1", port_);
  18495. auto handle =
  18496. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18497. ASSERT_TRUE(handle.is_valid());
  18498. // Consume body to allow trailers to be received/parsed
  18499. auto body = read_all(handle);
  18500. // Explicitly parse trailers (ensure trailers are available for assertion)
  18501. handle.parse_trailers_if_needed();
  18502. EXPECT_EQ(std::string("123456789"), body);
  18503. // The response should include a Trailer header declaring both names
  18504. ASSERT_TRUE(handle.response);
  18505. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18506. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18507. handle.response->get_header_value("Trailer"));
  18508. // Prohibited trailer must not be present
  18509. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18510. // Allowed trailer should be present
  18511. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18512. EXPECT_EQ(std::string("yes"),
  18513. handle.response->get_trailer_value("X-Allowed"));
  18514. // Verify trailers are NOT present as regular headers
  18515. EXPECT_EQ(std::string(""),
  18516. handle.response->get_header_value("Content-Length"));
  18517. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18518. }
  18519. static std::thread serve_single_response(std::promise<int> &port_promise,
  18520. const std::string &response) {
  18521. return std::thread([&port_promise, response] {
  18522. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18523. default_socket_options(srv);
  18524. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18525. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18526. sockaddr_in addr{};
  18527. addr.sin_family = AF_INET;
  18528. addr.sin_port = htons(0); // Let OS assign a free port
  18529. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18530. int opt = 1;
  18531. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18532. #ifdef _WIN32
  18533. reinterpret_cast<const char *>(&opt),
  18534. #else
  18535. &opt,
  18536. #endif
  18537. sizeof(opt));
  18538. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18539. ::listen(srv, 1) != 0) {
  18540. port_promise.set_value(-1);
  18541. detail::close_socket(srv);
  18542. return;
  18543. }
  18544. socklen_t addr_len = sizeof(addr);
  18545. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18546. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18547. sockaddr_in cli_addr{};
  18548. socklen_t cli_len = sizeof(cli_addr);
  18549. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18550. if (cli != INVALID_SOCKET) {
  18551. // Read the complete HTTP request (until the blank line that terminates
  18552. // headers) before sending the response. If the server closes the socket
  18553. // while the client's request data is still unread in the kernel receive
  18554. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18555. // connection on both sides: it discards the client's receive buffer
  18556. // (which already holds our response) and causes any in-progress write on
  18557. // the client to fail with ECONNRESET. Reading all request data first
  18558. // ensures close() emits a graceful FIN.
  18559. {
  18560. char rbuf[256];
  18561. std::string req;
  18562. while (req.find("\r\n\r\n") == std::string::npos) {
  18563. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18564. if (n <= 0) { break; }
  18565. req.append(rbuf, static_cast<size_t>(n));
  18566. }
  18567. }
  18568. ::send(cli,
  18569. #ifdef _WIN32
  18570. static_cast<const char *>(response.c_str()),
  18571. static_cast<int>(response.size()),
  18572. #else
  18573. response.c_str(), response.size(),
  18574. #endif
  18575. 0);
  18576. detail::close_socket(cli);
  18577. }
  18578. detail::close_socket(srv);
  18579. });
  18580. }
  18581. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18582. #ifndef _WIN32
  18583. signal(SIGPIPE, SIG_IGN);
  18584. #endif
  18585. std::promise<int> port_promise;
  18586. auto port_future = port_promise.get_future();
  18587. auto server_thread =
  18588. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18589. "Content-Type: text/plain\r\n"
  18590. "Content-Length: not-a-number\r\n"
  18591. "Connection: close\r\n"
  18592. "\r\n"
  18593. "hello");
  18594. auto port = port_future.get();
  18595. ASSERT_GT(port, 0);
  18596. Client cli("127.0.0.1", port);
  18597. auto handle = cli.open_stream("GET", "/");
  18598. EXPECT_FALSE(handle.is_valid());
  18599. server_thread.join();
  18600. }
  18601. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18602. #ifndef _WIN32
  18603. signal(SIGPIPE, SIG_IGN);
  18604. #endif
  18605. std::promise<int> port_promise;
  18606. auto port_future = port_promise.get_future();
  18607. auto server_thread = serve_single_response(
  18608. port_promise, "HTTP/1.1 200 OK\r\n"
  18609. "Content-Type: text/plain\r\n"
  18610. "Content-Length: 99999999999999999999999999\r\n"
  18611. "Connection: close\r\n"
  18612. "\r\n"
  18613. "hello");
  18614. auto port = port_future.get();
  18615. ASSERT_GT(port, 0);
  18616. // Historically std::stoull would throw std::out_of_range here and crash
  18617. // the process, then parsing silently clamped to a bogus framing length and
  18618. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18619. // so the stream fails to open, matching the not-a-number case above. The
  18620. // process still must NOT terminate.
  18621. Client cli("127.0.0.1", port);
  18622. auto handle = cli.open_stream("GET", "/");
  18623. EXPECT_FALSE(handle.is_valid());
  18624. server_thread.join();
  18625. }
  18626. // Serves `response` to the single request `fn` makes with a fresh client.
  18627. template <typename Fn>
  18628. static void with_single_response(const std::string &response, Fn fn) {
  18629. #ifndef _WIN32
  18630. signal(SIGPIPE, SIG_IGN);
  18631. #endif
  18632. std::promise<int> port_promise;
  18633. auto port_future = port_promise.get_future();
  18634. auto server_thread = serve_single_response(port_promise, response);
  18635. auto se = detail::scope_exit([&] { server_thread.join(); });
  18636. auto port = port_future.get();
  18637. ASSERT_GT(port, 0);
  18638. Client cli("127.0.0.1", port);
  18639. fn(cli);
  18640. }
  18641. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18642. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18643. // the chunked coding and drop Content-Length, so a front-end that trusts
  18644. // Content-Length would disagree about where the body ends (response
  18645. // smuggling). The client must reject such a response.
  18646. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18647. for (const char *te : {"chunked", "gzip, chunked"}) {
  18648. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18649. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18650. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18651. "5\r\nhello\r\n0\r\n\r\n";
  18652. with_single_response(response, [&](Client &cli) {
  18653. auto res = cli.Get("/");
  18654. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18655. EXPECT_EQ(Error::Read, res.error()) << te;
  18656. });
  18657. with_single_response(response, [&](Client &cli) {
  18658. auto handle = cli.open_stream("GET", "/");
  18659. EXPECT_FALSE(handle.is_valid()) << te;
  18660. EXPECT_EQ(Error::Read, handle.error) << te;
  18661. });
  18662. }
  18663. }
  18664. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18665. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18666. // closing the connection (unlike a request, which must be rejected).
  18667. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18668. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18669. "Transfer-Encoding: chunked\r\n"
  18670. "Connection: close\r\n"
  18671. "\r\n"
  18672. "5\r\nhello\r\n0\r\n\r\n",
  18673. "HTTP/1.1 200 OK\r\n"
  18674. "Transfer-Encoding: gzip\r\n"
  18675. "Connection: close\r\n"
  18676. "\r\n"
  18677. "hello"}) {
  18678. with_single_response(response, [&](Client &cli) {
  18679. auto res = cli.Get("/");
  18680. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18681. EXPECT_EQ("hello", res->body);
  18682. });
  18683. with_single_response(response, [&](Client &cli) {
  18684. auto handle = cli.open_stream("GET", "/");
  18685. ASSERT_TRUE(handle.is_valid()) << response;
  18686. EXPECT_EQ("hello", read_all(handle));
  18687. });
  18688. }
  18689. }
  18690. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18691. // framing headers describe nothing to read and must not be rejected.
  18692. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18693. const std::string framing = "Content-Length: 5\r\n"
  18694. "Transfer-Encoding: chunked\r\n"
  18695. "Connection: close\r\n"
  18696. "\r\n";
  18697. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18698. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18699. });
  18700. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18701. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18702. });
  18703. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18704. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18705. with_single_response(response, [&](Client &cli) {
  18706. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18707. });
  18708. with_single_response(response, [&](Client &cli) {
  18709. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18710. });
  18711. }
  18712. }
  18713. // A payload max length of 0 means no limit, however the body is framed.
  18714. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18715. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18716. "Transfer-Encoding: chunked\r\n"
  18717. "\r\n"
  18718. "5\r\nhello\r\n0\r\n\r\n",
  18719. "HTTP/1.1 200 OK\r\n"
  18720. "Connection: close\r\n"
  18721. "\r\n"
  18722. "hello"}) {
  18723. with_single_response(response, [&](Client &cli) {
  18724. cli.set_payload_max_length(0);
  18725. auto res = cli.Get("/");
  18726. ASSERT_TRUE(res) << response;
  18727. EXPECT_EQ("hello", res->body) << response;
  18728. });
  18729. }
  18730. }
  18731. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18732. Server svr;
  18733. svr.set_payload_max_length(0);
  18734. svr.Post("/echo", [](const Request &req, Response &res) {
  18735. res.set_content(req.body, "text/plain");
  18736. });
  18737. auto port = svr.bind_to_any_port(HOST);
  18738. thread t = thread([&] { svr.listen_after_bind(); });
  18739. auto se = detail::scope_exit([&] {
  18740. svr.stop();
  18741. t.join();
  18742. ASSERT_FALSE(svr.is_running());
  18743. });
  18744. svr.wait_until_ready();
  18745. Client cli(HOST, port);
  18746. auto res = cli.Post(
  18747. "/echo",
  18748. [](size_t /*offset*/, DataSink &sink) {
  18749. sink.write("hello", 5);
  18750. sink.done();
  18751. return true;
  18752. },
  18753. "text/plain");
  18754. ASSERT_TRUE(res);
  18755. EXPECT_EQ(StatusCode::OK_200, res->status);
  18756. EXPECT_EQ("hello", res->body);
  18757. }
  18758. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18759. TEST_F(OpenStreamTest, Gzip) {
  18760. Client cli("127.0.0.1", port_);
  18761. auto handle = cli.open_stream("GET", "/compressible", {},
  18762. {{"Accept-Encoding", "gzip"}});
  18763. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18764. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18765. }
  18766. #endif
  18767. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18768. TEST_F(OpenStreamTest, Brotli) {
  18769. Client cli("127.0.0.1", port_);
  18770. auto handle =
  18771. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18772. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18773. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18774. }
  18775. #endif
  18776. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18777. TEST_F(OpenStreamTest, Zstd) {
  18778. Client cli("127.0.0.1", port_);
  18779. auto handle = cli.open_stream("GET", "/compressible", {},
  18780. {{"Accept-Encoding", "zstd"}});
  18781. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18782. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18783. }
  18784. #endif
  18785. #ifdef CPPHTTPLIB_SSL_ENABLED
  18786. class SSLOpenStreamTest : public ::testing::Test {
  18787. protected:
  18788. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18789. void SetUp() override {
  18790. svr_.Get("/hello", [](const Request &, Response &res) {
  18791. res.set_content("Hello SSL World!", "text/plain");
  18792. });
  18793. svr_.Get("/chunked", [](const Request &, Response &res) {
  18794. res.set_chunked_content_provider("text/plain",
  18795. [](size_t offset, DataSink &sink) {
  18796. if (offset < 15) {
  18797. sink.write("chunk", 5);
  18798. return true;
  18799. }
  18800. sink.done();
  18801. return true;
  18802. });
  18803. });
  18804. svr_.Post("/echo", [](const Request &req, Response &res) {
  18805. res.set_content(req.body, req.get_header_value("Content-Type"));
  18806. });
  18807. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18808. std::string body = req.body;
  18809. res.set_chunked_content_provider(
  18810. "text/plain", [body](size_t offset, DataSink &sink) {
  18811. if (offset < body.size()) {
  18812. sink.write(body.data() + offset, body.size() - offset);
  18813. }
  18814. sink.done();
  18815. return true;
  18816. });
  18817. });
  18818. port_ = svr_.bind_to_any_port("127.0.0.1");
  18819. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18820. svr_.wait_until_ready();
  18821. }
  18822. void TearDown() override {
  18823. svr_.stop();
  18824. if (thread_.joinable()) thread_.join();
  18825. }
  18826. SSLServer svr_;
  18827. std::thread thread_;
  18828. int port_ = 0;
  18829. };
  18830. TEST_F(SSLOpenStreamTest, Basic) {
  18831. SSLClient cli("127.0.0.1", port_);
  18832. cli.enable_server_certificate_verification(false);
  18833. auto handle = cli.open_stream("GET", "/hello");
  18834. ASSERT_TRUE(handle.is_valid());
  18835. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18836. }
  18837. TEST_F(SSLOpenStreamTest, Chunked) {
  18838. SSLClient cli("127.0.0.1", port_);
  18839. cli.enable_server_certificate_verification(false);
  18840. auto handle = cli.open_stream("GET", "/chunked");
  18841. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18842. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18843. "Transfer-Encoding") == "chunked");
  18844. auto body = read_all(handle);
  18845. EXPECT_EQ("chunkchunkchunk", body);
  18846. }
  18847. TEST_F(SSLOpenStreamTest, Post) {
  18848. SSLClient cli("127.0.0.1", port_);
  18849. cli.enable_server_certificate_verification(false);
  18850. auto handle =
  18851. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18852. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18853. EXPECT_EQ(200, handle.response->status);
  18854. auto body = read_all(handle);
  18855. EXPECT_EQ("Hello SSL POST", body);
  18856. }
  18857. TEST_F(SSLOpenStreamTest, PostChunked) {
  18858. SSLClient cli("127.0.0.1", port_);
  18859. cli.enable_server_certificate_verification(false);
  18860. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18861. "Chunked SSL Data", "text/plain");
  18862. ASSERT_TRUE(handle.is_valid());
  18863. EXPECT_EQ(200, handle.response->status);
  18864. auto body = read_all(handle);
  18865. EXPECT_EQ("Chunked SSL Data", body);
  18866. }
  18867. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18868. // Content-Length is terminated by the server closing the connection. When the
  18869. // SSL peer sends a close_notify after the body, the client must treat it as a
  18870. // clean EOF and return a successful response rather than an error.
  18871. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18873. ASSERT_TRUE(svr.is_valid());
  18874. svr.set_keep_alive_max_count(1);
  18875. const std::string expected_body = "Hello from connection-close response!";
  18876. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18877. res.set_content_provider("text/plain",
  18878. [&](size_t offset, DataSink &sink) -> bool {
  18879. if (offset < expected_body.size()) {
  18880. sink.write(expected_body.data() + offset,
  18881. expected_body.size() - offset);
  18882. }
  18883. sink.done();
  18884. return true;
  18885. });
  18886. });
  18887. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18888. auto se = detail::scope_exit([&] {
  18889. svr.stop();
  18890. listen_thread.join();
  18891. ASSERT_FALSE(svr.is_running());
  18892. });
  18893. svr.wait_until_ready();
  18894. SSLClient cli(HOST, PORT);
  18895. cli.enable_server_certificate_verification(false);
  18896. auto res = cli.Get("/no-content-length");
  18897. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18898. EXPECT_EQ(StatusCode::OK_200, res->status);
  18899. EXPECT_EQ(expected_body, res->body);
  18900. }
  18901. #endif // CPPHTTPLIB_SSL_ENABLED
  18902. //==============================================================================
  18903. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18904. // results for various scenarios.
  18905. //==============================================================================
  18906. TEST(ParityTest, GetVsOpenStream) {
  18907. Server svr;
  18908. const std::string path = "/parity";
  18909. const std::string content = "Parity test content: hello world";
  18910. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18911. res.set_content(content, "text/plain");
  18912. });
  18913. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18914. auto se = detail::scope_exit([&] {
  18915. svr.stop();
  18916. t.join();
  18917. ASSERT_FALSE(svr.is_running());
  18918. });
  18919. svr.wait_until_ready();
  18920. Client cli(HOST, PORT);
  18921. // Non-stream path
  18922. auto r1 = cli.Get(path);
  18923. ASSERT_TRUE(r1);
  18924. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18925. // Stream path
  18926. auto h = cli.open_stream("GET", path);
  18927. ASSERT_TRUE(h.is_valid());
  18928. EXPECT_EQ(r1->body, read_all(h));
  18929. }
  18930. // Helper to compress data with provided compressor type T
  18931. template <typename Compressor>
  18932. static std::string compress_payload_for_parity(const std::string &in) {
  18933. std::string out;
  18934. Compressor compressor;
  18935. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18936. [&](const char *data, size_t n) {
  18937. out.append(data, n);
  18938. return true;
  18939. });
  18940. EXPECT_TRUE(ok);
  18941. return out;
  18942. }
  18943. // Helper function for compression parity tests
  18944. template <typename Compressor>
  18945. static void test_compression_parity(const std::string &original,
  18946. const std::string &path,
  18947. const std::string &encoding) {
  18948. const std::string compressed =
  18949. compress_payload_for_parity<Compressor>(original);
  18950. Server svr;
  18951. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18952. res.set_content(compressed, "application/octet-stream");
  18953. res.set_header("Content-Encoding", encoding);
  18954. });
  18955. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18956. auto se = detail::scope_exit([&] {
  18957. svr.stop();
  18958. t.join();
  18959. ASSERT_FALSE(svr.is_running());
  18960. });
  18961. svr.wait_until_ready();
  18962. Client cli(HOST, PORT);
  18963. // Non-streaming
  18964. {
  18965. auto res = cli.Get(path);
  18966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18967. EXPECT_EQ(StatusCode::OK_200, res->status);
  18968. EXPECT_EQ(original, res->body);
  18969. }
  18970. // Streaming
  18971. {
  18972. auto h = cli.open_stream("GET", path);
  18973. ASSERT_TRUE(h.is_valid());
  18974. EXPECT_EQ(original, read_all(h));
  18975. }
  18976. }
  18977. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18978. TEST(ParityTest, Gzip) {
  18979. test_compression_parity<detail::gzip_compressor>(
  18980. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18981. }
  18982. #endif
  18983. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18984. TEST(ParityTest, Brotli) {
  18985. test_compression_parity<detail::brotli_compressor>(
  18986. "Hello, brotli parity test payload", "/parity-br", "br");
  18987. }
  18988. #endif
  18989. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18990. TEST(ParityTest, Zstd) {
  18991. test_compression_parity<detail::zstd_compressor>(
  18992. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18993. }
  18994. #endif
  18995. //==============================================================================
  18996. // New Stream API Tests
  18997. //==============================================================================
  18998. inline std::string read_body(httplib::stream::Result &result) {
  18999. std::string body;
  19000. while (result.next()) {
  19001. body.append(result.data(), result.size());
  19002. }
  19003. return body;
  19004. }
  19005. TEST(ClientConnectionTest, Basic) {
  19006. httplib::ClientConnection conn;
  19007. EXPECT_FALSE(conn.is_open());
  19008. conn.sock = 1;
  19009. EXPECT_TRUE(conn.is_open());
  19010. httplib::ClientConnection conn2(std::move(conn));
  19011. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19012. conn2.sock = INVALID_SOCKET;
  19013. }
  19014. // Unified test server for all stream::* tests
  19015. class StreamApiTest : public ::testing::Test {
  19016. protected:
  19017. void SetUp() override {
  19018. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19019. res.set_content("Hello World!", "text/plain");
  19020. });
  19021. svr_.Get("/echo-params",
  19022. [](const httplib::Request &req, httplib::Response &res) {
  19023. std::string r;
  19024. for (const auto &p : req.params) {
  19025. if (!r.empty()) r += "&";
  19026. r += p.first + "=" + p.second;
  19027. }
  19028. res.set_content(r, "text/plain");
  19029. });
  19030. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19031. res.set_content(req.body, req.get_header_value("Content-Type"));
  19032. });
  19033. svr_.Post("/echo-headers",
  19034. [](const httplib::Request &req, httplib::Response &res) {
  19035. std::string r;
  19036. for (const auto &h : req.headers)
  19037. r += h.first + ": " + h.second + "\n";
  19038. res.set_content(r, "text/plain");
  19039. });
  19040. svr_.Post("/echo-params",
  19041. [](const httplib::Request &req, httplib::Response &res) {
  19042. std::string r = "params:";
  19043. for (const auto &p : req.params)
  19044. r += p.first + "=" + p.second + ";";
  19045. res.set_content(r + " body:" + req.body, "text/plain");
  19046. });
  19047. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19048. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19049. });
  19050. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19051. res.set_content("PUT:" + req.body, "text/plain");
  19052. });
  19053. svr_.Patch("/echo",
  19054. [](const httplib::Request &req, httplib::Response &res) {
  19055. res.set_content("PATCH:" + req.body, "text/plain");
  19056. });
  19057. svr_.Delete(
  19058. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19059. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19060. "text/plain");
  19061. });
  19062. svr_.Get("/head-test",
  19063. [](const httplib::Request &, httplib::Response &res) {
  19064. res.set_content("body for HEAD", "text/plain");
  19065. });
  19066. svr_.Options("/options",
  19067. [](const httplib::Request &, httplib::Response &res) {
  19068. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19069. });
  19070. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19071. svr_.wait_until_ready();
  19072. }
  19073. void TearDown() override {
  19074. svr_.stop();
  19075. if (thread_.joinable()) thread_.join();
  19076. }
  19077. httplib::Server svr_;
  19078. std::thread thread_;
  19079. };
  19080. // stream::Get tests
  19081. TEST_F(StreamApiTest, GetBasic) {
  19082. httplib::Client cli(HOST, PORT);
  19083. auto result = httplib::stream::Get(cli, "/hello");
  19084. ASSERT_TRUE(result.is_valid());
  19085. EXPECT_EQ(200, result.status());
  19086. EXPECT_EQ("Hello World!", read_body(result));
  19087. }
  19088. TEST_F(StreamApiTest, GetWithParams) {
  19089. httplib::Client cli(HOST, PORT);
  19090. httplib::Params params{{"foo", "bar"}};
  19091. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19092. ASSERT_TRUE(result.is_valid());
  19093. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19094. }
  19095. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19096. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19097. httplib::Client cli(HOST, PORT);
  19098. cli.set_payload_max_length(0);
  19099. auto result = httplib::stream::Get(cli, "/hello");
  19100. ASSERT_TRUE(result.is_valid());
  19101. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19102. EXPECT_EQ("Hello World!", read_body(result));
  19103. }
  19104. #endif
  19105. TEST_F(StreamApiTest, GetConnectionError) {
  19106. httplib::Client cli(HOST, 9999);
  19107. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19108. }
  19109. TEST_F(StreamApiTest, Get404) {
  19110. httplib::Client cli(HOST, PORT);
  19111. auto result = httplib::stream::Get(cli, "/nonexistent");
  19112. EXPECT_TRUE(result.is_valid());
  19113. EXPECT_EQ(404, result.status());
  19114. }
  19115. // stream::Post tests
  19116. TEST_F(StreamApiTest, PostBasic) {
  19117. httplib::Client cli(HOST, PORT);
  19118. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19119. "application/json");
  19120. ASSERT_TRUE(result.is_valid());
  19121. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19122. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19123. }
  19124. TEST_F(StreamApiTest, PostWithHeaders) {
  19125. httplib::Client cli(HOST, PORT);
  19126. httplib::Headers headers{{"X-Custom", "value"}};
  19127. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19128. "text/plain");
  19129. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19130. }
  19131. TEST_F(StreamApiTest, PostWithParams) {
  19132. httplib::Client cli(HOST, PORT);
  19133. httplib::Params params{{"k", "v"}};
  19134. auto result =
  19135. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19136. auto body = read_body(result);
  19137. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19138. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19139. }
  19140. TEST_F(StreamApiTest, PostLarge) {
  19141. httplib::Client cli(HOST, PORT);
  19142. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19143. size_t total = 0;
  19144. while (result.next()) {
  19145. total += result.size();
  19146. }
  19147. EXPECT_EQ(100u * 1024u, total);
  19148. }
  19149. // stream::Put/Patch tests
  19150. TEST_F(StreamApiTest, PutAndPatch) {
  19151. httplib::Client cli(HOST, PORT);
  19152. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19153. EXPECT_EQ("PUT:test", read_body(put));
  19154. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19155. EXPECT_EQ("PATCH:test", read_body(patch));
  19156. }
  19157. // stream::Delete tests
  19158. TEST_F(StreamApiTest, Delete) {
  19159. httplib::Client cli(HOST, PORT);
  19160. auto del1 = httplib::stream::Delete(cli, "/resource");
  19161. EXPECT_EQ("Deleted", read_body(del1));
  19162. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19163. EXPECT_EQ("Deleted:data", read_body(del2));
  19164. }
  19165. // stream::Head/Options tests
  19166. TEST_F(StreamApiTest, HeadAndOptions) {
  19167. httplib::Client cli(HOST, PORT);
  19168. auto head = httplib::stream::Head(cli, "/head-test");
  19169. EXPECT_TRUE(head.is_valid());
  19170. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19171. auto opts = httplib::stream::Options(cli, "/options");
  19172. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19173. }
  19174. // SSL stream::* tests
  19175. #ifdef CPPHTTPLIB_SSL_ENABLED
  19176. class SSLStreamApiTest : public ::testing::Test {
  19177. protected:
  19178. void SetUp() override {
  19179. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19180. res.set_content("Hello SSL!", "text/plain");
  19181. });
  19182. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19183. res.set_content(req.body, "text/plain");
  19184. });
  19185. port_ = svr_.bind_to_any_port("127.0.0.1");
  19186. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19187. svr_.wait_until_ready();
  19188. }
  19189. void TearDown() override {
  19190. svr_.stop();
  19191. if (thread_.joinable()) thread_.join();
  19192. }
  19193. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19194. std::thread thread_;
  19195. int port_ = 0;
  19196. };
  19197. TEST_F(SSLStreamApiTest, GetAndPost) {
  19198. httplib::SSLClient cli("127.0.0.1", port_);
  19199. cli.enable_server_certificate_verification(false);
  19200. auto get = httplib::stream::Get(cli, "/hello");
  19201. EXPECT_EQ("Hello SSL!", read_body(get));
  19202. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19203. EXPECT_EQ("test", read_body(post));
  19204. }
  19205. #endif
  19206. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19207. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19208. // BodyReader
  19209. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19210. // Test that read timeout during streaming is detected
  19211. // Use a large content-length response where server delays mid-stream
  19212. Server svr;
  19213. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19214. // Send a large response with delay in the middle
  19215. res.set_content_provider(
  19216. 1000, // content_length
  19217. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19218. if (offset < 100) {
  19219. // Send first 100 bytes immediately
  19220. std::string data(100, 'A');
  19221. sink.write(data.c_str(), data.size());
  19222. return true;
  19223. }
  19224. // Then delay longer than client timeout
  19225. std::this_thread::sleep_for(std::chrono::seconds(3));
  19226. std::string data(900, 'B');
  19227. sink.write(data.c_str(), data.size());
  19228. return true;
  19229. });
  19230. });
  19231. auto port = 8091;
  19232. std::thread t([&]() { svr.listen("localhost", port); });
  19233. svr.wait_until_ready();
  19234. Client cli("localhost", port);
  19235. cli.set_read_timeout(1, 0); // 1 second timeout
  19236. auto handle = cli.open_stream("GET", "/slow-stream");
  19237. ASSERT_TRUE(handle.is_valid());
  19238. char buf[256];
  19239. ssize_t total = 0;
  19240. ssize_t n;
  19241. bool got_error = false;
  19242. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19243. total += n;
  19244. }
  19245. if (n < 0) {
  19246. got_error = true;
  19247. // Should be timeout or read error
  19248. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19249. handle.get_read_error() == Error::Read)
  19250. << "Actual error: " << to_string(handle.get_read_error());
  19251. }
  19252. // Either we got an error, or we got less data than expected
  19253. EXPECT_TRUE(got_error || total < 1000)
  19254. << "Expected timeout but got all " << total << " bytes";
  19255. svr.stop();
  19256. t.join();
  19257. }
  19258. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19259. // Test connection closed detection via BodyReader
  19260. Server svr;
  19261. std::atomic<bool> close_now{false};
  19262. svr.Get("/will-close", [&](const Request &, Response &res) {
  19263. res.set_content_provider(
  19264. 10000, // Large content_length that we won't fully send
  19265. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19266. if (offset < 100) {
  19267. std::string data(100, 'X');
  19268. sink.write(data.c_str(), data.size());
  19269. return true;
  19270. }
  19271. // Wait for signal then abort
  19272. while (!close_now) {
  19273. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19274. }
  19275. return false; // Abort - server will close connection
  19276. });
  19277. });
  19278. auto port = 8092;
  19279. std::thread t([&]() { svr.listen("localhost", port); });
  19280. svr.wait_until_ready();
  19281. Client cli("localhost", port);
  19282. auto handle = cli.open_stream("GET", "/will-close");
  19283. ASSERT_TRUE(handle.is_valid());
  19284. char buf[256];
  19285. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19286. EXPECT_GT(n, 0) << "First read should succeed";
  19287. // Signal server to close
  19288. close_now = true;
  19289. // Keep reading until error or EOF
  19290. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19291. // Keep reading
  19292. }
  19293. // Should get an error since content_length wasn't satisfied
  19294. if (n < 0) {
  19295. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19296. handle.get_read_error() == Error::Read)
  19297. << "Actual error: " << to_string(handle.get_read_error());
  19298. }
  19299. svr.stop();
  19300. t.join();
  19301. }
  19302. #ifdef CPPHTTPLIB_SSL_ENABLED
  19303. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19304. // Test that read timeout during SSL streaming is detected
  19305. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19306. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19307. res.set_content_provider(
  19308. 1000, "text/plain",
  19309. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19310. if (offset < 100) {
  19311. std::string data(100, 'A');
  19312. sink.write(data.c_str(), data.size());
  19313. return true;
  19314. }
  19315. std::this_thread::sleep_for(std::chrono::seconds(3));
  19316. std::string data(900, 'B');
  19317. sink.write(data.c_str(), data.size());
  19318. return true;
  19319. });
  19320. });
  19321. auto port = 8093;
  19322. std::thread t([&]() { svr.listen("localhost", port); });
  19323. svr.wait_until_ready();
  19324. SSLClient cli("localhost", port);
  19325. cli.enable_server_certificate_verification(false);
  19326. cli.set_read_timeout(1, 0); // 1 second timeout
  19327. auto handle = cli.open_stream("GET", "/slow-stream");
  19328. ASSERT_TRUE(handle.is_valid());
  19329. char buf[256];
  19330. ssize_t total = 0;
  19331. ssize_t n;
  19332. bool got_error = false;
  19333. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19334. total += n;
  19335. }
  19336. if (n < 0) {
  19337. got_error = true;
  19338. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19339. handle.get_read_error() == Error::Read)
  19340. << "Actual error: " << to_string(handle.get_read_error());
  19341. }
  19342. EXPECT_TRUE(got_error || total < 1000)
  19343. << "Expected timeout but got all " << total << " bytes";
  19344. svr.stop();
  19345. t.join();
  19346. }
  19347. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19348. // Test SSL connection closed detection
  19349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19350. std::atomic<bool> close_now{false};
  19351. svr.Get("/will-close", [&](const Request &, Response &res) {
  19352. res.set_content_provider(
  19353. 10000, "text/plain",
  19354. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19355. if (offset < 100) {
  19356. std::string data(100, 'X');
  19357. sink.write(data.c_str(), data.size());
  19358. return true;
  19359. }
  19360. while (!close_now) {
  19361. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19362. }
  19363. return false;
  19364. });
  19365. });
  19366. auto port = 8094;
  19367. std::thread t([&]() { svr.listen("localhost", port); });
  19368. svr.wait_until_ready();
  19369. SSLClient cli("localhost", port);
  19370. cli.enable_server_certificate_verification(false);
  19371. auto handle = cli.open_stream("GET", "/will-close");
  19372. ASSERT_TRUE(handle.is_valid());
  19373. char buf[256];
  19374. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19375. EXPECT_GT(n, 0);
  19376. // Signal server to close
  19377. close_now = true;
  19378. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19379. // Keep reading
  19380. }
  19381. if (n < 0) {
  19382. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19383. handle.get_read_error() == Error::Read)
  19384. << "Actual error: " << to_string(handle.get_read_error());
  19385. }
  19386. svr.stop();
  19387. t.join();
  19388. }
  19389. #endif
  19390. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19391. using namespace httplib;
  19392. // Create a test file
  19393. const char *fname = "etag_testfile.txt";
  19394. const char *content = "etag-content";
  19395. {
  19396. std::ofstream ofs(fname);
  19397. ofs << content;
  19398. ASSERT_TRUE(ofs.good());
  19399. }
  19400. Server svr;
  19401. svr.set_mount_point("/static", ".");
  19402. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19403. svr.wait_until_ready();
  19404. Client cli(HOST, PORT);
  19405. // First request: should get 200 with ETag header
  19406. auto res1 = cli.Get("/static/etag_testfile.txt");
  19407. ASSERT_TRUE(res1);
  19408. ASSERT_EQ(200, res1->status);
  19409. ASSERT_TRUE(res1->has_header("ETag"));
  19410. std::string etag = res1->get_header_value("ETag");
  19411. EXPECT_FALSE(etag.empty());
  19412. // Verify ETag format: W/"hex-hex"
  19413. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19414. EXPECT_EQ('W', etag[0]);
  19415. EXPECT_EQ('/', etag[1]);
  19416. EXPECT_EQ('"', etag[2]);
  19417. EXPECT_EQ('"', etag.back());
  19418. // Exact match: expect 304 Not Modified
  19419. Headers h2 = {{"If-None-Match", etag}};
  19420. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19421. ASSERT_TRUE(res2);
  19422. EXPECT_EQ(304, res2->status);
  19423. // Wildcard match: expect 304 Not Modified
  19424. Headers h3 = {{"If-None-Match", "*"}};
  19425. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19426. ASSERT_TRUE(res3);
  19427. EXPECT_EQ(304, res3->status);
  19428. // Non-matching ETag: expect 200
  19429. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19430. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19431. ASSERT_TRUE(res4);
  19432. EXPECT_EQ(200, res4->status);
  19433. // Multiple ETags with one matching: expect 304
  19434. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19435. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19436. ASSERT_TRUE(res5);
  19437. EXPECT_EQ(304, res5->status);
  19438. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19439. // that equivalent to the single comma-separated list above, so the match on
  19440. // the second line must still be found.
  19441. Headers h6;
  19442. h6.emplace("If-None-Match", "W/\"other\"");
  19443. h6.emplace("If-None-Match", etag);
  19444. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19445. ASSERT_TRUE(res6);
  19446. EXPECT_EQ(304, res6->status);
  19447. svr.stop();
  19448. t.join();
  19449. std::remove(fname);
  19450. }
  19451. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19452. using namespace httplib;
  19453. Server svr;
  19454. svr.set_mount_point("/static", ".");
  19455. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19456. svr.wait_until_ready();
  19457. Client cli(HOST, PORT);
  19458. // Send If-None-Match: * to a non-existent file
  19459. Headers h = {{"If-None-Match", "*"}};
  19460. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19462. EXPECT_EQ(404, res->status);
  19463. svr.stop();
  19464. t.join();
  19465. }
  19466. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19467. using namespace httplib;
  19468. // Create a test file
  19469. const char *fname = "etag_boundary_testfile.txt";
  19470. const char *content = "boundary-test";
  19471. {
  19472. std::ofstream ofs(fname);
  19473. ofs << content;
  19474. ASSERT_TRUE(ofs.good());
  19475. }
  19476. Server svr;
  19477. svr.set_mount_point("/static", ".");
  19478. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19479. svr.wait_until_ready();
  19480. Client cli(HOST, PORT);
  19481. // Get the actual ETag
  19482. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19483. ASSERT_TRUE(res1);
  19484. ASSERT_EQ(200, res1->status);
  19485. ASSERT_TRUE(res1->has_header("ETag"));
  19486. std::string etag = res1->get_header_value("ETag");
  19487. // Test 1: Very long ETag value (longer than actual ETag)
  19488. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19489. Headers h1 = {{"If-None-Match", "W/"
  19490. "\"very-long-etag-value-that-is-much-longer-"
  19491. "than-the-actual-etag-value\""}};
  19492. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19493. ASSERT_TRUE(res2);
  19494. EXPECT_EQ(200, res2->status); // Should not match
  19495. // Test 2: Long string followed by wildcard
  19496. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19497. // string)
  19498. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19499. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19500. ASSERT_TRUE(res3);
  19501. EXPECT_EQ(304, res3->status); // Should match on "*"
  19502. // Test 3: Wildcard followed by long string
  19503. // Should match on "*" immediately and return 304
  19504. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19505. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19506. ASSERT_TRUE(res4);
  19507. EXPECT_EQ(304, res4->status); // Should match on "*"
  19508. // Test 4: Multiple long non-matching values
  19509. // Should NOT match and return 200 (test that all comparisons are safe)
  19510. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19511. "W/\"second-long-non-matching-value\", "
  19512. "W/\"third-long-non-matching-value\""}};
  19513. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19514. ASSERT_TRUE(res5);
  19515. EXPECT_EQ(200, res5->status); // Should not match
  19516. // Test 5: Single character that is not "*" (edge case)
  19517. Headers h5 = {{"If-None-Match", "X"}};
  19518. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19519. ASSERT_TRUE(res6);
  19520. EXPECT_EQ(200, res6->status); // Should not match
  19521. svr.stop();
  19522. t.join();
  19523. std::remove(fname);
  19524. }
  19525. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19526. using namespace httplib;
  19527. // Create a test file
  19528. const char *fname = "ims_testfile.txt";
  19529. const char *content = "if-modified-since-test";
  19530. {
  19531. std::ofstream ofs(fname);
  19532. ofs << content;
  19533. ASSERT_TRUE(ofs.good());
  19534. }
  19535. Server svr;
  19536. svr.set_mount_point("/static", ".");
  19537. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19538. svr.wait_until_ready();
  19539. Client cli(HOST, PORT);
  19540. // First request: should get 200 with Last-Modified header
  19541. auto res1 = cli.Get("/static/ims_testfile.txt");
  19542. ASSERT_TRUE(res1);
  19543. ASSERT_EQ(200, res1->status);
  19544. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19545. std::string last_modified = res1->get_header_value("Last-Modified");
  19546. EXPECT_FALSE(last_modified.empty());
  19547. // If-Modified-Since with same time: expect 304
  19548. Headers h2 = {{"If-Modified-Since", last_modified}};
  19549. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19550. ASSERT_TRUE(res2);
  19551. EXPECT_EQ(304, res2->status);
  19552. // If-Modified-Since with future time: expect 304
  19553. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19554. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19555. ASSERT_TRUE(res3);
  19556. EXPECT_EQ(304, res3->status);
  19557. // If-Modified-Since with past time: expect 200
  19558. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19559. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19560. ASSERT_TRUE(res4);
  19561. EXPECT_EQ(200, res4->status);
  19562. // If-None-Match takes precedence over If-Modified-Since
  19563. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19564. ASSERT_TRUE(res1->has_header("ETag"));
  19565. std::string etag = res1->get_header_value("ETag");
  19566. Headers h5 = {{"If-None-Match", etag},
  19567. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19568. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19569. ASSERT_TRUE(res5);
  19570. EXPECT_EQ(304, res5->status);
  19571. svr.stop();
  19572. t.join();
  19573. std::remove(fname);
  19574. }
  19575. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19576. using namespace httplib;
  19577. Server svr;
  19578. // Endpoint that returns compressible content
  19579. svr.Get("/compressible", [](const Request &, Response &res) {
  19580. // Return a large enough body to trigger compression
  19581. std::string body(1000, 'a');
  19582. res.set_content(body, "text/plain");
  19583. });
  19584. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19585. svr.wait_until_ready();
  19586. Client cli(HOST, PORT);
  19587. // Request with gzip support: should get Vary header when compressed
  19588. cli.set_compress(true);
  19589. auto res1 = cli.Get("/compressible");
  19590. ASSERT_TRUE(res1);
  19591. EXPECT_EQ(200, res1->status);
  19592. // If Content-Encoding is set, Vary should also be set
  19593. if (res1->has_header("Content-Encoding")) {
  19594. EXPECT_TRUE(res1->has_header("Vary"));
  19595. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19596. }
  19597. // Request without Accept-Encoding header: should not have compression
  19598. Headers h_no_compress;
  19599. auto res2 = cli.Get("/compressible", h_no_compress);
  19600. ASSERT_TRUE(res2);
  19601. EXPECT_EQ(200, res2->status);
  19602. // Verify Vary header is present when compression is applied
  19603. // (the exact behavior depends on server configuration)
  19604. svr.stop();
  19605. t.join();
  19606. }
  19607. TEST(ETagTest, IfRangeWithETag) {
  19608. using namespace httplib;
  19609. // Create a test file with known content
  19610. const char *fname = "if_range_testfile.txt";
  19611. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19612. {
  19613. std::ofstream ofs(fname);
  19614. ofs << content;
  19615. ASSERT_TRUE(ofs.good());
  19616. }
  19617. Server svr;
  19618. svr.set_mount_point("/static", ".");
  19619. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19620. svr.wait_until_ready();
  19621. Client cli(HOST, PORT);
  19622. // First request: get ETag
  19623. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19624. ASSERT_TRUE(res1);
  19625. ASSERT_EQ(200, res1->status);
  19626. ASSERT_TRUE(res1->has_header("ETag"));
  19627. std::string etag = res1->get_header_value("ETag");
  19628. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19629. // Since our server generates weak ETags (W/"..."), If-Range with our
  19630. // ETag should NOT result in partial content - it should return full content.
  19631. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19632. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19633. ASSERT_TRUE(res2);
  19634. // Weak ETag in If-Range -> full content (200), not partial (206)
  19635. EXPECT_EQ(200, res2->status);
  19636. EXPECT_EQ(content, res2->body);
  19637. EXPECT_FALSE(res2->has_header("Content-Range"));
  19638. // Range request with non-matching If-Range (ETag): should get 200 (full
  19639. // content)
  19640. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19641. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19642. ASSERT_TRUE(res3);
  19643. EXPECT_EQ(200, res3->status);
  19644. EXPECT_EQ(content, res3->body);
  19645. EXPECT_FALSE(res3->has_header("Content-Range"));
  19646. // Range request with strong ETag (hypothetical - our server doesn't generate
  19647. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19648. // should return full content)
  19649. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19650. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19651. ASSERT_TRUE(res4);
  19652. EXPECT_EQ(200, res4->status);
  19653. EXPECT_EQ(content, res4->body);
  19654. EXPECT_FALSE(res4->has_header("Content-Range"));
  19655. svr.stop();
  19656. t.join();
  19657. std::remove(fname);
  19658. }
  19659. TEST(ETagTest, IfRangeWithDate) {
  19660. using namespace httplib;
  19661. // Create a test file
  19662. const char *fname = "if_range_date_testfile.txt";
  19663. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19664. {
  19665. std::ofstream ofs(fname);
  19666. ofs << content;
  19667. ASSERT_TRUE(ofs.good());
  19668. }
  19669. Server svr;
  19670. svr.set_mount_point("/static", ".");
  19671. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19672. svr.wait_until_ready();
  19673. Client cli(HOST, PORT);
  19674. // First request: get Last-Modified
  19675. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19676. ASSERT_TRUE(res1);
  19677. ASSERT_EQ(200, res1->status);
  19678. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19679. std::string last_modified = res1->get_header_value("Last-Modified");
  19680. // Range request with matching If-Range (date): should get 206
  19681. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19682. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19683. ASSERT_TRUE(res2);
  19684. EXPECT_EQ(206, res2->status);
  19685. EXPECT_EQ("FGHIJ", res2->body);
  19686. // Range request with old If-Range date: should get 200 (full content)
  19687. Headers h3 = {{"Range", "bytes=5-9"},
  19688. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19689. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19690. ASSERT_TRUE(res3);
  19691. EXPECT_EQ(200, res3->status);
  19692. EXPECT_EQ(content, res3->body);
  19693. // Range request with future If-Range date: should get 206
  19694. Headers h4 = {{"Range", "bytes=0-4"},
  19695. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19696. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19697. ASSERT_TRUE(res4);
  19698. EXPECT_EQ(206, res4->status);
  19699. EXPECT_EQ("ABCDE", res4->body);
  19700. svr.stop();
  19701. t.join();
  19702. std::remove(fname);
  19703. }
  19704. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19705. using namespace httplib;
  19706. const char *fname = "etag_malformed.txt";
  19707. const char *content = "malformed-etag";
  19708. {
  19709. std::ofstream ofs(fname);
  19710. ofs << content;
  19711. ASSERT_TRUE(ofs.good());
  19712. }
  19713. Server svr;
  19714. svr.set_mount_point("/static", ".");
  19715. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19716. svr.wait_until_ready();
  19717. Client cli(HOST, PORT);
  19718. // baseline: should get 200 and an ETag
  19719. auto res1 = cli.Get("/static/etag_malformed.txt");
  19720. ASSERT_TRUE(res1);
  19721. ASSERT_EQ(200, res1->status);
  19722. ASSERT_TRUE(res1->has_header("ETag"));
  19723. // Malformed ETag value (missing quotes) should be treated as non-matching
  19724. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19725. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19726. ASSERT_TRUE(res_bad);
  19727. EXPECT_EQ(200, res_bad->status);
  19728. // Whitespace-only header value should be considered invalid / non-matching
  19729. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19730. "Host: localhost\r\n"
  19731. "If-None-Match: \r\n"
  19732. "Connection: close\r\n"
  19733. "\r\n";
  19734. std::string out;
  19735. ASSERT_TRUE(send_request(5, raw_req, &out));
  19736. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19737. svr.stop();
  19738. t.join();
  19739. std::remove(fname);
  19740. }
  19741. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19742. using namespace httplib;
  19743. const char *fname = "ims_invalid_format.txt";
  19744. const char *content = "ims-bad-format";
  19745. {
  19746. std::ofstream ofs(fname);
  19747. ofs << content;
  19748. ASSERT_TRUE(ofs.good());
  19749. }
  19750. Server svr;
  19751. svr.set_mount_point("/static", ".");
  19752. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19753. svr.wait_until_ready();
  19754. Client cli(HOST, PORT);
  19755. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19756. ASSERT_TRUE(res1);
  19757. ASSERT_EQ(200, res1->status);
  19758. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19759. // If-Modified-Since with invalid format should not result in 304
  19760. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19761. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19762. ASSERT_TRUE(res_bad);
  19763. EXPECT_EQ(200, res_bad->status);
  19764. // If-Range with invalid date format should be treated as mismatch -> full
  19765. // content (200)
  19766. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19767. {"If-Range", "invalid-date"}};
  19768. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19769. ASSERT_TRUE(res_ifrange);
  19770. EXPECT_EQ(200, res_ifrange->status);
  19771. svr.stop();
  19772. t.join();
  19773. std::remove(fname);
  19774. }
  19775. TEST(ETagTest, IfRangeWithMalformedETag) {
  19776. using namespace httplib;
  19777. const char *fname = "ifrange_malformed.txt";
  19778. const std::string content = "0123456789";
  19779. {
  19780. std::ofstream ofs(fname);
  19781. ofs << content;
  19782. ASSERT_TRUE(ofs.good());
  19783. }
  19784. Server svr;
  19785. svr.set_mount_point("/static", ".");
  19786. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19787. svr.wait_until_ready();
  19788. Client cli(HOST, PORT);
  19789. // First request: get ETag
  19790. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19791. ASSERT_TRUE(res1);
  19792. ASSERT_EQ(200, res1->status);
  19793. ASSERT_TRUE(res1->has_header("ETag"));
  19794. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19795. // full content (200)
  19796. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19797. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19798. ASSERT_TRUE(res2);
  19799. EXPECT_EQ(200, res2->status);
  19800. EXPECT_EQ(content, res2->body);
  19801. svr.stop();
  19802. t.join();
  19803. std::remove(fname);
  19804. }
  19805. TEST(ETagTest, ExtremeLargeDateValues) {
  19806. using namespace httplib;
  19807. const char *fname = "ims_extreme_date.txt";
  19808. const char *content = "ims-extreme-date";
  19809. {
  19810. std::ofstream ofs(fname);
  19811. ofs << content;
  19812. ASSERT_TRUE(ofs.good());
  19813. }
  19814. Server svr;
  19815. svr.set_mount_point("/static", ".");
  19816. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19817. svr.wait_until_ready();
  19818. Client cli(HOST, PORT);
  19819. auto res1 = cli.Get(std::string("/static/") + fname);
  19820. ASSERT_TRUE(res1);
  19821. ASSERT_EQ(200, res1->status);
  19822. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19823. // Extremely large year that may overflow date parsing routines.
  19824. Headers h_large_date = {
  19825. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19826. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19827. ASSERT_TRUE(res_bad);
  19828. // Expect server to treat this as invalid/mismatch and return full content
  19829. EXPECT_EQ(200, res_bad->status);
  19830. // If-Range with extremely large date should be treated as mismatch -> full
  19831. // content (200)
  19832. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19833. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19834. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19835. ASSERT_TRUE(res_ifrange);
  19836. EXPECT_EQ(200, res_ifrange->status);
  19837. svr.stop();
  19838. t.join();
  19839. std::remove(fname);
  19840. }
  19841. TEST(ETagTest, NegativeFileModificationTime) {
  19842. using namespace httplib;
  19843. const char *fname = "ims_negative_mtime.txt";
  19844. const std::string content = "negative-mtime";
  19845. {
  19846. std::ofstream ofs(fname);
  19847. ofs << content;
  19848. ASSERT_TRUE(ofs.good());
  19849. }
  19850. // Try to set file mtime to a negative value. This may fail on some
  19851. // platforms/filesystems; if it fails, the test will still verify server
  19852. // behaves safely by performing a regular conditional request.
  19853. #if defined(__APPLE__) || defined(__linux__)
  19854. bool set_negative = false;
  19855. do {
  19856. struct timeval times[2];
  19857. // access time: now
  19858. times[0].tv_sec = time(nullptr);
  19859. times[0].tv_usec = 0;
  19860. // modification time: negative (e.g., -1)
  19861. times[1].tv_sec = -1;
  19862. times[1].tv_usec = 0;
  19863. if (utimes(fname, times) == 0) { set_negative = true; }
  19864. } while (0);
  19865. #else
  19866. bool set_negative = false;
  19867. #endif
  19868. Server svr;
  19869. svr.set_mount_point("/static", ".");
  19870. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19871. svr.wait_until_ready();
  19872. Client cli(HOST, PORT);
  19873. auto res1 = cli.Get(std::string("/static/") + fname);
  19874. ASSERT_TRUE(res1);
  19875. ASSERT_EQ(200, res1->status);
  19876. bool has_last_modified = res1->has_header("Last-Modified");
  19877. std::string last_modified;
  19878. if (has_last_modified) {
  19879. last_modified = res1->get_header_value("Last-Modified");
  19880. }
  19881. if (set_negative) {
  19882. // If we successfully set a negative mtime, ensure server returns a
  19883. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19884. // with an old date and ensure server handles it without crash.
  19885. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19886. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19887. ASSERT_TRUE(res2);
  19888. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19889. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19890. } else {
  19891. // Could not set negative mtime on this platform; fall back to verifying
  19892. // that normal invalid/malformed dates are treated safely (non-304).
  19893. Headers h_bad_date = {
  19894. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19895. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19896. ASSERT_TRUE(res_bad);
  19897. EXPECT_EQ(200, res_bad->status);
  19898. }
  19899. svr.stop();
  19900. t.join();
  19901. std::remove(fname);
  19902. }
  19903. //==============================================================================
  19904. // Integration Tests with Server
  19905. //==============================================================================
  19906. class SSEIntegrationTest : public ::testing::Test {
  19907. protected:
  19908. void SetUp() override {
  19909. stop_server_.store(false);
  19910. events_.clear();
  19911. server_ = httplib::detail::make_unique<Server>();
  19912. setup_server();
  19913. start_server();
  19914. }
  19915. void TearDown() override {
  19916. stop_server_.store(true);
  19917. event_cv_.notify_all();
  19918. server_->stop();
  19919. if (server_thread_.joinable()) { server_thread_.join(); }
  19920. }
  19921. void setup_server() {
  19922. // Simple SSE endpoint
  19923. server_->Get("/events", [this](const Request &req, Response &res) {
  19924. auto last_id = req.get_header_value("Last-Event-ID");
  19925. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19926. res.set_chunked_content_provider(
  19927. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19928. std::unique_lock<std::mutex> lock(event_mutex_);
  19929. if (event_cv_.wait_for(
  19930. lock, std::chrono::milliseconds(200), [this] {
  19931. return !events_.empty() || stop_server_.load();
  19932. })) {
  19933. if (stop_server_.load()) { return false; }
  19934. if (!events_.empty()) {
  19935. std::string event = events_.front();
  19936. events_.erase(events_.begin());
  19937. sink.write(event.data(), event.size());
  19938. return true;
  19939. }
  19940. }
  19941. return !stop_server_.load();
  19942. });
  19943. });
  19944. // Endpoint that returns error
  19945. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19946. res.status = 500;
  19947. res.set_content("Internal Server Error", "text/plain");
  19948. });
  19949. // Endpoint for custom event types
  19950. server_->Get("/custom-events", [](const Request &, Response &res) {
  19951. res.set_chunked_content_provider(
  19952. "text/event-stream", [](size_t offset, DataSink &sink) {
  19953. if (offset == 0) {
  19954. std::string event = "event: update\ndata: updated\n\n"
  19955. "event: delete\ndata: deleted\n\n";
  19956. sink.write(event.data(), event.size());
  19957. }
  19958. return false; // End stream after sending
  19959. });
  19960. });
  19961. }
  19962. void start_server() {
  19963. port_ = server_->bind_to_any_port(HOST);
  19964. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19965. // Wait for server to start
  19966. while (!server_->is_running()) {
  19967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19968. }
  19969. }
  19970. int get_port() const { return port_; }
  19971. void send_event(const std::string &event) {
  19972. std::lock_guard<std::mutex> lock(event_mutex_);
  19973. events_.push_back(event);
  19974. event_cv_.notify_all();
  19975. }
  19976. std::unique_ptr<Server> server_;
  19977. std::thread server_thread_;
  19978. std::mutex event_mutex_;
  19979. std::condition_variable event_cv_;
  19980. std::vector<std::string> events_;
  19981. std::atomic<bool> stop_server_{false};
  19982. std::string last_received_event_id_;
  19983. int port_ = 0;
  19984. };
  19985. //==============================================================================
  19986. // SSE Parsing Tests
  19987. //==============================================================================
  19988. class SSEParsingTest : public SSEIntegrationTest {
  19989. protected:
  19990. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19991. // A trailing sentinel event tells when the whole stream has been parsed.
  19992. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19993. auto body = stream + "event: end\ndata: end\n\n";
  19994. server_->Get("/parse", [body](const Request &, Response &res) {
  19995. res.set_content(body, "text/event-stream");
  19996. });
  19997. return collect("/parse");
  19998. }
  19999. // Runs SSEClient against path until an "end" event arrives and returns the
  20000. // messages dispatched before it
  20001. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20002. Client client(HOST, get_port());
  20003. sse::SSEClient sse(client, path);
  20004. std::mutex mutex;
  20005. std::condition_variable cv;
  20006. std::vector<sse::SSEMessage> messages;
  20007. auto done = false;
  20008. sse.on_message([&](const sse::SSEMessage &msg) {
  20009. std::lock_guard<std::mutex> lock(mutex);
  20010. // Ignore a replay from a reconnect that races with stop()
  20011. if (!done) { messages.push_back(msg); }
  20012. });
  20013. sse.on_event("end", [&](const sse::SSEMessage &) {
  20014. std::lock_guard<std::mutex> lock(mutex);
  20015. done = true;
  20016. cv.notify_all();
  20017. });
  20018. sse.set_reconnect_interval(100);
  20019. sse.start_async();
  20020. {
  20021. std::unique_lock<std::mutex> lock(mutex);
  20022. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20023. }
  20024. sse.stop();
  20025. EXPECT_TRUE(done);
  20026. return messages;
  20027. }
  20028. };
  20029. TEST_F(SSEParsingTest, SingleLineData) {
  20030. auto msgs = parse("data: hello\n\n");
  20031. ASSERT_EQ(msgs.size(), 1u);
  20032. EXPECT_EQ(msgs[0].data, "hello");
  20033. EXPECT_EQ(msgs[0].event, "message");
  20034. }
  20035. TEST_F(SSEParsingTest, MultiLineData) {
  20036. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20037. ASSERT_EQ(msgs.size(), 1u);
  20038. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20039. }
  20040. TEST_F(SSEParsingTest, CustomEventType) {
  20041. auto msgs = parse("event: update\ndata: payload\n\n");
  20042. ASSERT_EQ(msgs.size(), 1u);
  20043. EXPECT_EQ(msgs[0].event, "update");
  20044. EXPECT_EQ(msgs[0].data, "payload");
  20045. }
  20046. TEST_F(SSEParsingTest, EventIdHandling) {
  20047. auto msgs = parse("id: 12345\ndata: test\n\n");
  20048. ASSERT_EQ(msgs.size(), 1u);
  20049. EXPECT_EQ(msgs[0].id, "12345");
  20050. }
  20051. TEST_F(SSEParsingTest, EmptyEventId) {
  20052. auto msgs = parse("id:\ndata: test\n\n");
  20053. ASSERT_EQ(msgs.size(), 1u);
  20054. EXPECT_EQ(msgs[0].id, "");
  20055. }
  20056. TEST_F(SSEParsingTest, CommentsIgnored) {
  20057. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20058. ASSERT_EQ(msgs.size(), 1u);
  20059. EXPECT_EQ(msgs[0].data, "hello");
  20060. EXPECT_EQ(msgs[0].event, "message");
  20061. }
  20062. TEST_F(SSEParsingTest, ColonInValue) {
  20063. auto msgs = parse("data: hello:world:test\n\n");
  20064. ASSERT_EQ(msgs.size(), 1u);
  20065. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20066. }
  20067. TEST_F(SSEParsingTest, FieldNameOnly) {
  20068. // A line without a colon is a field name with an empty value
  20069. auto msgs = parse("data\n\n");
  20070. ASSERT_EQ(msgs.size(), 1u);
  20071. EXPECT_EQ(msgs[0].data, "");
  20072. }
  20073. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20074. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20075. ASSERT_EQ(msgs.size(), 1u);
  20076. EXPECT_EQ(msgs[0].event, "update");
  20077. EXPECT_EQ(msgs[0].data, "hello");
  20078. }
  20079. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20080. auto msgs = parse("data\r\n\r\n");
  20081. ASSERT_EQ(msgs.size(), 1u);
  20082. EXPECT_EQ(msgs[0].data, "");
  20083. }
  20084. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20085. auto msgs = parse("event: update\rdata: hello\r\r");
  20086. ASSERT_EQ(msgs.size(), 1u);
  20087. EXPECT_EQ(msgs[0].event, "update");
  20088. EXPECT_EQ(msgs[0].data, "hello");
  20089. }
  20090. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20091. // Chunk boundaries fall inside every \r\n and right before the first one
  20092. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20093. "\n\r", "\nevent: end\ndata: end\n\n"};
  20094. server_->Get("/split", [chunks](const Request &, Response &res) {
  20095. auto i = std::make_shared<size_t>(0);
  20096. res.set_chunked_content_provider(
  20097. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20098. if (*i == chunks.size()) {
  20099. sink.done();
  20100. } else {
  20101. sink.write(chunks[*i].data(), chunks[*i].size());
  20102. (*i)++;
  20103. }
  20104. return true;
  20105. });
  20106. });
  20107. auto msgs = collect("/split");
  20108. ASSERT_EQ(msgs.size(), 1u);
  20109. EXPECT_EQ(msgs[0].event, "update");
  20110. EXPECT_EQ(msgs[0].data, "hello");
  20111. }
  20112. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20113. // Only a BOM at the start of the stream is ignored
  20114. auto msgs = parse("\xEF\xBB\xBF"
  20115. "data: first\n\n"
  20116. "\xEF\xBB\xBF"
  20117. "data: second\n\n");
  20118. ASSERT_EQ(msgs.size(), 1u);
  20119. EXPECT_EQ(msgs[0].data, "first");
  20120. }
  20121. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20122. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20123. ASSERT_EQ(msgs.size(), 1u);
  20124. EXPECT_EQ(msgs[0].data, "hello");
  20125. EXPECT_EQ(msgs[0].event, "message");
  20126. }
  20127. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20128. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20129. ASSERT_EQ(msgs.size(), 2u);
  20130. EXPECT_EQ(msgs[0].data, "hello");
  20131. EXPECT_EQ(msgs[1].data, "hello");
  20132. }
  20133. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20134. // An event without data is not dispatched, and its type must not leak
  20135. // into the next event
  20136. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20137. ASSERT_EQ(msgs.size(), 1u);
  20138. EXPECT_EQ(msgs[0].event, "message");
  20139. EXPECT_EQ(msgs[0].data, "hello");
  20140. }
  20141. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20142. // The first connection sends only an id; the second echoes back the
  20143. // Last-Event-ID it was reconnected with
  20144. std::atomic<int> connection_count{0};
  20145. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20146. if (connection_count++ == 0) {
  20147. res.set_content("id: 42\n\n", "text/event-stream");
  20148. } else {
  20149. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20150. "\n\nevent: end\ndata: end\n\n",
  20151. "text/event-stream");
  20152. }
  20153. });
  20154. auto msgs = collect("/id-only");
  20155. ASSERT_EQ(msgs.size(), 1u);
  20156. EXPECT_EQ(msgs[0].data, "42");
  20157. }
  20158. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20159. // The first connection sets an id and then clears it with an empty one; the
  20160. // second reports whether it was reconnected with a Last-Event-ID
  20161. std::atomic<int> connection_count{0};
  20162. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20163. if (connection_count++ == 0) {
  20164. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20165. "text/event-stream");
  20166. } else {
  20167. res.set_content(
  20168. std::string("data: ") +
  20169. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20170. "\n\nevent: end\ndata: end\n\n",
  20171. "text/event-stream");
  20172. }
  20173. });
  20174. auto msgs = collect("/id-clear");
  20175. ASSERT_EQ(msgs.size(), 3u);
  20176. EXPECT_EQ(msgs[0].id, "1");
  20177. EXPECT_EQ(msgs[1].id, "");
  20178. EXPECT_EQ(msgs[2].data, "not sent");
  20179. }
  20180. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20181. // The first connection sets an id and then sends ids that cannot be carried
  20182. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20183. // with
  20184. std::atomic<int> connection_count{0};
  20185. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20186. if (connection_count++ == 0) {
  20187. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20188. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20189. "text/event-stream");
  20190. } else {
  20191. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20192. "\n\nevent: end\ndata: end\n\n",
  20193. "text/event-stream");
  20194. }
  20195. });
  20196. auto msgs = collect("/id-unsendable");
  20197. ASSERT_EQ(msgs.size(), 1u);
  20198. EXPECT_EQ(msgs[0].data, "42");
  20199. }
  20200. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20201. auto msgs = parse("event: notification\nid: evt-42\n"
  20202. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20203. ASSERT_EQ(msgs.size(), 1u);
  20204. EXPECT_EQ(msgs[0].event, "notification");
  20205. EXPECT_EQ(msgs[0].id, "evt-42");
  20206. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20207. }
  20208. TEST(SSEMessageTest, Clear) {
  20209. sse::SSEMessage msg;
  20210. msg.event = "custom";
  20211. msg.data = "some data";
  20212. msg.id = "123";
  20213. msg.clear();
  20214. EXPECT_EQ(msg.event, "message");
  20215. EXPECT_EQ(msg.data, "");
  20216. EXPECT_EQ(msg.id, "");
  20217. }
  20218. //==============================================================================
  20219. // SSE Integration Tests
  20220. //==============================================================================
  20221. // Test: Successful connection and on_open callback
  20222. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20223. // Add a simple endpoint that sends one event and closes
  20224. server_->Get("/simple-event", [](const Request &, Response &res) {
  20225. res.set_chunked_content_provider(
  20226. "text/event-stream", [](size_t offset, DataSink &sink) {
  20227. if (offset == 0) {
  20228. std::string event = "data: hello\n\n";
  20229. sink.write(event.data(), event.size());
  20230. }
  20231. return false; // Close stream after sending
  20232. });
  20233. });
  20234. Client client("localhost", get_port());
  20235. sse::SSEClient sse(client, "/simple-event");
  20236. std::atomic<bool> open_called{false};
  20237. std::atomic<bool> message_received{false};
  20238. sse.on_open([&open_called]() { open_called.store(true); });
  20239. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20240. if (msg.data == "hello") { message_received.store(true); }
  20241. });
  20242. sse.set_reconnect_interval(100);
  20243. sse.set_max_reconnect_attempts(1);
  20244. // Start async
  20245. sse.start_async();
  20246. // Wait for message to be processed
  20247. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20248. sse.stop();
  20249. EXPECT_TRUE(open_called.load());
  20250. EXPECT_TRUE(message_received.load());
  20251. }
  20252. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20253. // A data line that never ends.
  20254. server_->Get("/endless-line", [](const Request &, Response &res) {
  20255. res.set_chunked_content_provider(
  20256. "text/event-stream", [](size_t offset, DataSink &sink) {
  20257. if (offset == 0) { sink.write("data: ", 6); }
  20258. std::string chunk(64 * 1024, 'A');
  20259. return sink.write(chunk.data(), chunk.size());
  20260. });
  20261. });
  20262. Client client("localhost", get_port());
  20263. // A stream that may run forever, so that only the event is bounded.
  20264. client.set_payload_max_length(0);
  20265. sse::SSEClient sse(client, "/endless-line");
  20266. std::atomic<bool> too_long{false};
  20267. sse.on_error([&](Error err) {
  20268. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20269. });
  20270. sse.set_max_reconnect_attempts(1);
  20271. sse.start_async();
  20272. for (int i = 0; i < 500 && !too_long; i++) {
  20273. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20274. }
  20275. sse.stop();
  20276. EXPECT_TRUE(too_long);
  20277. }
  20278. // Test: on_message callback
  20279. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20280. // Endpoint that sends multiple events then closes
  20281. server_->Get("/multi-event", [](const Request &, Response &res) {
  20282. res.set_chunked_content_provider(
  20283. "text/event-stream", [](size_t offset, DataSink &sink) {
  20284. if (offset == 0) {
  20285. std::string events = "data: message1\n\ndata: message2\n\n";
  20286. sink.write(events.data(), events.size());
  20287. }
  20288. return false;
  20289. });
  20290. });
  20291. Client client("localhost", get_port());
  20292. sse::SSEClient sse(client, "/multi-event");
  20293. std::vector<std::string> received_messages;
  20294. std::mutex messages_mutex;
  20295. sse.on_message([&](const sse::SSEMessage &msg) {
  20296. std::lock_guard<std::mutex> lock(messages_mutex);
  20297. received_messages.push_back(msg.data);
  20298. });
  20299. sse.set_reconnect_interval(100);
  20300. sse.set_max_reconnect_attempts(1);
  20301. sse.start_async();
  20302. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20303. sse.stop();
  20304. std::lock_guard<std::mutex> lock(messages_mutex);
  20305. EXPECT_GE(received_messages.size(), 2u);
  20306. if (received_messages.size() >= 2) {
  20307. EXPECT_EQ(received_messages[0], "message1");
  20308. EXPECT_EQ(received_messages[1], "message2");
  20309. }
  20310. }
  20311. // Test: on_event for specific types
  20312. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20313. Client client("localhost", get_port());
  20314. sse::SSEClient sse(client, "/custom-events");
  20315. std::atomic<bool> update_received{false};
  20316. std::atomic<bool> delete_received{false};
  20317. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20318. if (msg.data == "updated") { update_received.store(true); }
  20319. });
  20320. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20321. if (msg.data == "deleted") { delete_received.store(true); }
  20322. });
  20323. sse.set_max_reconnect_attempts(1);
  20324. sse.start_async();
  20325. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20326. sse.stop();
  20327. EXPECT_TRUE(update_received.load());
  20328. EXPECT_TRUE(delete_received.load());
  20329. }
  20330. // Test: on_error callback on connection failure
  20331. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20332. // Connect to a non-existent port
  20333. Client client("localhost", 59999);
  20334. sse::SSEClient sse(client, "/events");
  20335. std::atomic<bool> error_called{false};
  20336. Error received_error = Error::Success;
  20337. sse.on_error([&](Error err) {
  20338. error_called.store(true);
  20339. received_error = err;
  20340. });
  20341. sse.set_reconnect_interval(50);
  20342. sse.set_max_reconnect_attempts(1);
  20343. sse.start_async();
  20344. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20345. sse.stop();
  20346. EXPECT_TRUE(error_called.load());
  20347. EXPECT_NE(received_error, Error::Success);
  20348. }
  20349. // Test: Last-Event-ID header sent on reconnect
  20350. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20351. // Endpoint that sends event with ID
  20352. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20353. res.set_chunked_content_provider(
  20354. "text/event-stream", [](size_t offset, DataSink &sink) {
  20355. if (offset == 0) {
  20356. std::string event = "id: evt-123\ndata: test\n\n";
  20357. sink.write(event.data(), event.size());
  20358. }
  20359. return false;
  20360. });
  20361. });
  20362. Client client("localhost", get_port());
  20363. sse::SSEClient sse(client, "/event-with-id");
  20364. std::atomic<bool> id_received{false};
  20365. sse.on_message([&](const sse::SSEMessage &msg) {
  20366. if (!msg.id.empty()) { id_received.store(true); }
  20367. });
  20368. sse.set_reconnect_interval(100);
  20369. sse.set_max_reconnect_attempts(1);
  20370. sse.start_async();
  20371. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20372. sse.stop();
  20373. EXPECT_TRUE(id_received.load());
  20374. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20375. }
  20376. // Test: Manual stop
  20377. TEST_F(SSEIntegrationTest, ManualStop) {
  20378. // Endpoint that sends one event and stays open briefly
  20379. std::atomic<bool> handler_running{true};
  20380. server_->Get("/stay-open", [&handler_running](const Request &,
  20381. Response &res) {
  20382. res.set_chunked_content_provider(
  20383. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20384. if (offset == 0) {
  20385. std::string event = "data: connected\n\n";
  20386. sink.write(event.data(), event.size());
  20387. }
  20388. // Keep connection open while handler_running is true
  20389. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20390. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20391. }
  20392. return false;
  20393. });
  20394. });
  20395. Client client("localhost", get_port());
  20396. sse::SSEClient sse(client, "/stay-open");
  20397. std::atomic<bool> connected{false};
  20398. sse.on_open([&connected]() { connected.store(true); });
  20399. sse.set_reconnect_interval(100);
  20400. sse.set_max_reconnect_attempts(1);
  20401. sse.start_async();
  20402. // Wait for connection to establish
  20403. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20404. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20405. }
  20406. EXPECT_TRUE(connected.load());
  20407. EXPECT_TRUE(sse.is_connected());
  20408. // Signal handler to stop
  20409. handler_running.store(false);
  20410. // Stop SSE client
  20411. sse.stop();
  20412. EXPECT_FALSE(sse.is_connected());
  20413. }
  20414. // Test: SSEClient with custom headers
  20415. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20416. // Setup a server endpoint that checks for custom header
  20417. std::atomic<bool> header_received{false};
  20418. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20419. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20420. header_received.store(true);
  20421. }
  20422. res.set_chunked_content_provider("text/event-stream",
  20423. [](size_t, DataSink &) { return false; });
  20424. });
  20425. Client client("localhost", get_port());
  20426. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20427. sse::SSEClient sse(client, "/header-check", headers);
  20428. sse.set_max_reconnect_attempts(1);
  20429. sse.start_async();
  20430. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20431. sse.stop();
  20432. EXPECT_TRUE(header_received.load());
  20433. }
  20434. // Test: Reconnect interval configuration
  20435. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20436. Client client("localhost", get_port());
  20437. sse::SSEClient sse(client, "/events");
  20438. auto &result = sse.set_reconnect_interval(500);
  20439. // Builder pattern should return reference to self
  20440. EXPECT_EQ(&result, &sse);
  20441. }
  20442. // Test: Max reconnect attempts
  20443. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20444. // Connect to non-existent port to force reconnects
  20445. Client client("localhost", 59998);
  20446. sse::SSEClient sse(client, "/events");
  20447. std::atomic<int> error_count{0};
  20448. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20449. sse.set_reconnect_interval(50);
  20450. sse.set_max_reconnect_attempts(2);
  20451. auto start = std::chrono::steady_clock::now();
  20452. sse.start(); // Blocking call
  20453. auto end = std::chrono::steady_clock::now();
  20454. // Should have stopped after 2 failed attempts
  20455. EXPECT_GE(error_count.load(), 2);
  20456. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20457. auto duration =
  20458. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20459. #ifdef _WIN32
  20460. // Windows is much slower for socket connection failures
  20461. EXPECT_LT(duration.count(), 7000);
  20462. #else
  20463. EXPECT_LT(duration.count(), 1000);
  20464. #endif
  20465. }
  20466. // Test: Multi-line data in integration
  20467. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20468. // Endpoint with multi-line data
  20469. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20470. res.set_chunked_content_provider(
  20471. "text/event-stream", [](size_t offset, DataSink &sink) {
  20472. if (offset == 0) {
  20473. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20474. sink.write(event.data(), event.size());
  20475. }
  20476. return false;
  20477. });
  20478. });
  20479. Client client("localhost", get_port());
  20480. sse::SSEClient sse(client, "/multiline-data");
  20481. std::string received_data;
  20482. std::mutex data_mutex;
  20483. sse.on_message([&](const sse::SSEMessage &msg) {
  20484. std::lock_guard<std::mutex> lock(data_mutex);
  20485. received_data = msg.data;
  20486. });
  20487. sse.set_reconnect_interval(100);
  20488. sse.set_max_reconnect_attempts(1);
  20489. sse.start_async();
  20490. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20491. sse.stop();
  20492. std::lock_guard<std::mutex> lock(data_mutex);
  20493. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20494. }
  20495. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20496. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20497. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20498. DataSink &sink) {
  20499. if (offset == 0) {
  20500. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20501. sink.write(events.data(), events.size());
  20502. }
  20503. return false;
  20504. });
  20505. });
  20506. Client client("localhost", get_port());
  20507. sse::SSEClient sse(client, "/empty-data-lines");
  20508. std::mutex mutex;
  20509. std::condition_variable cv;
  20510. std::vector<std::string> received;
  20511. sse.on_message([&](const sse::SSEMessage &msg) {
  20512. std::lock_guard<std::mutex> lock(mutex);
  20513. received.push_back(msg.data);
  20514. cv.notify_all();
  20515. });
  20516. sse.set_max_reconnect_attempts(1);
  20517. sse.start_async();
  20518. {
  20519. std::unique_lock<std::mutex> lock(mutex);
  20520. cv.wait_for(lock, std::chrono::seconds(2),
  20521. [&] { return received.size() >= 3; });
  20522. }
  20523. sse.stop();
  20524. ASSERT_GE(received.size(), 3u);
  20525. EXPECT_EQ(received[0], "");
  20526. EXPECT_EQ(received[1], "\nhello");
  20527. EXPECT_EQ(received[2], "");
  20528. }
  20529. // Test: Auto-reconnect after server disconnection
  20530. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20531. std::atomic<int> connection_count{0};
  20532. std::atomic<int> message_count{0};
  20533. // Endpoint that sends one event and closes, forcing reconnect
  20534. server_->Get("/reconnect-test",
  20535. [&connection_count](const Request &, Response &res) {
  20536. connection_count.fetch_add(1);
  20537. res.set_chunked_content_provider(
  20538. "text/event-stream", [](size_t offset, DataSink &sink) {
  20539. if (offset == 0) {
  20540. std::string event = "data: hello\n\n";
  20541. sink.write(event.data(), event.size());
  20542. }
  20543. return false; // Close connection after sending
  20544. });
  20545. });
  20546. Client client("localhost", get_port());
  20547. sse::SSEClient sse(client, "/reconnect-test");
  20548. sse.on_message([&message_count](const sse::SSEMessage &) {
  20549. message_count.fetch_add(1);
  20550. });
  20551. sse.set_reconnect_interval(100);
  20552. sse.set_max_reconnect_attempts(3);
  20553. sse.start_async();
  20554. // Wait long enough for multiple reconnects
  20555. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20556. sse.stop();
  20557. // Should have connected multiple times (initial + reconnects)
  20558. EXPECT_GE(connection_count.load(), 2);
  20559. // Should have received messages from multiple connections
  20560. EXPECT_GE(message_count.load(), 2);
  20561. }
  20562. // Test: A retry field that is not all ASCII digits is ignored
  20563. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20564. std::atomic<int> connection_count{0};
  20565. server_->Get("/bad-retry",
  20566. [&connection_count](const Request &, Response &res) {
  20567. connection_count.fetch_add(1);
  20568. res.set_chunked_content_provider(
  20569. "text/event-stream", [](size_t offset, DataSink &sink) {
  20570. if (offset == 0) {
  20571. std::string event = "retry: -1\ndata: hello\n\n";
  20572. sink.write(event.data(), event.size());
  20573. }
  20574. return false;
  20575. });
  20576. });
  20577. Client client("localhost", get_port());
  20578. sse::SSEClient sse(client, "/bad-retry");
  20579. sse.set_reconnect_interval(10000);
  20580. sse.start_async();
  20581. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20582. sse.stop();
  20583. EXPECT_EQ(connection_count.load(), 1);
  20584. }
  20585. // Test: A retry field of all ASCII digits sets the reconnection time
  20586. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20587. std::mutex mutex;
  20588. std::condition_variable cv;
  20589. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20590. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20591. {
  20592. std::lock_guard<std::mutex> lock(mutex);
  20593. connected_at.push_back(std::chrono::steady_clock::now());
  20594. cv.notify_all();
  20595. }
  20596. res.set_chunked_content_provider(
  20597. "text/event-stream", [](size_t offset, DataSink &sink) {
  20598. if (offset == 0) {
  20599. std::string event = "retry: 0\ndata: hello\n\n";
  20600. sink.write(event.data(), event.size());
  20601. }
  20602. return false;
  20603. });
  20604. });
  20605. Client client("localhost", get_port());
  20606. sse::SSEClient sse(client, "/zero-retry");
  20607. sse.set_reconnect_interval(10000);
  20608. sse.start_async();
  20609. {
  20610. std::unique_lock<std::mutex> lock(mutex);
  20611. cv.wait_for(lock, std::chrono::seconds(5),
  20612. [&] { return connected_at.size() >= 2; });
  20613. }
  20614. sse.stop();
  20615. // The server-supplied interval is applied, but never below 100ms, so
  20616. // "retry: 0" does not cause a busy reconnect loop
  20617. std::lock_guard<std::mutex> lock(mutex);
  20618. ASSERT_GE(connected_at.size(), 2u);
  20619. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20620. connected_at[1] - connected_at[0])
  20621. .count();
  20622. EXPECT_GE(interval_ms, 100);
  20623. }
  20624. // Test: Last-Event-ID sent on reconnect
  20625. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20626. std::atomic<int> connection_count{0};
  20627. std::vector<std::string> received_last_event_ids;
  20628. std::mutex id_mutex;
  20629. // Endpoint that checks Last-Event-ID header and sends event with ID
  20630. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20631. int conn = connection_count.fetch_add(1);
  20632. // Capture the Last-Event-ID header from each connection
  20633. {
  20634. std::lock_guard<std::mutex> lock(id_mutex);
  20635. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20636. }
  20637. res.set_chunked_content_provider(
  20638. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20639. if (offset == 0) {
  20640. std::string event =
  20641. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20642. sink.write(event.data(), event.size());
  20643. }
  20644. return false;
  20645. });
  20646. });
  20647. Client client("localhost", get_port());
  20648. sse::SSEClient sse(client, "/reconnect-with-id");
  20649. sse.set_reconnect_interval(100);
  20650. sse.set_max_reconnect_attempts(3);
  20651. sse.start_async();
  20652. // Wait for at least 2 connections
  20653. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20654. sse.stop();
  20655. // Verify behavior
  20656. std::lock_guard<std::mutex> lock(id_mutex);
  20657. EXPECT_GE(received_last_event_ids.size(), 2u);
  20658. // First connection should have no Last-Event-ID
  20659. if (!received_last_event_ids.empty()) {
  20660. EXPECT_EQ(received_last_event_ids[0], "");
  20661. }
  20662. // Second connection should have Last-Event-ID from first connection
  20663. if (received_last_event_ids.size() >= 2) {
  20664. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20665. }
  20666. }
  20667. // Test: set_headers updates headers used on reconnect
  20668. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20669. std::vector<std::string> received_tokens;
  20670. std::mutex token_mutex;
  20671. // Endpoint that captures Authorization header
  20672. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20673. {
  20674. std::lock_guard<std::mutex> lock(token_mutex);
  20675. received_tokens.push_back(req.get_header_value("Authorization"));
  20676. }
  20677. res.set_chunked_content_provider(
  20678. "text/event-stream", [](size_t offset, DataSink &sink) {
  20679. if (offset == 0) {
  20680. std::string event = "data: hello\n\n";
  20681. sink.write(event.data(), event.size());
  20682. }
  20683. return false; // Close connection to trigger reconnect
  20684. });
  20685. });
  20686. Client client("localhost", get_port());
  20687. Headers headers = {{"Authorization", "Bearer old-token"}};
  20688. sse::SSEClient sse(client, "/auth-check", headers);
  20689. // Update headers on each successful connection
  20690. sse.on_open(
  20691. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20692. sse.set_reconnect_interval(100);
  20693. sse.set_max_reconnect_attempts(3);
  20694. sse.start_async();
  20695. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20696. sse.stop();
  20697. std::lock_guard<std::mutex> lock(token_mutex);
  20698. ASSERT_GE(received_tokens.size(), 2u);
  20699. // First connection uses original header
  20700. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20701. // Second connection uses updated header from set_headers
  20702. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20703. }
  20704. // Test: 401 allows reconnection (so on_error can refresh headers)
  20705. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20706. std::atomic<int> connection_count{0};
  20707. // Endpoint: returns 401 on first attempt, 200 on second
  20708. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20709. int conn = connection_count.fetch_add(1);
  20710. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20711. res.status = StatusCode::Unauthorized_401;
  20712. res.set_content("Unauthorized", "text/plain");
  20713. return;
  20714. }
  20715. res.set_chunked_content_provider(
  20716. "text/event-stream", [](size_t offset, DataSink &sink) {
  20717. if (offset == 0) {
  20718. std::string event = "data: authenticated\n\n";
  20719. sink.write(event.data(), event.size());
  20720. }
  20721. return false;
  20722. });
  20723. });
  20724. Client client("localhost", get_port());
  20725. Headers headers = {{"Authorization", "Bearer expired"}};
  20726. sse::SSEClient sse(client, "/auth-retry", headers);
  20727. std::atomic<bool> message_received{false};
  20728. // Refresh token on error
  20729. sse.on_error(
  20730. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20731. sse.on_message([&](const sse::SSEMessage &msg) {
  20732. if (msg.data == "authenticated") { message_received.store(true); }
  20733. });
  20734. sse.set_reconnect_interval(100);
  20735. sse.set_max_reconnect_attempts(3);
  20736. sse.start_async();
  20737. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20738. sse.stop();
  20739. // Should have reconnected after 401 and succeeded with new token
  20740. EXPECT_GE(connection_count.load(), 2);
  20741. EXPECT_TRUE(message_received.load());
  20742. }
  20743. TEST(Issue2318Test, EmptyHostString) {
  20744. {
  20745. httplib::Client cli_empty("", PORT);
  20746. auto res = cli_empty.Get("/");
  20747. ASSERT_FALSE(res);
  20748. EXPECT_EQ(httplib::Error::Connection, res.error());
  20749. }
  20750. {
  20751. httplib::Client cli(" ", PORT);
  20752. auto res = cli.Get("/");
  20753. ASSERT_FALSE(res);
  20754. EXPECT_EQ(httplib::Error::Connection, res.error());
  20755. }
  20756. }
  20757. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20758. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20759. Server svr;
  20760. // Set a small payload limit (1KB)
  20761. svr.set_payload_max_length(1024);
  20762. svr.Post("/test", [&](const Request &req, Response &res) {
  20763. res.set_content("Body size: " + std::to_string(req.body.size()),
  20764. "text/plain");
  20765. });
  20766. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20767. auto se = detail::scope_exit([&] {
  20768. svr.stop();
  20769. listen_thread.join();
  20770. });
  20771. svr.wait_until_ready();
  20772. // Create data that compresses well but exceeds limit when decompressed
  20773. // 8KB of repeated null bytes compresses to a very small size
  20774. std::string original_data(8 * 1024, '\0');
  20775. // Compress the data using gzip
  20776. std::string compressed_data;
  20777. detail::gzip_compressor compressor;
  20778. compressor.compress(original_data.data(), original_data.size(), true,
  20779. [&](const char *data, size_t size) {
  20780. compressed_data.append(data, size);
  20781. return true;
  20782. });
  20783. // Verify compression worked (compressed should be much smaller)
  20784. ASSERT_LT(compressed_data.size(), original_data.size());
  20785. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20786. // Send compressed data with Content-Encoding: gzip
  20787. Client cli(HOST, PORT);
  20788. Headers headers = {{"Content-Encoding", "gzip"}};
  20789. auto res =
  20790. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20791. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20793. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20794. }
  20795. #endif
  20796. // ============================================================================
  20797. // OpenSSL-Specific Tests
  20798. // ============================================================================
  20799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20800. X509 *readCertificate(const std::string &strFileName) {
  20801. std::ifstream inStream(strFileName);
  20802. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20803. std::istreambuf_iterator<char>());
  20804. if (strCertPEM.empty()) return (nullptr);
  20805. BIO *pbCert = BIO_new(BIO_s_mem());
  20806. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20807. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20808. BIO_free(pbCert);
  20809. return (pCert);
  20810. }
  20811. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20812. std::ifstream inStream(strFileName);
  20813. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20814. std::istreambuf_iterator<char>());
  20815. if (strPrivateKeyPEM.empty()) return (nullptr);
  20816. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20817. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20818. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20819. BIO_free(pbPrivKey);
  20820. return (pPrivateKey);
  20821. }
  20822. TEST(BindServerTest, UpdateCerts) {
  20823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20824. int port = svr.bind_to_any_port("0.0.0.0");
  20825. ASSERT_TRUE(svr.is_valid());
  20826. ASSERT_TRUE(port > 0);
  20827. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20828. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20829. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20830. ASSERT_TRUE(cert != nullptr);
  20831. ASSERT_TRUE(ca_cert != nullptr);
  20832. ASSERT_TRUE(key != nullptr);
  20833. X509_STORE *cert_store = X509_STORE_new();
  20834. X509_STORE_add_cert(cert_store, ca_cert);
  20835. // svr.update_certs(cert, key, cert_store); // deprecated
  20836. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20837. CLIENT_CA_CERT_FILE);
  20838. ASSERT_TRUE(svr.is_valid());
  20839. svr.stop();
  20840. X509_STORE_free(cert_store);
  20841. X509_free(cert);
  20842. X509_free(ca_cert);
  20843. EVP_PKEY_free(key);
  20844. }
  20845. // Test that update_certs() updates client CA list correctly
  20846. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20847. // Start with file-based constructor
  20848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20849. ASSERT_TRUE(svr.is_valid());
  20850. // Initially no client CA list should be set
  20851. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20852. ASSERT_TRUE(ssl_ctx != nullptr);
  20853. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20854. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20855. EXPECT_EQ(0, count_before);
  20856. // Now update with client CA (PEM string)
  20857. std::string cert_pem, key_pem, ca_pem;
  20858. read_file(SERVER_CERT_FILE, cert_pem);
  20859. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20860. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20861. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20862. ASSERT_TRUE(svr.is_valid());
  20863. // Now client CA list should be set
  20864. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20865. ASSERT_TRUE(ca_list_after != nullptr);
  20866. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20867. }
  20868. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20869. // Test that the file-path SSLServer constructor properly sets the client CA
  20870. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20872. ASSERT_TRUE(svr.is_valid());
  20873. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20874. ASSERT_TRUE(ssl_ctx != nullptr);
  20875. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20876. ASSERT_TRUE(ca_list != nullptr);
  20877. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20878. }
  20879. #endif
  20880. // ============================================================================
  20881. // MbedTLS-Specific Tests
  20882. // ============================================================================
  20883. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20884. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20885. using namespace httplib::tls;
  20886. // Track if callback was invoked
  20887. bool callback_invoked = false;
  20888. // The callback receives void* ctx which is actually MbedTlsContext*
  20889. // We can access the mbedtls_ssl_config via the context
  20890. auto setup_callback = [&callback_invoked](void *ctx) {
  20891. callback_invoked = true;
  20892. // Cast to MbedTlsContext* to access the ssl config
  20893. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20894. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20895. // Use static variables to hold certificate data (simplified for test)
  20896. static mbedtls_x509_crt own_cert;
  20897. static mbedtls_pk_context own_key;
  20898. static mbedtls_x509_crt ca_chain;
  20899. static bool initialized = false;
  20900. if (!initialized) {
  20901. mbedtls_x509_crt_init(&own_cert);
  20902. mbedtls_pk_init(&own_key);
  20903. mbedtls_x509_crt_init(&ca_chain);
  20904. // Load server certificate
  20905. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20906. return false;
  20907. }
  20908. // Load server private key.
  20909. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20910. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20911. #if MBEDTLS_VERSION_MAJOR == 3
  20912. ,
  20913. mbedtls_ctr_drbg_random, nullptr
  20914. #endif
  20915. ) != 0) {
  20916. return false;
  20917. }
  20918. // Load CA chain for client verification
  20919. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20920. return false;
  20921. }
  20922. initialized = true;
  20923. }
  20924. // Configure the SSL config
  20925. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20926. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20927. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20928. // Set minimum TLS version using mbedTLS native API
  20929. #if MBEDTLS_VERSION_MAJOR >= 3
  20930. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20931. #else
  20932. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20933. MBEDTLS_SSL_MINOR_VERSION_3);
  20934. #endif
  20935. return true;
  20936. };
  20937. SSLServer svr(setup_callback);
  20938. ASSERT_TRUE(svr.is_valid());
  20939. ASSERT_TRUE(callback_invoked);
  20940. svr.Get("/test", [&](const Request &req, Response &res) {
  20941. res.set_content("test", "text/plain");
  20942. auto cert = req.peer_cert();
  20943. ASSERT_TRUE(static_cast<bool>(cert));
  20944. auto common_name = cert.subject_cn();
  20945. EXPECT_EQ("Common Name", common_name);
  20946. });
  20947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20948. auto se = detail::scope_exit([&] {
  20949. svr.stop();
  20950. t.join();
  20951. ASSERT_FALSE(svr.is_running());
  20952. });
  20953. svr.wait_until_ready();
  20954. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20955. cli.enable_server_certificate_verification(false);
  20956. cli.set_connection_timeout(30);
  20957. auto res = cli.Get("/test");
  20958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20959. ASSERT_EQ(StatusCode::OK_200, res->status);
  20960. }
  20961. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20962. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20963. // keep-alive SSL session, which reads through that config in
  20964. // mbedtls_ssl_close_notify.
  20965. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20967. ASSERT_TRUE(svr.is_valid());
  20968. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20969. res.set_content("test", "text/plain");
  20970. });
  20971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20972. auto se = detail::scope_exit([&] {
  20973. svr.stop();
  20974. t.join();
  20975. ASSERT_FALSE(svr.is_running());
  20976. });
  20977. svr.wait_until_ready();
  20978. {
  20979. SSLClient cli(HOST, PORT);
  20980. cli.enable_server_certificate_verification(false);
  20981. cli.set_keep_alive(true);
  20982. auto res = cli.Get("/test");
  20983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20984. ASSERT_EQ(StatusCode::OK_200, res->status);
  20985. // cli is destructed here with the keep-alive SSL session still open.
  20986. }
  20987. }
  20988. #endif
  20989. // WebSocket Tests
  20990. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20991. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20992. // defining the meaning of these bits has been negotiated.
  20993. auto make_frame = [](uint8_t first_byte) {
  20994. std::string frame;
  20995. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20996. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20997. frame += "Hello";
  20998. return frame;
  20999. };
  21000. // RSV1 set (0x40)
  21001. {
  21002. detail::BufferStream strm;
  21003. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21004. ws::Opcode opcode;
  21005. std::string payload;
  21006. bool fin;
  21007. EXPECT_EQ(
  21008. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21009. ws::impl::FrameRead::Fail);
  21010. }
  21011. // RSV2 set (0x20)
  21012. {
  21013. detail::BufferStream strm;
  21014. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21015. ws::Opcode opcode;
  21016. std::string payload;
  21017. bool fin;
  21018. EXPECT_EQ(
  21019. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21020. ws::impl::FrameRead::Fail);
  21021. }
  21022. // RSV3 set (0x10)
  21023. {
  21024. detail::BufferStream strm;
  21025. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21026. ws::Opcode opcode;
  21027. std::string payload;
  21028. bool fin;
  21029. EXPECT_EQ(
  21030. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21031. ws::impl::FrameRead::Fail);
  21032. }
  21033. // No RSV bits set - should succeed
  21034. {
  21035. detail::BufferStream strm;
  21036. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21037. ws::Opcode opcode;
  21038. std::string payload;
  21039. bool fin;
  21040. EXPECT_EQ(
  21041. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21042. ws::impl::FrameRead::Ok);
  21043. EXPECT_EQ(ws::Opcode::Text, opcode);
  21044. EXPECT_EQ("Hello", payload);
  21045. EXPECT_TRUE(fin);
  21046. }
  21047. }
  21048. TEST(WebSocketTest, ControlFrameValidation) {
  21049. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21050. // payload length <= 125.
  21051. // Ping with FIN=0 - must be rejected
  21052. {
  21053. detail::BufferStream strm;
  21054. std::string frame;
  21055. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21056. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21057. strm.write(frame.data(), frame.size());
  21058. ws::Opcode opcode;
  21059. std::string payload;
  21060. bool fin;
  21061. EXPECT_EQ(
  21062. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21063. ws::impl::FrameRead::Fail);
  21064. }
  21065. // Close with FIN=0 - must be rejected
  21066. {
  21067. detail::BufferStream strm;
  21068. std::string frame;
  21069. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21070. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21071. strm.write(frame.data(), frame.size());
  21072. ws::Opcode opcode;
  21073. std::string payload;
  21074. bool fin;
  21075. EXPECT_EQ(
  21076. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21077. ws::impl::FrameRead::Fail);
  21078. }
  21079. // Ping with payload_len=126 (extended length) - must be rejected
  21080. {
  21081. detail::BufferStream strm;
  21082. std::string frame;
  21083. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21084. frame += static_cast<char>(126); // payload_len=126 (>125)
  21085. frame += static_cast<char>(0x00); // extended length high byte
  21086. frame += static_cast<char>(126); // extended length low byte
  21087. frame += std::string(126, 'x');
  21088. strm.write(frame.data(), frame.size());
  21089. ws::Opcode opcode;
  21090. std::string payload;
  21091. bool fin;
  21092. EXPECT_EQ(
  21093. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21094. ws::impl::FrameRead::Fail);
  21095. }
  21096. // Ping with FIN=1 and payload_len=125 - should succeed
  21097. {
  21098. detail::BufferStream strm;
  21099. std::string frame;
  21100. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21101. frame += static_cast<char>(125); // payload_len=125
  21102. frame += std::string(125, 'x');
  21103. strm.write(frame.data(), frame.size());
  21104. ws::Opcode opcode;
  21105. std::string payload;
  21106. bool fin;
  21107. EXPECT_EQ(
  21108. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21109. ws::impl::FrameRead::Ok);
  21110. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21111. EXPECT_EQ(125u, payload.size());
  21112. EXPECT_TRUE(fin);
  21113. }
  21114. }
  21115. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21116. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21117. // length MUST be 0.
  21118. // MSB set - must be rejected
  21119. {
  21120. detail::BufferStream strm;
  21121. std::string frame;
  21122. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21123. frame += static_cast<char>(127); // 64-bit extended length
  21124. frame += static_cast<char>(0x80); // MSB set (invalid)
  21125. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21126. strm.write(frame.data(), frame.size());
  21127. ws::Opcode opcode;
  21128. std::string payload;
  21129. bool fin;
  21130. EXPECT_EQ(
  21131. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21132. ws::impl::FrameRead::Fail);
  21133. }
  21134. // MSB clear - should pass length parsing (will be rejected by max_len,
  21135. // but that's a different check; use a small length to verify)
  21136. {
  21137. detail::BufferStream strm;
  21138. std::string frame;
  21139. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21140. frame += static_cast<char>(127); // 64-bit extended length
  21141. frame += std::string(7, '\0'); // high bytes = 0
  21142. frame += static_cast<char>(0x03); // length = 3
  21143. frame += "abc";
  21144. strm.write(frame.data(), frame.size());
  21145. ws::Opcode opcode;
  21146. std::string payload;
  21147. bool fin;
  21148. EXPECT_EQ(
  21149. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21150. ws::impl::FrameRead::Ok);
  21151. EXPECT_EQ(ws::Opcode::Text, opcode);
  21152. EXPECT_EQ("abc", payload);
  21153. }
  21154. }
  21155. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21156. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21157. // Valid UTF-8
  21158. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21159. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21160. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21161. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21162. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21163. // Invalid UTF-8
  21164. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21165. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21166. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21167. EXPECT_FALSE(
  21168. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21169. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21170. }
  21171. TEST(WebSocketTest, ConnectAndDisconnect) {
  21172. Server svr;
  21173. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21174. std::string msg;
  21175. while (ws.read(msg)) {}
  21176. });
  21177. auto port = svr.bind_to_any_port(HOST);
  21178. std::thread t([&]() { svr.listen_after_bind(); });
  21179. svr.wait_until_ready();
  21180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21181. auto res = client.connect();
  21182. ASSERT_TRUE(res);
  21183. EXPECT_EQ(Error::Success, res.error());
  21184. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21185. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21186. EXPECT_TRUE(client.is_open());
  21187. client.close();
  21188. EXPECT_FALSE(client.is_open());
  21189. svr.stop();
  21190. t.join();
  21191. }
  21192. TEST(WebSocketTest, ValidURL) {
  21193. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21194. EXPECT_TRUE(ws1.is_valid());
  21195. ws::WebSocketClient ws2("ws://example.com/path");
  21196. EXPECT_TRUE(ws2.is_valid());
  21197. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21198. EXPECT_TRUE(ws3.is_valid());
  21199. #ifdef CPPHTTPLIB_SSL_ENABLED
  21200. ws::WebSocketClient wss1("wss://example.com/path");
  21201. EXPECT_TRUE(wss1.is_valid());
  21202. ws::WebSocketClient wss2("wss://example.com:443/path");
  21203. EXPECT_TRUE(wss2.is_valid());
  21204. #endif
  21205. }
  21206. TEST(WebSocketTest, InvalidURL) {
  21207. // No scheme
  21208. ws::WebSocketClient ws1("localhost:8080/path");
  21209. EXPECT_FALSE(ws1.is_valid());
  21210. // No path
  21211. ws::WebSocketClient ws2("ws://localhost:8080");
  21212. EXPECT_FALSE(ws2.is_valid());
  21213. // Empty string
  21214. ws::WebSocketClient ws3("");
  21215. EXPECT_FALSE(ws3.is_valid());
  21216. // Missing host
  21217. ws::WebSocketClient ws4("ws://:8080/path");
  21218. EXPECT_FALSE(ws4.is_valid());
  21219. // Port number overflow — should not crash
  21220. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21221. EXPECT_FALSE(ws5.is_valid());
  21222. // Port out of range
  21223. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21224. EXPECT_FALSE(ws6.is_valid());
  21225. }
  21226. TEST(WebSocketTest, UnsupportedScheme) {
  21227. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21228. ws::WebSocketClient ws1("http://localhost:8080/path");
  21229. EXPECT_FALSE(ws1.is_valid());
  21230. ws::WebSocketClient ws2("https://localhost:8080/path");
  21231. EXPECT_FALSE(ws2.is_valid());
  21232. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21233. EXPECT_FALSE(ws3.is_valid());
  21234. #else
  21235. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21236. std::invalid_argument);
  21237. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21238. std::invalid_argument);
  21239. #endif
  21240. }
  21241. TEST(WebSocketTest, ConnectWhenInvalid) {
  21242. ws::WebSocketClient ws("not a valid url");
  21243. EXPECT_FALSE(ws.is_valid());
  21244. auto res = ws.connect();
  21245. EXPECT_FALSE(res);
  21246. EXPECT_EQ(Error::Connection, res.error());
  21247. EXPECT_EQ(-1, res.status());
  21248. }
  21249. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21250. // Grab a port that is free, then close it again so nothing listens there
  21251. Server svr;
  21252. auto port = svr.bind_to_any_port(HOST);
  21253. svr.stop();
  21254. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21255. auto res = client.connect();
  21256. ASSERT_FALSE(res);
  21257. EXPECT_EQ(Error::Connection, res.error());
  21258. EXPECT_EQ(-1, res.status());
  21259. }
  21260. TEST(WebSocketTest, DefaultPort) {
  21261. ws::WebSocketClient ws1("ws://example.com/path");
  21262. EXPECT_TRUE(ws1.is_valid());
  21263. // ws:// defaults to port 80 (verified by successful parse)
  21264. #ifdef CPPHTTPLIB_SSL_ENABLED
  21265. ws::WebSocketClient ws2("wss://example.com/path");
  21266. EXPECT_TRUE(ws2.is_valid());
  21267. // wss:// defaults to port 443 (verified by successful parse)
  21268. #endif
  21269. }
  21270. TEST(WebSocketTest, IPv6LiteralAddress) {
  21271. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21272. EXPECT_TRUE(ws1.is_valid());
  21273. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21274. EXPECT_TRUE(ws2.is_valid());
  21275. }
  21276. TEST(WebSocketTest, ComplexPath) {
  21277. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21278. EXPECT_TRUE(ws1.is_valid());
  21279. ws::WebSocketClient ws2("ws://localhost:8080/");
  21280. EXPECT_TRUE(ws2.is_valid());
  21281. }
  21282. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21283. Server svr;
  21284. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21285. std::string msg;
  21286. while (ws.read(msg)) {}
  21287. });
  21288. auto port = svr.bind_to_any_port(HOST);
  21289. std::thread t([&]() { svr.listen_after_bind(); });
  21290. svr.wait_until_ready();
  21291. auto another_host = "example.com";
  21292. auto wrong_ip = "192.0.2.1";
  21293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21294. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21295. ASSERT_TRUE(client.connect());
  21296. EXPECT_TRUE(client.is_open());
  21297. client.close();
  21298. svr.stop();
  21299. t.join();
  21300. }
  21301. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21302. Server svr;
  21303. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21304. std::string msg;
  21305. while (ws.read(msg)) {}
  21306. });
  21307. auto port = svr.bind_to_any_port(HOST);
  21308. std::thread t([&]() { svr.listen_after_bind(); });
  21309. svr.wait_until_ready();
  21310. auto wrong_ip = "192.0.2.1";
  21311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21312. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21313. client.set_connection_timeout(1);
  21314. client.set_read_timeout(1);
  21315. client.set_write_timeout(1);
  21316. EXPECT_FALSE(client.connect());
  21317. EXPECT_FALSE(client.is_open());
  21318. svr.stop();
  21319. t.join();
  21320. }
  21321. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21322. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21323. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21324. // (RFC 6761) is only a map key and the Host header value.
  21325. auto host = "target.invalid";
  21326. Server svr;
  21327. std::string received_host;
  21328. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21329. received_host = req.get_header_value("Host");
  21330. std::string msg;
  21331. while (ws.read(msg)) {}
  21332. });
  21333. auto port = svr.bind_to_any_port(HOST);
  21334. std::thread t([&]() { svr.listen_after_bind(); });
  21335. // ASSERT_* below returns from the test body, which would leave t joinable
  21336. // and make ~thread call std::terminate.
  21337. auto se = detail::scope_exit([&] {
  21338. svr.stop();
  21339. if (t.joinable()) { t.join(); }
  21340. });
  21341. svr.wait_until_ready();
  21342. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21343. std::to_string(port) + "/ws");
  21344. client.set_hostname_addr_map({{host, HOST}});
  21345. ASSERT_TRUE(client.connect());
  21346. EXPECT_TRUE(client.is_open());
  21347. client.close();
  21348. svr.stop();
  21349. t.join();
  21350. // The mapping only redirects the connection; the identity stays host_.
  21351. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21352. }
  21353. class WebSocketIntegrationTest : public ::testing::Test {
  21354. protected:
  21355. void SetUp() override {
  21356. server_ = httplib::detail::make_unique<Server>();
  21357. setup_server();
  21358. start_server();
  21359. }
  21360. void TearDown() override {
  21361. server_->stop();
  21362. if (server_thread_.joinable()) { server_thread_.join(); }
  21363. }
  21364. void setup_server() {
  21365. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21366. std::string msg;
  21367. ws::ReadResult ret;
  21368. while ((ret = ws.read(msg))) {
  21369. if (ret == ws::Binary) {
  21370. ws.send(msg.data(), msg.size());
  21371. } else {
  21372. ws.send(msg);
  21373. }
  21374. }
  21375. });
  21376. server_->WebSocket("/ws-echo-string",
  21377. [](const Request &, ws::WebSocket &ws) {
  21378. std::string msg;
  21379. while (ws.read(msg)) {
  21380. ws.send("echo: " + msg);
  21381. }
  21382. });
  21383. server_->WebSocket(
  21384. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21385. // Echo back request metadata
  21386. ws.send("path:" + req.path);
  21387. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21388. std::string msg;
  21389. while (ws.read(msg)) {}
  21390. });
  21391. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21392. std::string msg;
  21393. ws.read(msg); // wait for a message
  21394. ws.close();
  21395. });
  21396. server_->WebSocket("/ws-close-status",
  21397. [](const Request &, ws::WebSocket &ws) {
  21398. std::string msg;
  21399. ws.read(msg); // wait for a message
  21400. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21401. });
  21402. server_->WebSocket(
  21403. "/ws-subprotocol",
  21404. [](const Request &, ws::WebSocket &ws) {
  21405. std::string msg;
  21406. while (ws.read(msg)) {
  21407. ws.send(msg);
  21408. }
  21409. },
  21410. [](const std::vector<std::string> &protocols) -> std::string {
  21411. for (const auto &p : protocols) {
  21412. if (p == "graphql-ws") { return p; }
  21413. }
  21414. return "";
  21415. });
  21416. server_->WebSocket(
  21417. "/ws-subprotocol-unoffered",
  21418. [](const Request &, ws::WebSocket &ws) {
  21419. std::string msg;
  21420. while (ws.read(msg)) {
  21421. ws.send(msg);
  21422. }
  21423. },
  21424. [](const std::vector<std::string> &) -> std::string {
  21425. return "admin";
  21426. });
  21427. }
  21428. void start_server() {
  21429. port_ = server_->bind_to_any_port(HOST);
  21430. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21431. server_->wait_until_ready();
  21432. }
  21433. std::unique_ptr<Server> server_;
  21434. std::thread server_thread_;
  21435. int port_ = 0;
  21436. };
  21437. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21439. "/ws-echo");
  21440. ASSERT_TRUE(client.connect());
  21441. ASSERT_TRUE(client.is_open());
  21442. ASSERT_TRUE(client.send("Hello WebSocket"));
  21443. std::string msg;
  21444. EXPECT_EQ(ws::Text, client.read(msg));
  21445. EXPECT_EQ("Hello WebSocket", msg);
  21446. client.close();
  21447. }
  21448. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21449. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21450. "/ws-echo");
  21451. ASSERT_TRUE(client.connect());
  21452. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21453. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21454. std::string msg;
  21455. EXPECT_EQ(ws::Binary, client.read(msg));
  21456. EXPECT_EQ(binary_data, msg);
  21457. client.close();
  21458. }
  21459. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21460. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21461. "/ws-echo");
  21462. ASSERT_TRUE(client.connect());
  21463. for (int i = 0; i < 10; i++) {
  21464. auto text = "message " + std::to_string(i);
  21465. ASSERT_TRUE(client.send(text));
  21466. std::string msg;
  21467. ASSERT_TRUE(client.read(msg));
  21468. EXPECT_EQ(text, msg);
  21469. }
  21470. client.close();
  21471. }
  21472. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21474. "/ws-close");
  21475. ASSERT_TRUE(client.connect());
  21476. // Send a message to trigger the server to close
  21477. ASSERT_TRUE(client.send("trigger close"));
  21478. // The server will close, so read should return false
  21479. std::string msg;
  21480. EXPECT_FALSE(client.read(msg));
  21481. EXPECT_FALSE(client.is_open());
  21482. }
  21483. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21484. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21485. "/ws-echo");
  21486. ASSERT_TRUE(client.connect());
  21487. // 128KB message
  21488. std::string large_data(128 * 1024, 'X');
  21489. ASSERT_TRUE(client.send(large_data));
  21490. std::string msg;
  21491. ASSERT_TRUE(client.read(msg));
  21492. EXPECT_EQ(large_data, msg);
  21493. client.close();
  21494. }
  21495. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21496. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21497. "/ws-echo");
  21498. ASSERT_TRUE(client.connect());
  21499. const int num_threads = 4;
  21500. std::vector<std::thread> threads;
  21501. std::atomic<int> send_count{0};
  21502. for (int t = 0; t < num_threads; t++) {
  21503. threads.emplace_back([&client, &send_count, t]() {
  21504. for (int i = 0; i < 5; i++) {
  21505. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21506. if (client.send(text)) { send_count++; }
  21507. }
  21508. });
  21509. }
  21510. for (auto &th : threads) {
  21511. th.join();
  21512. }
  21513. int received = 0;
  21514. std::string msg;
  21515. while (received < send_count.load()) {
  21516. if (!client.read(msg)) { break; }
  21517. received++;
  21518. }
  21519. EXPECT_EQ(send_count.load(), received);
  21520. client.close();
  21521. }
  21522. TEST_F(WebSocketIntegrationTest, ReadString) {
  21523. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21524. "/ws-echo-string");
  21525. ASSERT_TRUE(client.connect());
  21526. ASSERT_TRUE(client.send("hello"));
  21527. std::string msg;
  21528. ASSERT_TRUE(client.read(msg));
  21529. EXPECT_EQ("echo: hello", msg);
  21530. ASSERT_TRUE(client.send("world"));
  21531. ASSERT_TRUE(client.read(msg));
  21532. EXPECT_EQ("echo: world", msg);
  21533. client.close();
  21534. }
  21535. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21536. Headers headers = {{"X-Test-Header", "test-value"}};
  21537. ws::WebSocketClient client(
  21538. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21539. ASSERT_TRUE(client.connect());
  21540. std::string msg;
  21541. ASSERT_TRUE(client.read(msg));
  21542. EXPECT_EQ("path:/ws-request-info", msg);
  21543. ASSERT_TRUE(client.read(msg));
  21544. EXPECT_EQ("header:test-value", msg);
  21545. client.close();
  21546. }
  21547. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21548. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21549. "/ws-echo");
  21550. client.set_read_timeout(1, 0); // 1 second
  21551. ASSERT_TRUE(client.connect());
  21552. // Don't send anything — server echo handler waits for a message, so read()
  21553. // should time out. The connection survives it: nothing was consumed.
  21554. std::string msg;
  21555. EXPECT_EQ(client.read(msg), ws::Timeout);
  21556. EXPECT_TRUE(client.is_open());
  21557. // And it is still usable afterwards.
  21558. EXPECT_TRUE(client.send("after timeout"));
  21559. EXPECT_EQ(client.read(msg), ws::Text);
  21560. EXPECT_EQ(msg, "after timeout");
  21561. }
  21562. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21564. "/ws-echo");
  21565. client.set_read_timeout(1, 0);
  21566. ASSERT_TRUE(client.connect());
  21567. ASSERT_TRUE(client.send("first"));
  21568. std::string msg;
  21569. ASSERT_EQ(client.read(msg), ws::Text);
  21570. ASSERT_EQ(msg, "first");
  21571. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21572. // not be used with a read timeout: it would reprocess the previous message.
  21573. EXPECT_EQ(client.read(msg), ws::Timeout);
  21574. EXPECT_EQ(msg, "first");
  21575. }
  21576. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21577. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21578. "/ws-echo");
  21579. ASSERT_TRUE(client.connect());
  21580. // Setting it once the connection is open reaches the live stream, not just
  21581. // the seed for the next connect().
  21582. client.set_read_timeout(1, 0);
  21583. std::string msg;
  21584. EXPECT_EQ(client.read(msg), ws::Timeout);
  21585. EXPECT_TRUE(client.is_open());
  21586. }
  21587. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21588. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21589. "/ws-echo");
  21590. client.set_read_timeout(5, 0);
  21591. ASSERT_TRUE(client.connect());
  21592. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21593. // The server should reject it and close the connection.
  21594. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21595. client.send(oversized);
  21596. // The server's read() should have failed due to payload limit,
  21597. // so our read() should return false (connection closed).
  21598. std::string msg;
  21599. EXPECT_FALSE(client.read(msg));
  21600. }
  21601. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21602. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21603. "/ws-echo");
  21604. client.set_read_timeout(10, 0);
  21605. ASSERT_TRUE(client.connect());
  21606. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21607. // This should succeed.
  21608. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21609. ASSERT_TRUE(client.send(at_limit));
  21610. std::string msg;
  21611. ASSERT_TRUE(client.read(msg));
  21612. EXPECT_EQ(at_limit.size(), msg.size());
  21613. client.close();
  21614. }
  21615. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21616. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21617. "/nonexistent");
  21618. auto res = client.connect();
  21619. EXPECT_FALSE(res);
  21620. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21621. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21622. EXPECT_FALSE(client.is_open());
  21623. }
  21624. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21625. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21626. "/ws-echo");
  21627. ASSERT_TRUE(client.connect());
  21628. ASSERT_TRUE(client.send(""));
  21629. std::string msg;
  21630. EXPECT_EQ(ws::Text, client.read(msg));
  21631. EXPECT_EQ("", msg);
  21632. client.close();
  21633. }
  21634. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21635. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21636. "/ws-echo");
  21637. // First connection
  21638. ASSERT_TRUE(client.connect());
  21639. ASSERT_TRUE(client.send("first"));
  21640. std::string msg;
  21641. ASSERT_TRUE(client.read(msg));
  21642. EXPECT_EQ("first", msg);
  21643. client.close();
  21644. EXPECT_FALSE(client.is_open());
  21645. // Reconnect using the same client object
  21646. ASSERT_TRUE(client.connect());
  21647. ASSERT_TRUE(client.is_open());
  21648. ASSERT_TRUE(client.send("second"));
  21649. ASSERT_TRUE(client.read(msg));
  21650. EXPECT_EQ("second", msg);
  21651. client.close();
  21652. }
  21653. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21654. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21655. "/ws-close-status");
  21656. ASSERT_TRUE(client.connect());
  21657. // Trigger the server to close with GoingAway status
  21658. ASSERT_TRUE(client.send("trigger"));
  21659. // read() should return false after receiving the close frame
  21660. std::string msg;
  21661. EXPECT_FALSE(client.read(msg));
  21662. EXPECT_FALSE(client.is_open());
  21663. }
  21664. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21666. "/ws-echo");
  21667. ASSERT_TRUE(client.connect());
  21668. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21669. EXPECT_FALSE(client.is_open());
  21670. }
  21671. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21672. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21673. ws::WebSocketClient client(
  21674. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21675. ASSERT_TRUE(client.connect());
  21676. // Server should have selected graphql-ws
  21677. EXPECT_EQ("graphql-ws", client.subprotocol());
  21678. client.close();
  21679. }
  21680. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21681. Headers headers;
  21682. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21683. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21684. ws::WebSocketClient client(
  21685. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21686. ASSERT_TRUE(client.connect());
  21687. // The offer on the second field line counts too, so graphql-ws is selected
  21688. EXPECT_EQ("graphql-ws", client.subprotocol());
  21689. client.close();
  21690. }
  21691. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21692. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21693. ws::WebSocketClient client(
  21694. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21695. ASSERT_TRUE(client.connect());
  21696. // Server should not have selected any subprotocol
  21697. EXPECT_TRUE(client.subprotocol().empty());
  21698. client.close();
  21699. }
  21700. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21701. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21703. "/ws-subprotocol-unoffered",
  21704. headers);
  21705. ASSERT_TRUE(client.connect());
  21706. EXPECT_TRUE(client.subprotocol().empty());
  21707. client.close();
  21708. }
  21709. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21710. // Connect without requesting any subprotocol
  21711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21712. "/ws-subprotocol");
  21713. ASSERT_TRUE(client.connect());
  21714. EXPECT_TRUE(client.subprotocol().empty());
  21715. client.close();
  21716. }
  21717. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21718. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21719. "/ws-echo");
  21720. client.set_tcp_nodelay(true);
  21721. client.set_connection_timeout(3, 0);
  21722. bool socket_options_called = false;
  21723. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21724. ASSERT_TRUE(client.connect());
  21725. ASSERT_TRUE(client.is_open());
  21726. EXPECT_TRUE(socket_options_called);
  21727. ASSERT_TRUE(client.send("hello"));
  21728. std::string msg;
  21729. auto result = client.read(msg);
  21730. EXPECT_EQ(result, ws::ReadResult::Text);
  21731. EXPECT_EQ(msg, "hello");
  21732. client.close();
  21733. }
  21734. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21736. "/ws-echo");
  21737. client.set_connection_timeout(std::chrono::seconds(3));
  21738. client.set_write_timeout(std::chrono::seconds(3));
  21739. // A sub-second remainder exercises the seconds/microseconds split.
  21740. client.set_read_timeout(std::chrono::milliseconds(1500));
  21741. ASSERT_TRUE(client.connect());
  21742. auto start = std::chrono::steady_clock::now();
  21743. std::string msg;
  21744. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21745. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21746. std::chrono::steady_clock::now() - start)
  21747. .count();
  21748. // Above 1s so that dropping the microseconds half of the split fails here.
  21749. // Ignoring the setter altogether would not reach this line at all: a client
  21750. // waits forever by default.
  21751. EXPECT_GE(elapsed, 1400);
  21752. EXPECT_LT(elapsed, 30000);
  21753. }
  21754. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21755. Server svr;
  21756. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21757. if (!req.has_header("Authorization")) {
  21758. res.status = StatusCode::Unauthorized_401;
  21759. res.set_content("Unauthorized", "text/plain");
  21760. return Server::HandlerResponse::Handled;
  21761. }
  21762. return Server::HandlerResponse::Unhandled;
  21763. });
  21764. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21765. std::string msg;
  21766. while (ws.read(msg)) {
  21767. ws.send(msg);
  21768. }
  21769. });
  21770. auto port = svr.bind_to_any_port("localhost");
  21771. std::thread t([&]() { svr.listen_after_bind(); });
  21772. svr.wait_until_ready();
  21773. // Without Authorization header - should be rejected before upgrade
  21774. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21775. EXPECT_FALSE(client1.connect());
  21776. // The rejection is framed like any other HTTP response
  21777. {
  21778. Client cli("localhost", port);
  21779. Headers headers = {{"Upgrade", "websocket"},
  21780. {"Connection", "Upgrade"},
  21781. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21782. {"Sec-WebSocket-Version", "13"}};
  21783. auto res = cli.Get("/ws", headers);
  21784. ASSERT_TRUE(res);
  21785. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21786. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21787. EXPECT_EQ("Unauthorized", res->body);
  21788. }
  21789. // With Authorization header - should succeed
  21790. Headers headers = {{"Authorization", "Bearer token123"}};
  21791. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21792. headers);
  21793. ASSERT_TRUE(client2.connect());
  21794. ASSERT_TRUE(client2.send("hello"));
  21795. std::string msg;
  21796. ASSERT_TRUE(client2.read(msg));
  21797. EXPECT_EQ("hello", msg);
  21798. client2.close();
  21799. svr.stop();
  21800. t.join();
  21801. }
  21802. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21803. Server svr;
  21804. std::atomic<int> pre_request_calls{0};
  21805. std::atomic<bool> route_matched{false};
  21806. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21807. pre_request_calls++;
  21808. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21809. if (req.get_header_value("Authorization") != "Bearer token123") {
  21810. res.status = StatusCode::Unauthorized_401;
  21811. res.set_content("Unauthorized", "text/plain");
  21812. return Server::HandlerResponse::Handled;
  21813. }
  21814. return Server::HandlerResponse::Unhandled;
  21815. });
  21816. std::atomic<bool> handler_called{false};
  21817. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21818. handler_called = true;
  21819. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21820. });
  21821. auto port = svr.bind_to_any_port("localhost");
  21822. std::thread t([&]() { svr.listen_after_bind(); });
  21823. svr.wait_until_ready();
  21824. // Without Authorization header - should be rejected before upgrade
  21825. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21826. "/ws/1");
  21827. EXPECT_FALSE(client1.connect());
  21828. EXPECT_FALSE(handler_called);
  21829. EXPECT_EQ(1, pre_request_calls);
  21830. EXPECT_TRUE(route_matched);
  21831. // The rejection is an ordinary HTTP response, not a protocol switch
  21832. {
  21833. Client cli("localhost", port);
  21834. Headers headers = {{"Upgrade", "websocket"},
  21835. {"Connection", "Upgrade"},
  21836. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21837. {"Sec-WebSocket-Version", "13"}};
  21838. auto res = cli.Get("/ws/1", headers);
  21839. ASSERT_TRUE(res);
  21840. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21841. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21842. EXPECT_EQ("Unauthorized", res->body);
  21843. }
  21844. EXPECT_FALSE(handler_called);
  21845. // With Authorization header - should succeed
  21846. Headers headers = {{"Authorization", "Bearer token123"}};
  21847. ws::WebSocketClient client2(
  21848. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21849. ASSERT_TRUE(client2.connect());
  21850. std::string msg;
  21851. ASSERT_TRUE(client2.read(msg));
  21852. EXPECT_EQ("/ws/:id 2", msg);
  21853. EXPECT_TRUE(handler_called);
  21854. client2.close();
  21855. svr.stop();
  21856. t.join();
  21857. }
  21858. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21859. Server svr;
  21860. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21861. // A read timeout is how a handler gets control back. Without it, a handler
  21862. // parked in read() can never write on the connection it is reading.
  21863. ws.set_read_timeout(std::chrono::milliseconds(100));
  21864. std::string msg;
  21865. while (ws.is_open()) {
  21866. auto r = ws.read(msg);
  21867. if (r == httplib::ws::Timeout) {
  21868. ws.send("tick");
  21869. continue;
  21870. }
  21871. if (r == httplib::ws::Fail) { break; }
  21872. ws.send(msg);
  21873. }
  21874. });
  21875. auto port = svr.bind_to_any_port("localhost");
  21876. std::thread t([&]() { svr.listen_after_bind(); });
  21877. svr.wait_until_ready();
  21878. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21879. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21880. ASSERT_TRUE(client.connect());
  21881. // The client sends nothing, so anything it receives came out of the
  21882. // handler's timeout path.
  21883. std::string msg;
  21884. ASSERT_EQ(client.read(msg), ws::Text);
  21885. EXPECT_EQ("tick", msg);
  21886. client.close();
  21887. svr.stop();
  21888. t.join();
  21889. }
  21890. // Stream::read may return fewer bytes than asked for. This is that contract at
  21891. // its worst -- one byte per call -- which is what a frame header straddling a
  21892. // read buffer's boundary looks like to the frame parser.
  21893. class WsByteAtATimeStream : public Stream {
  21894. public:
  21895. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21896. bool is_readable() const override { return true; }
  21897. bool wait_readable() const override { return true; }
  21898. bool wait_writable() const override { return true; }
  21899. ssize_t read(char *ptr, size_t size) override {
  21900. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21901. *ptr = data_[pos_++];
  21902. return 1;
  21903. }
  21904. ssize_t write(const char *, size_t size) override {
  21905. return static_cast<ssize_t>(size);
  21906. }
  21907. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21908. ip = "127.0.0.1";
  21909. port = 0;
  21910. }
  21911. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21912. ip = "127.0.0.1";
  21913. port = 0;
  21914. }
  21915. socket_t socket() const override { return INVALID_SOCKET; }
  21916. time_t duration() const override { return 0; }
  21917. private:
  21918. std::string data_;
  21919. size_t pos_ = 0;
  21920. };
  21921. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21922. // The payload uses the 16-bit extended length, so the header, the length
  21923. // and the mask key are all multi-byte fields here. Each used to be read
  21924. // with a single read() call, which fails as soon as one is split. The
  21925. // payload is also a little over one read chunk, so it is read in two.
  21926. std::string body;
  21927. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21928. body += static_cast<char>(i % 251);
  21929. }
  21930. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21931. std::string frame;
  21932. frame += static_cast<char>(0x81); // FIN + Text
  21933. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21934. frame += static_cast<char>(body.size() >> 8);
  21935. frame += static_cast<char>(body.size() & 0xff);
  21936. for (size_t i = 0; i < 4; i++) {
  21937. frame += static_cast<char>(mask[i]);
  21938. }
  21939. for (size_t i = 0; i < body.size(); i++) {
  21940. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21941. }
  21942. WsByteAtATimeStream strm(frame);
  21943. ws::Opcode opcode;
  21944. std::string payload;
  21945. bool fin = false;
  21946. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21947. /*expect_masked=*/true, body.size()),
  21948. ws::impl::FrameRead::Ok);
  21949. EXPECT_TRUE(fin);
  21950. EXPECT_EQ(opcode, ws::Opcode::Text);
  21951. EXPECT_EQ(payload, body);
  21952. }
  21953. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21954. std::string body(2000, 'x');
  21955. std::string frame;
  21956. frame += static_cast<char>(0x82); // FIN + Binary
  21957. frame += static_cast<char>(126); // 16-bit length follows
  21958. frame += static_cast<char>(body.size() >> 8);
  21959. frame += static_cast<char>(body.size() & 0xff);
  21960. frame += body;
  21961. detail::BufferStream strm;
  21962. strm.write(frame.data(), frame.size());
  21963. ws::Opcode opcode;
  21964. std::string payload;
  21965. bool fin;
  21966. EXPECT_EQ(
  21967. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21968. ws::impl::FrameRead::Ok);
  21969. EXPECT_EQ(body, payload);
  21970. }
  21971. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21972. // The header announces the largest payload allowed, and only 3 bytes of it
  21973. // ever arrive.
  21974. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21975. std::string frame;
  21976. frame += static_cast<char>(0x82); // FIN + Binary
  21977. frame += static_cast<char>(127); // 64-bit length follows
  21978. for (int shift = 56; shift >= 0; shift -= 8) {
  21979. frame += static_cast<char>((len >> shift) & 0xff);
  21980. }
  21981. frame += "abc";
  21982. detail::BufferStream strm;
  21983. strm.write(frame.data(), frame.size());
  21984. ws::Opcode opcode;
  21985. std::string payload;
  21986. bool fin;
  21987. EXPECT_EQ(
  21988. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21989. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21990. ws::impl::FrameRead::Fail);
  21991. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21992. }
  21993. TEST(WebSocketTest, QueryStringInHandshake) {
  21994. Server svr;
  21995. std::mutex mtx;
  21996. std::string received_target;
  21997. std::string received_token;
  21998. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21999. {
  22000. std::lock_guard<std::mutex> lock(mtx);
  22001. received_target = req.target;
  22002. if (req.has_param("token")) {
  22003. received_token = req.get_param_value("token");
  22004. }
  22005. }
  22006. std::string msg;
  22007. while (ws.read(msg)) {
  22008. ws.send(msg);
  22009. }
  22010. });
  22011. auto port = svr.bind_to_any_port("localhost");
  22012. std::thread t([&]() { svr.listen_after_bind(); });
  22013. svr.wait_until_ready();
  22014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22015. "/ws?token=ABC&session=123");
  22016. ASSERT_TRUE(client.connect());
  22017. // Round-trip ensures the handler has run and captured the request.
  22018. ASSERT_TRUE(client.send("hello"));
  22019. std::string msg;
  22020. ASSERT_TRUE(client.read(msg));
  22021. EXPECT_EQ("hello", msg);
  22022. client.close();
  22023. {
  22024. std::lock_guard<std::mutex> lock(mtx);
  22025. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22026. EXPECT_EQ("ABC", received_token);
  22027. }
  22028. svr.stop();
  22029. t.join();
  22030. }
  22031. // Run a handshake against a throwaway server and hand the request the server
  22032. // received back to the caller, so tests can assert on the headers the client
  22033. // actually put on the wire.
  22034. static void capture_websocket_handshake_request(
  22035. const Headers &client_headers,
  22036. std::function<void(const Request &, int port)> verify) {
  22037. Server svr;
  22038. std::mutex mtx;
  22039. Request received;
  22040. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22041. {
  22042. std::lock_guard<std::mutex> lock(mtx);
  22043. received = req;
  22044. }
  22045. std::string msg;
  22046. while (ws.read(msg)) {
  22047. ws.send(msg);
  22048. }
  22049. });
  22050. auto port = svr.bind_to_any_port("localhost");
  22051. std::thread t([&]() { svr.listen_after_bind(); });
  22052. auto se = detail::scope_exit([&] {
  22053. svr.stop();
  22054. t.join();
  22055. });
  22056. svr.wait_until_ready();
  22057. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22058. client_headers);
  22059. ASSERT_TRUE(client.connect());
  22060. ASSERT_TRUE(client.send("hello"));
  22061. std::string msg;
  22062. ASSERT_TRUE(client.read(msg));
  22063. client.close();
  22064. {
  22065. std::lock_guard<std::mutex> lock(mtx);
  22066. verify(received, port);
  22067. }
  22068. }
  22069. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22070. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22071. // Non-default port must be present in the Host header. Default ports
  22072. // (80/443) are omitted; that logic is covered by
  22073. // MakeHostAndPortStringTest.
  22074. EXPECT_EQ("localhost:" + std::to_string(port),
  22075. req.get_header_value("Host"));
  22076. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22077. req.get_header_value("User-Agent"));
  22078. EXPECT_FALSE(req.has_header("Accept"));
  22079. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22080. EXPECT_FALSE(req.has_header("Content-Length"));
  22081. });
  22082. }
  22083. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22084. capture_websocket_handshake_request(
  22085. {{"Host", "example.com"},
  22086. {"User-Agent", "custom-agent"},
  22087. {"X-Custom", "value"}},
  22088. [](const Request &req, int) {
  22089. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22090. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22091. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22092. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22093. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22094. });
  22095. }
  22096. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22097. capture_websocket_handshake_request(
  22098. {{"Upgrade", "bogus"},
  22099. {"Connection", "close"},
  22100. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22101. {"Sec-WebSocket-Version", "8"}},
  22102. [](const Request &req, int) {
  22103. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22104. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22105. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22106. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22107. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22108. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22109. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22110. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22111. req.get_header_value("Sec-WebSocket-Key"));
  22112. });
  22113. }
  22114. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22115. // A header the client refuses to send must abort the handshake before any
  22116. // part of it reaches the wire; a lone request line would otherwise sit in
  22117. // the peer's buffer as a truncated request.
  22118. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22119. ASSERT_NE(INVALID_SOCKET, srv);
  22120. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22121. sockaddr_in addr{};
  22122. addr.sin_family = AF_INET;
  22123. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22124. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22125. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22126. ASSERT_EQ(0, ::listen(srv, 1));
  22127. sockaddr_in bound{};
  22128. socklen_t bound_len = sizeof(bound);
  22129. ASSERT_EQ(
  22130. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22131. auto port = ntohs(bound.sin_port);
  22132. ssize_t received = -1;
  22133. std::thread t([&] {
  22134. // Bound every blocking call so a regression fails the test with a bad
  22135. // value instead of hanging the suite.
  22136. fd_set rfds;
  22137. FD_ZERO(&rfds);
  22138. FD_SET(srv, &rfds);
  22139. timeval tv{5, 0};
  22140. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22141. 0) {
  22142. return;
  22143. }
  22144. sockaddr_in cli_addr{};
  22145. socklen_t cli_len = sizeof(cli_addr);
  22146. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22147. if (cli == INVALID_SOCKET) { return; }
  22148. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22149. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22150. char buf[4096];
  22151. received = ::recv(cli, buf, sizeof(buf), 0);
  22152. });
  22153. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22154. // connect() has already shut the socket down by the time it returns false,
  22155. // so the peer sees EOF without waiting for the client to be destroyed.
  22156. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22157. {{"X-Bad", "a\r\nInjected: 1"}});
  22158. EXPECT_FALSE(client.connect());
  22159. t.join();
  22160. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22161. EXPECT_EQ(0, received);
  22162. }
  22163. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22164. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22165. // contains "upgrade" as a substring is a different token and must not
  22166. // start a WebSocket handshake.
  22167. auto make_request = [](const std::vector<std::string> &connection_values) {
  22168. Request req;
  22169. req.method = "GET";
  22170. req.headers.emplace("Upgrade", "websocket");
  22171. for (const auto &value : connection_values) {
  22172. req.headers.emplace("Connection", value);
  22173. }
  22174. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22175. req.headers.emplace("Sec-WebSocket-Version", "13");
  22176. return req;
  22177. };
  22178. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22179. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22180. EXPECT_TRUE(
  22181. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22182. EXPECT_TRUE(
  22183. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22184. EXPECT_TRUE(
  22185. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22186. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22187. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22188. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22189. EXPECT_FALSE(
  22190. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22191. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22192. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22193. }
  22194. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22195. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22196. // asks recipients to match each protocol-name case-insensitively, and RFC
  22197. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22198. // client naming websocket alongside another protocol, or on a second field
  22199. // line, is offering websocket; a value that merely contains "websocket" as a
  22200. // substring is a different protocol name and is not.
  22201. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22202. Request req;
  22203. req.method = "GET";
  22204. for (const auto &value : upgrade_values) {
  22205. req.headers.emplace("Upgrade", value);
  22206. }
  22207. req.headers.emplace("Connection", "Upgrade");
  22208. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22209. req.headers.emplace("Sec-WebSocket-Version", "13");
  22210. return req;
  22211. };
  22212. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22213. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22214. EXPECT_TRUE(
  22215. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22216. EXPECT_TRUE(
  22217. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22218. EXPECT_TRUE(
  22219. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22220. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22221. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22222. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22223. EXPECT_FALSE(
  22224. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22225. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22226. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22227. }
  22228. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22229. Server svr;
  22230. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22231. auto port = svr.bind_to_any_port("localhost");
  22232. std::thread t([&]() { svr.listen_after_bind(); });
  22233. auto se = detail::scope_exit([&] {
  22234. svr.stop();
  22235. t.join();
  22236. });
  22237. svr.wait_until_ready();
  22238. Headers headers = {{"Upgrade", "websocket"},
  22239. {"Connection", "notupgrade"},
  22240. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22241. {"Sec-WebSocket-Version", "13"}};
  22242. Client cli("localhost", port);
  22243. auto res = cli.Get("/ws", headers);
  22244. // The route exists only as a WebSocket route, so a request that fails the
  22245. // handshake check falls through to ordinary routing.
  22246. ASSERT_TRUE(res);
  22247. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22248. }
  22249. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22250. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22251. // Connection value is the only thing left for the client to reject.
  22252. Server svr;
  22253. svr.Get("/ws", [](const Request &req, Response &res) {
  22254. res.status = StatusCode::SwitchingProtocol_101;
  22255. res.set_header("Upgrade", "websocket");
  22256. res.set_header("Connection", "notupgrade");
  22257. res.set_header("Sec-WebSocket-Accept",
  22258. detail::websocket_accept_key(
  22259. req.get_header_value("Sec-WebSocket-Key")));
  22260. });
  22261. auto port = svr.bind_to_any_port("localhost");
  22262. std::thread t([&]() { svr.listen_after_bind(); });
  22263. auto se = detail::scope_exit([&] {
  22264. svr.stop();
  22265. t.join();
  22266. });
  22267. svr.wait_until_ready();
  22268. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22269. auto res = client.connect();
  22270. EXPECT_FALSE(res);
  22271. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22272. EXPECT_FALSE(client.is_open());
  22273. }
  22274. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22275. Server svr;
  22276. svr.Get("/ws", [](const Request &req, Response &res) {
  22277. res.status = StatusCode::SwitchingProtocol_101;
  22278. res.set_header("Upgrade", "websocket");
  22279. res.set_header("Connection", "Upgrade");
  22280. res.set_header("Sec-WebSocket-Accept",
  22281. detail::websocket_accept_key(
  22282. req.get_header_value("Sec-WebSocket-Key")));
  22283. res.set_header("Sec-WebSocket-Protocol", "admin");
  22284. });
  22285. auto port = svr.bind_to_any_port("localhost");
  22286. std::thread t([&]() { svr.listen_after_bind(); });
  22287. auto se = detail::scope_exit([&] {
  22288. svr.stop();
  22289. t.join();
  22290. });
  22291. svr.wait_until_ready();
  22292. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22293. // Server selects a subprotocol the client never offered
  22294. {
  22295. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22296. ws::WebSocketClient client(url, headers);
  22297. auto res = client.connect();
  22298. EXPECT_FALSE(res);
  22299. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22300. EXPECT_FALSE(client.is_open());
  22301. EXPECT_TRUE(client.subprotocol().empty());
  22302. }
  22303. // Client offered none but the server named one anyway
  22304. {
  22305. ws::WebSocketClient client(url);
  22306. auto res = client.connect();
  22307. EXPECT_FALSE(res);
  22308. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22309. EXPECT_FALSE(client.is_open());
  22310. EXPECT_TRUE(client.subprotocol().empty());
  22311. }
  22312. }
  22313. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22314. // The socket path doubles as the URL host, so it must not contain '/'.
  22315. const char *shard = getenv("GTEST_SHARD_INDEX");
  22316. const std::string sock_path =
  22317. shard ? std::string("httplib-ws-") + shard + ".sock"
  22318. : std::string("httplib-ws.sock");
  22319. std::remove(sock_path.c_str());
  22320. Server svr;
  22321. std::mutex mtx;
  22322. std::string received_host;
  22323. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22324. {
  22325. std::lock_guard<std::mutex> lock(mtx);
  22326. received_host = req.get_header_value("Host");
  22327. }
  22328. std::string msg;
  22329. while (ws.read(msg)) {
  22330. ws.send(msg);
  22331. }
  22332. });
  22333. svr.set_address_family(AF_UNIX);
  22334. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22335. auto se = detail::scope_exit([&] {
  22336. svr.stop();
  22337. t.join();
  22338. std::remove(sock_path.c_str());
  22339. });
  22340. svr.wait_until_ready();
  22341. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22342. client.set_address_family(AF_UNIX);
  22343. ASSERT_TRUE(client.connect());
  22344. ASSERT_TRUE(client.send("hello"));
  22345. std::string msg;
  22346. ASSERT_TRUE(client.read(msg));
  22347. client.close();
  22348. {
  22349. std::lock_guard<std::mutex> lock(mtx);
  22350. // There is no host:port for a Unix socket, so the same "localhost"
  22351. // placeholder the HTTP client uses is expected.
  22352. EXPECT_EQ("localhost", received_host);
  22353. }
  22354. }
  22355. // Two threads must never parse WebSocket frames from the same stream.
  22356. // close() used to read the peer's Close reply with its own frame read, so it
  22357. // raced a reader thread that was in the middle of a payload: the payload loop
  22358. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22359. // so bytes taken by close() were replaced with bytes from further along the
  22360. // stream. The message kept its length and silently changed content.
  22361. //
  22362. // The raw peer below sends a frame header plus part of the payload, waits for
  22363. // the handler to call close(), and only then sends the rest. Whichever thread
  22364. // would win the race for those bytes, the message must arrive intact, because
  22365. // close() must not touch the stream while read() owns it.
  22366. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22367. #ifndef _WIN32
  22368. signal(SIGPIPE, SIG_IGN);
  22369. #endif
  22370. const size_t payload_len = 120; // fits the 7-bit length field
  22371. const size_t prefix_len = 8;
  22372. const int attempts = 8;
  22373. std::string expected(payload_len, '\0');
  22374. for (size_t i = 0; i < payload_len; i++) {
  22375. expected[i] = static_cast<char>('a' + i % 26);
  22376. }
  22377. std::atomic<bool> peer_stalled{false};
  22378. std::atomic<bool> handler_done{false};
  22379. std::mutex received_mutex;
  22380. std::vector<std::string> received;
  22381. // Bound every wait, so a regression fails the test instead of hanging the
  22382. // suite.
  22383. auto wait_for = [](const std::atomic<bool> &flag) {
  22384. for (int i = 0; i < 500 && !flag; i++) {
  22385. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22386. }
  22387. };
  22388. Server svr;
  22389. svr.set_websocket_ping_interval(0);
  22390. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22391. std::thread reader([&]() {
  22392. std::string msg;
  22393. while (ws.read(msg)) {
  22394. std::lock_guard<std::mutex> guard(received_mutex);
  22395. received.push_back(msg);
  22396. }
  22397. });
  22398. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22399. // inside read_websocket_frame() when close() runs.
  22400. wait_for(peer_stalled);
  22401. ws.close();
  22402. reader.join();
  22403. handler_done = true;
  22404. });
  22405. auto port = svr.bind_to_any_port("127.0.0.1");
  22406. std::thread t([&]() { svr.listen_after_bind(); });
  22407. auto se = detail::scope_exit([&] {
  22408. svr.stop();
  22409. t.join();
  22410. });
  22411. svr.wait_until_ready();
  22412. auto send_bytes = [](socket_t s, const std::string &data) {
  22413. #ifdef _WIN32
  22414. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22415. #else
  22416. auto n = ::send(s, data.data(), data.size(), 0);
  22417. #endif
  22418. return n == static_cast<decltype(n)>(data.size());
  22419. };
  22420. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22421. // Every length used here fits the 7-bit length field.
  22422. auto masked_header = [](uint8_t first_byte, size_t len) {
  22423. std::string h;
  22424. h += static_cast<char>(first_byte);
  22425. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22426. h.append(4, '\0'); // mask key
  22427. return h;
  22428. };
  22429. for (int attempt = 0; attempt < attempts; attempt++) {
  22430. peer_stalled = false;
  22431. handler_done = false;
  22432. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22433. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22434. auto se_sock = detail::scope_exit([&] {
  22435. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22436. });
  22437. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22438. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22439. sockaddr_in addr{};
  22440. addr.sin_family = AF_INET;
  22441. addr.sin_port = htons(static_cast<uint16_t>(port));
  22442. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22443. ASSERT_EQ(
  22444. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22445. << "attempt " << attempt;
  22446. ASSERT_TRUE(send_bytes(sock,
  22447. "GET /ws HTTP/1.1\r\n"
  22448. "Host: 127.0.0.1\r\n"
  22449. "Upgrade: websocket\r\n"
  22450. "Connection: Upgrade\r\n"
  22451. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22452. "Sec-WebSocket-Version: 13\r\n"
  22453. "\r\n"))
  22454. << "attempt " << attempt;
  22455. std::string response;
  22456. while (response.find("\r\n\r\n") == std::string::npos) {
  22457. char buf[512];
  22458. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22459. if (n <= 0) { break; }
  22460. response.append(buf, static_cast<size_t>(n));
  22461. }
  22462. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22463. << "attempt " << attempt;
  22464. // Send the header of a Binary message but only the first prefix_len bytes
  22465. // of its payload, leaving the reader thread stalled inside the payload.
  22466. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22467. expected.substr(0, prefix_len)))
  22468. << "attempt " << attempt;
  22469. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22470. peer_stalled = true;
  22471. // Let close() send its Close frame and park in its own read before the
  22472. // rest of the payload arrives, so both threads are waiting for it.
  22473. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22474. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22475. close_frame += static_cast<char>(0x03); // status 1000
  22476. close_frame += static_cast<char>(0xE8);
  22477. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22478. << "attempt " << attempt;
  22479. // Closing the peer releases the reader thread even on the buggy path,
  22480. // where it waits for bytes another thread already consumed.
  22481. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22482. detail::close_socket(sock);
  22483. sock = INVALID_SOCKET;
  22484. wait_for(handler_done);
  22485. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22486. }
  22487. std::lock_guard<std::mutex> guard(received_mutex);
  22488. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22489. << "a message in flight when close() ran was dropped";
  22490. for (size_t i = 0; i < received.size(); i++) {
  22491. EXPECT_EQ(expected, received[i]) << "message " << i;
  22492. }
  22493. }
  22494. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22495. // returning the socket, or INVALID_SOCKET.
  22496. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22497. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22498. if (sock == INVALID_SOCKET) { return sock; }
  22499. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22500. sockaddr_in addr{};
  22501. addr.sin_family = AF_INET;
  22502. addr.sin_port = htons(static_cast<uint16_t>(port));
  22503. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22504. std::string req = "GET " + path +
  22505. " HTTP/1.1\r\n"
  22506. "Host: 127.0.0.1\r\n"
  22507. "Upgrade: websocket\r\n"
  22508. "Connection: Upgrade\r\n"
  22509. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22510. "Sec-WebSocket-Version: 13\r\n"
  22511. "\r\n";
  22512. std::string res;
  22513. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22514. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22515. static_cast<int>(req.size())) {
  22516. char c;
  22517. while (res.find("\r\n\r\n") == std::string::npos &&
  22518. ::recv(sock, &c, 1, 0) == 1) {
  22519. res += c;
  22520. }
  22521. }
  22522. if (res.find(" 101 ") == std::string::npos) {
  22523. detail::close_socket(sock);
  22524. return INVALID_SOCKET;
  22525. }
  22526. return sock;
  22527. }
  22528. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22529. // The payload must fit the 7-bit length field.
  22530. static std::string masked_frame(uint8_t first_byte,
  22531. const std::string &payload) {
  22532. std::string f;
  22533. f += static_cast<char>(first_byte);
  22534. f += static_cast<char>(0x80 | payload.size());
  22535. f.append(4, '\0');
  22536. return f + payload;
  22537. }
  22538. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22539. std::atomic<bool> done{false};
  22540. std::string received;
  22541. Server svr;
  22542. svr.set_websocket_ping_interval(0);
  22543. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22544. std::string msg;
  22545. if (ws.read(msg) == ws::Binary) { received = msg; }
  22546. done = true;
  22547. });
  22548. auto port = svr.bind_to_any_port("127.0.0.1");
  22549. std::thread t([&]() { svr.listen_after_bind(); });
  22550. auto se = detail::scope_exit([&] {
  22551. svr.stop();
  22552. t.join();
  22553. });
  22554. svr.wait_until_ready();
  22555. auto sock = connect_raw_websocket(port, "/ws");
  22556. ASSERT_NE(INVALID_SOCKET, sock);
  22557. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22558. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22559. masked_frame(0x89, "p") + // FIN + Ping
  22560. masked_frame(0x80, "lo"); // FIN + Continuation
  22561. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22562. for (int i = 0; i < 500 && !done; i++) {
  22563. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22564. }
  22565. ASSERT_TRUE(done);
  22566. EXPECT_EQ("Hello", received);
  22567. }
  22568. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22569. Server svr;
  22570. svr.set_websocket_ping_interval(0);
  22571. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22572. std::string msg;
  22573. while (ws.read(msg)) {}
  22574. });
  22575. auto port = svr.bind_to_any_port("127.0.0.1");
  22576. std::thread t([&]() { svr.listen_after_bind(); });
  22577. auto se = detail::scope_exit([&] {
  22578. svr.stop();
  22579. t.join();
  22580. });
  22581. svr.wait_until_ready();
  22582. // The Close each payload is answered with: an echo when it is valid, and
  22583. // 1002 otherwise.
  22584. std::vector<std::pair<std::string, std::string>> cases = {
  22585. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22586. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22587. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22588. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22589. };
  22590. for (const auto &c : cases) {
  22591. auto sock = connect_raw_websocket(port, "/ws");
  22592. ASSERT_NE(INVALID_SOCKET, sock);
  22593. auto close_frame = masked_frame(0x88, c.first);
  22594. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22595. std::string reply;
  22596. char buf[256];
  22597. while (reply.size() < 2 + c.second.size()) {
  22598. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22599. if (n <= 0) { break; }
  22600. reply.append(buf, static_cast<size_t>(n));
  22601. }
  22602. detail::close_socket(sock);
  22603. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22604. c.second,
  22605. reply);
  22606. }
  22607. }
  22608. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22609. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22610. protected:
  22611. void SetUp() override {
  22612. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22613. SERVER_PRIVATE_KEY_FILE);
  22614. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22615. std::string msg;
  22616. ws::ReadResult ret;
  22617. while ((ret = ws.read(msg))) {
  22618. if (ret == ws::Binary) {
  22619. ws.send(msg.data(), msg.size());
  22620. } else {
  22621. ws.send(msg);
  22622. }
  22623. }
  22624. });
  22625. port_ = server_->bind_to_any_port(HOST);
  22626. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22627. server_->wait_until_ready();
  22628. }
  22629. void TearDown() override {
  22630. server_->stop();
  22631. if (server_thread_.joinable()) { server_thread_.join(); }
  22632. }
  22633. std::unique_ptr<SSLServer> server_;
  22634. std::thread server_thread_;
  22635. int port_ = 0;
  22636. };
  22637. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22638. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22639. "/ws-echo");
  22640. client.enable_server_certificate_verification(false);
  22641. ASSERT_TRUE(client.connect());
  22642. ASSERT_TRUE(client.is_open());
  22643. ASSERT_TRUE(client.send("Hello WSS"));
  22644. std::string msg;
  22645. EXPECT_EQ(ws::Text, client.read(msg));
  22646. EXPECT_EQ("Hello WSS", msg);
  22647. client.close();
  22648. }
  22649. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22650. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22651. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22652. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22653. // client (without calling close() first) is the only path that runs
  22654. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22655. // bug exactly.
  22656. //
  22657. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22658. // when linked against an instrumented libssl; run under Valgrind to catch it
  22659. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22660. // suite (the freed session otherwise stalls on the close handshake) — this test
  22661. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22662. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22663. {
  22664. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22665. "/ws-echo");
  22666. client.enable_server_certificate_verification(false);
  22667. client.set_read_timeout(2, 0);
  22668. client.set_write_timeout(2, 0);
  22669. ASSERT_TRUE(client.connect());
  22670. ASSERT_TRUE(client.is_open());
  22671. ASSERT_TRUE(client.send("still open"));
  22672. // Intentionally do NOT call client.close(): leaving scope runs
  22673. // shutdown_and_close() with the WebSocket still open, which must send the
  22674. // close frame while the TLS session is still alive.
  22675. }
  22676. }
  22677. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22678. // shutdown_and_close() at the start of connect(), reproducing the same
  22679. // use-after-free within the test body rather than at scope exit. The second
  22680. // connect must succeed and echo, proving the close handshake ran over a live
  22681. // session. See the note above about memory-tool requirements.
  22682. TEST_F(WebSocketSSLIntegrationTest,
  22683. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22684. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22685. "/ws-echo");
  22686. client.enable_server_certificate_verification(false);
  22687. client.set_read_timeout(2, 0);
  22688. client.set_write_timeout(2, 0);
  22689. ASSERT_TRUE(client.connect());
  22690. ASSERT_TRUE(client.is_open());
  22691. ASSERT_TRUE(client.send("still open"));
  22692. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22693. // the still-open connection, which must not touch a freed TLS session.
  22694. ASSERT_TRUE(client.connect());
  22695. ASSERT_TRUE(client.is_open());
  22696. ASSERT_TRUE(client.send("after reconnect"));
  22697. std::string msg;
  22698. EXPECT_EQ(ws::Text, client.read(msg));
  22699. EXPECT_EQ("after reconnect", msg);
  22700. client.close();
  22701. }
  22702. #endif
  22703. #ifdef CPPHTTPLIB_SSL_ENABLED
  22704. class WebSocketSSLCATest : public ::testing::Test {
  22705. protected:
  22706. void SetUp() override {
  22707. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22708. SERVER_PRIVATE_KEY_FILE);
  22709. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22710. std::string msg;
  22711. while (ws.read(msg)) {
  22712. ws.send(msg);
  22713. }
  22714. });
  22715. port_ = server_->bind_to_any_port("127.0.0.1");
  22716. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22717. server_->wait_until_ready();
  22718. }
  22719. void TearDown() override {
  22720. server_->stop();
  22721. if (server_thread_.joinable()) { server_thread_.join(); }
  22722. }
  22723. std::string url() const {
  22724. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22725. }
  22726. std::unique_ptr<SSLServer> server_;
  22727. std::thread server_thread_;
  22728. int port_ = 0;
  22729. };
  22730. // A custom CA loaded as PEM verifies the server with full certificate
  22731. // verification enabled
  22732. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22733. ws::WebSocketClient client(url());
  22734. std::string cert;
  22735. read_file(SERVER_CERT2_FILE, cert);
  22736. client.load_ca_cert_store(cert.c_str(), cert.size());
  22737. ASSERT_TRUE(client.connect());
  22738. ASSERT_TRUE(client.send("hello"));
  22739. std::string msg;
  22740. EXPECT_EQ(ws::Text, client.read(msg));
  22741. EXPECT_EQ("hello", msg);
  22742. client.close();
  22743. }
  22744. // A custom CA that does not cover the server must fail verification (the
  22745. // custom CA is exclusive; system certs are not loaded alongside it)
  22746. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22747. ws::WebSocketClient client(url());
  22748. std::string cert;
  22749. read_file(CLIENT_CA_CERT_FILE, cert);
  22750. client.load_ca_cert_store(cert.c_str(), cert.size());
  22751. auto res = client.connect();
  22752. ASSERT_FALSE(res);
  22753. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22754. EXPECT_EQ(-1, res.status());
  22755. EXPECT_NE(0u, res.ssl_backend_error());
  22756. }
  22757. // The same CA as a file path rather than PEM in memory
  22758. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22759. ws::WebSocketClient client(url());
  22760. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22761. ASSERT_TRUE(client.connect());
  22762. ASSERT_TRUE(client.send("hello"));
  22763. std::string msg;
  22764. EXPECT_EQ(ws::Text, client.read(msg));
  22765. EXPECT_EQ("hello", msg);
  22766. client.close();
  22767. }
  22768. // ...and a CA file that does not cover the server still fails, so it is the
  22769. // path above that decides the outcome
  22770. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22771. ws::WebSocketClient client(url());
  22772. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22773. ASSERT_FALSE(client.connect());
  22774. }
  22775. // Regression test: reconnecting with a native custom CA store used to reuse
  22776. // a store handle the previous TLS context had already freed (use-after-free
  22777. // under the OpenSSL backend). The context now lives as long as the client.
  22778. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22779. ws::WebSocketClient client(url());
  22780. std::string cert;
  22781. read_file(SERVER_CERT2_FILE, cert);
  22782. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22783. ASSERT_TRUE(client.connect());
  22784. client.close();
  22785. ASSERT_TRUE(client.connect());
  22786. ASSERT_TRUE(client.send("again"));
  22787. std::string msg;
  22788. EXPECT_EQ(ws::Text, client.read(msg));
  22789. EXPECT_EQ("again", msg);
  22790. client.close();
  22791. }
  22792. // Regression test: a certificate with a trusted chain but no identity match
  22793. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22794. // verification entirely for IP hosts, so this connection succeeded there.
  22795. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22796. // chain verification while the identity check must still fail.
  22797. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22799. ASSERT_TRUE(svr.is_valid());
  22800. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22801. std::string msg;
  22802. while (ws.read(msg)) {
  22803. ws.send(msg);
  22804. }
  22805. });
  22806. auto port = svr.bind_to_any_port("127.0.0.1");
  22807. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22808. auto se = detail::scope_exit([&] {
  22809. svr.stop();
  22810. t.join();
  22811. });
  22812. svr.wait_until_ready();
  22813. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22814. "/echo");
  22815. std::string cert;
  22816. read_file(SERVER_CERT_FILE, cert);
  22817. client.load_ca_cert_store(cert.c_str(), cert.size());
  22818. ASSERT_FALSE(client.connect());
  22819. }
  22820. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22821. // SNI, so nothing binds the host name to the TLS session. These bind the
  22822. // server to "localhost" instead, the only shape that exercises the SNI and
  22823. // hostname-verification path with certificate verification left enabled.
  22824. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22825. protected:
  22826. void Start(const char *cert_file) {
  22827. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22828. SERVER_PRIVATE_KEY_FILE);
  22829. ASSERT_TRUE(server_->is_valid());
  22830. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22831. std::string msg;
  22832. while (ws.read(msg)) {
  22833. ws.send(msg);
  22834. }
  22835. });
  22836. port_ = server_->bind_to_any_port("localhost");
  22837. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22838. server_->wait_until_ready();
  22839. }
  22840. void TearDown() override {
  22841. if (server_) { server_->stop(); }
  22842. if (server_thread_.joinable()) { server_thread_.join(); }
  22843. }
  22844. std::string url() const {
  22845. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22846. }
  22847. std::unique_ptr<SSLServer> server_;
  22848. std::thread server_thread_;
  22849. int port_ = 0;
  22850. };
  22851. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22852. // out and the connection is usable
  22853. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22854. Start(SERVER_CERT2_FILE);
  22855. ws::WebSocketClient client(url());
  22856. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22857. ASSERT_TRUE(client.connect());
  22858. ASSERT_TRUE(client.send("hello"));
  22859. std::string msg;
  22860. EXPECT_EQ(ws::Text, client.read(msg));
  22861. EXPECT_EQ("hello", msg);
  22862. client.close();
  22863. }
  22864. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22865. // while the identity check must still reject "localhost"
  22866. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22867. Start(SERVER_CERT_FILE);
  22868. ws::WebSocketClient client(url());
  22869. client.set_ca_cert_path(SERVER_CERT_FILE);
  22870. auto res = client.connect();
  22871. ASSERT_FALSE(res);
  22872. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22873. EXPECT_EQ(-1, res.status());
  22874. }
  22875. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22876. // disabled: the chain is still checked, only the identity check is skipped
  22877. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22878. Start(SERVER_CERT_FILE);
  22879. ws::WebSocketClient client(url());
  22880. client.set_ca_cert_path(SERVER_CERT_FILE);
  22881. client.enable_server_hostname_verification(false);
  22882. ASSERT_TRUE(client.connect());
  22883. ASSERT_TRUE(client.send("hello"));
  22884. std::string msg;
  22885. EXPECT_EQ(ws::Text, client.read(msg));
  22886. EXPECT_EQ("hello", msg);
  22887. client.close();
  22888. }
  22889. // A CA that did not sign the server certificate fails the chain, even though
  22890. // the name would match
  22891. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22892. Start(SERVER_CERT2_FILE);
  22893. ws::WebSocketClient client(url());
  22894. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22895. ASSERT_FALSE(client.connect());
  22896. }
  22897. // With verification disabled, neither the chain nor the name is checked
  22898. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22899. Start(SERVER_CERT_FILE);
  22900. ws::WebSocketClient client(url());
  22901. client.enable_server_certificate_verification(false);
  22902. ASSERT_TRUE(client.connect());
  22903. ASSERT_TRUE(client.send("hello"));
  22904. std::string msg;
  22905. EXPECT_EQ(ws::Text, client.read(msg));
  22906. EXPECT_EQ("hello", msg);
  22907. client.close();
  22908. }
  22909. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22910. protected:
  22911. void SetUp() override {
  22912. server_ = httplib::detail::make_unique<SSLServer>(
  22913. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22914. ASSERT_TRUE(server_->is_valid());
  22915. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22916. std::string msg;
  22917. while (ws.read(msg)) {
  22918. ws.send(msg);
  22919. }
  22920. });
  22921. port_ = server_->bind_to_any_port("localhost");
  22922. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22923. server_->wait_until_ready();
  22924. }
  22925. void TearDown() override {
  22926. server_->stop();
  22927. if (server_thread_.joinable()) { server_thread_.join(); }
  22928. }
  22929. std::string url() const {
  22930. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22931. }
  22932. void ConnectWithClientCert(const std::string &client_cert_file,
  22933. const std::string &client_private_key_file,
  22934. const char *private_key_password) {
  22935. std::string cert_pem, key_pem;
  22936. read_file(client_cert_file, cert_pem);
  22937. read_file(client_private_key_file, key_pem);
  22938. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22939. key_pem.c_str(), key_pem.size(),
  22940. private_key_password};
  22941. ws::WebSocketClient client(url(), pem);
  22942. ASSERT_TRUE(client.is_valid());
  22943. client.enable_server_certificate_verification(false);
  22944. ASSERT_TRUE(client.connect());
  22945. ASSERT_TRUE(client.send("hello"));
  22946. std::string msg;
  22947. EXPECT_EQ(ws::Text, client.read(msg));
  22948. EXPECT_EQ("hello", msg);
  22949. client.close();
  22950. }
  22951. std::unique_ptr<SSLServer> server_;
  22952. std::thread server_thread_;
  22953. int port_ = 0;
  22954. };
  22955. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22956. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22957. }
  22958. // Control for the tests above: the fixture's server really does require a
  22959. // client certificate, so it is the PEM the constructor installed that decides
  22960. // the outcome.
  22961. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22962. ws::WebSocketClient client(url());
  22963. ASSERT_TRUE(client.is_valid());
  22964. client.enable_server_certificate_verification(false);
  22965. EXPECT_FALSE(client.connect());
  22966. }
  22967. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22968. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22969. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22970. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22971. }
  22972. #endif
  22973. #if !defined(_WIN32)
  22974. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22975. auto secret_dir = std::string("./symlink_test_secret");
  22976. auto served_dir = std::string("./symlink_test_served");
  22977. auto secret_file = secret_dir + "/secret.txt";
  22978. auto symlink_path = served_dir + "/escape";
  22979. // Setup: create directories and files
  22980. mkdir(secret_dir.c_str(), 0755);
  22981. mkdir(served_dir.c_str(), 0755);
  22982. {
  22983. std::ofstream ofs(secret_file);
  22984. ofs << "SECRET_DATA";
  22985. }
  22986. // Create symlink using absolute path so it resolves correctly
  22987. #ifdef PATH_MAX
  22988. char abs_secret[PATH_MAX];
  22989. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22990. #else
  22991. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22992. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22993. ASSERT_NE(nullptr, abs_secret);
  22994. #endif
  22995. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22996. auto se = detail::scope_exit([&] {
  22997. unlink(symlink_path.c_str());
  22998. unlink(secret_file.c_str());
  22999. rmdir(served_dir.c_str());
  23000. rmdir(secret_dir.c_str());
  23001. });
  23002. Server svr;
  23003. svr.set_mount_point("/", served_dir);
  23004. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23005. auto se2 = detail::scope_exit([&] {
  23006. svr.stop();
  23007. listen_thread.join();
  23008. });
  23009. svr.wait_until_ready();
  23010. Client cli("localhost", PORT);
  23011. // Symlink pointing outside base dir should be blocked
  23012. auto res = cli.Get("/escape/secret.txt");
  23013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23014. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23015. }
  23016. #endif
  23017. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23018. // "GET /smuggled" request), reads the first response, and only then sends the
  23019. // embedded request as the body. Returns how many times /smuggled ran.
  23020. //
  23021. // The body is sent AFTER receiving the first response (as in the original
  23022. // PoC) so that the stream_line_reader cannot buffer it together with the
  23023. // headers of the first request.
  23024. static int count_smuggled_requests(const std::string &outer_head,
  23025. std::string &first_response) {
  23026. Server svr;
  23027. svr.set_mount_point("/", "./www");
  23028. std::atomic<int> smuggled_count(0);
  23029. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23030. smuggled_count++;
  23031. res.set_content("oops", "text/plain");
  23032. });
  23033. svr.Post("/post", [&](const Request &req, Response &res) {
  23034. res.set_content(req.body, "text/plain");
  23035. });
  23036. auto port = svr.bind_to_any_port("localhost");
  23037. thread t = thread([&] { svr.listen_after_bind(); });
  23038. auto se = detail::scope_exit([&] {
  23039. svr.stop();
  23040. t.join();
  23041. });
  23042. svr.wait_until_ready();
  23043. auto error = Error::Success;
  23044. auto sock = detail::create_client_socket(
  23045. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23046. /*connection_timeout_sec=*/2, 0,
  23047. /*read_timeout_sec=*/2, 0,
  23048. /*write_timeout_sec=*/2, 0, std::string(), error);
  23049. EXPECT_NE(INVALID_SOCKET, sock);
  23050. if (sock == INVALID_SOCKET) { return -1; }
  23051. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23052. // The "smuggled" request will be sent as the body of the outer request
  23053. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23054. "Host: localhost\r\n"
  23055. "Connection: close\r\n"
  23056. "\r\n";
  23057. auto head = outer_head;
  23058. auto len = std::to_string(smuggled.size());
  23059. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23060. pos = head.find("{len}", pos + len.size())) {
  23061. head.replace(pos, 5, len);
  23062. }
  23063. // Step 1: Send only the outer request headers (no body yet)
  23064. auto sent = send(sock, head.data(), head.size(), 0);
  23065. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23066. // Step 2: Read the first response
  23067. char buf[4096];
  23068. for (;;) {
  23069. auto n = recv(sock, buf, sizeof(buf), 0);
  23070. if (n <= 0) break;
  23071. first_response.append(buf, static_cast<size_t>(n));
  23072. // Stop once we have a complete response (headers + body)
  23073. auto hdr_end = first_response.find("\r\n\r\n");
  23074. if (hdr_end != std::string::npos) {
  23075. // Check for Content-Length to know when the body is complete
  23076. auto cl_pos = first_response.find("Content-Length:");
  23077. if (cl_pos != std::string::npos) {
  23078. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23079. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23080. auto cl = std::stoul(
  23081. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23082. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23083. } else {
  23084. break; // No Content-Length, assume headers-only response
  23085. }
  23086. }
  23087. }
  23088. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23089. // vulnerable server the keep-alive loop reads this as a second request. The
  23090. // server may already have closed the connection, so the result is ignored.
  23091. send(sock, smuggled.data(), smuggled.size(), 0);
  23092. // Half-close so that a server which drained the body sees EOF and closes,
  23093. // instead of the read below waiting for the read timeout.
  23094. #ifdef _WIN32
  23095. ::shutdown(sock, SD_SEND);
  23096. #else
  23097. ::shutdown(sock, SHUT_WR);
  23098. #endif
  23099. // Step 4: Read until the server closes the connection
  23100. for (;;) {
  23101. auto n = recv(sock, buf, sizeof(buf), 0);
  23102. if (n <= 0) break;
  23103. }
  23104. return smuggled_count.load();
  23105. }
  23106. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23107. // A GET request with Content-Length to a static file handler must have its
  23108. // body drained before the keep-alive connection is reused. Otherwise the
  23109. // unread body bytes are interpreted as the next HTTP request.
  23110. std::string first_response;
  23111. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23112. "Host: localhost\r\n"
  23113. "Content-Length: {len}\r\n"
  23114. "\r\n",
  23115. first_response));
  23116. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23117. }
  23118. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23119. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23120. // be answered with 400 and the connection closed. Treating it as "no body"
  23121. // leaves the body to be parsed as the next request.
  23122. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23123. const char *targets[] = {
  23124. "GET /file", // handler that never reads the body
  23125. "GET /not-found", // no handler matches (404)
  23126. "POST /post", // handler that reads the body
  23127. };
  23128. for (auto target : targets) {
  23129. for (auto value : values) {
  23130. std::string first_response;
  23131. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23132. " HTTP/1.1\r\n"
  23133. "Host: localhost\r\n"
  23134. "Content-Length: " +
  23135. value + "\r\n\r\n",
  23136. first_response))
  23137. << target << " with Content-Length: " << value;
  23138. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23139. << target << " with Content-Length: " << value;
  23140. }
  23141. }
  23142. }
  23143. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23144. // A 400 for an unparseable request line leaves the rest of the message
  23145. // unread, so the connection must be closed rather than reused.
  23146. std::string first_response;
  23147. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23148. "Host: localhost\r\n"
  23149. "Content-Length: {len}\r\n"
  23150. "\r\n",
  23151. first_response));
  23152. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23153. }
  23154. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23155. // Same as above for a header block that fails to parse.
  23156. std::string first_response;
  23157. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23158. "Host: localhost\r\n"
  23159. "Bad Header\r\n"
  23160. "Content-Length: {len}\r\n"
  23161. "\r\n",
  23162. first_response));
  23163. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23164. }
  23165. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23166. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23167. // server must not read another request on that connection, even when the
  23168. // request had no body to drain.
  23169. std::string first_response;
  23170. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23171. "Host: localhost\r\n"
  23172. "\r\n",
  23173. first_response));
  23174. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23175. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23176. }
  23177. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23178. // A content reader that stops early leaves the stream inside the body.
  23179. // Draining the whole Content-Length from there, or reading the body again,
  23180. // reads into the next request, and whatever follows is parsed as a request
  23181. // of its own.
  23182. Server svr;
  23183. std::atomic<int> smuggled_count(0);
  23184. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23185. svr.Post("/upload", [](const Request &req, Response &res,
  23186. const ContentReader &content_reader) {
  23187. // Stop at the last chunk, so the whole body has been read however it
  23188. // arrives.
  23189. auto length = req.get_header_value_u64("Content-Length");
  23190. size_t total = 0;
  23191. auto consumed = content_reader([&](const char *, size_t n) {
  23192. total += n;
  23193. return total < length;
  23194. });
  23195. EXPECT_FALSE(consumed);
  23196. if (req.has_param("retry")) {
  23197. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23198. }
  23199. // Replace the 400 the aborted read set, which would close the connection.
  23200. res.set_redirect("/done");
  23201. });
  23202. auto port = svr.bind_to_any_port(HOST);
  23203. thread t = thread([&] { svr.listen_after_bind(); });
  23204. auto se = detail::scope_exit([&] {
  23205. svr.stop();
  23206. t.join();
  23207. });
  23208. svr.wait_until_ready();
  23209. // A front end sees the second request as a POST whose body is the GET. The
  23210. // first body is as long as the POST's headers, so draining it again reads
  23211. // exactly those and leaves the GET to be parsed next.
  23212. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23213. "Host: localhost\r\n"
  23214. "\r\n";
  23215. std::string second_head = "POST /post HTTP/1.1\r\n"
  23216. "Host: localhost\r\n"
  23217. "Content-Length: " +
  23218. std::to_string(inner.size()) +
  23219. "\r\n"
  23220. "\r\n";
  23221. for (auto target : {"/upload", "/upload?retry"}) {
  23222. smuggled_count = 0;
  23223. std::string request = "POST " + std::string(target) +
  23224. " HTTP/1.1\r\n"
  23225. "Host: localhost\r\n"
  23226. "Content-Length: " +
  23227. std::to_string(second_head.size()) +
  23228. "\r\n"
  23229. "\r\n" +
  23230. std::string(second_head.size(), 'A') + second_head +
  23231. inner;
  23232. std::string response;
  23233. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23234. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23235. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23236. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23237. EXPECT_EQ(0, smuggled_count.load()) << target;
  23238. }
  23239. }
  23240. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23241. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23242. // must be rejected with 400 Bad Request.
  23243. Server svr;
  23244. svr.Post("/test", [&](const Request &, Response &res) {
  23245. res.set_content("ok", "text/plain");
  23246. });
  23247. thread t = thread([&] { svr.listen(HOST, PORT); });
  23248. auto se = detail::scope_exit([&] {
  23249. svr.stop();
  23250. t.join();
  23251. ASSERT_FALSE(svr.is_running());
  23252. });
  23253. svr.wait_until_ready();
  23254. // Exact "chunked"
  23255. {
  23256. auto req = "POST /test HTTP/1.1\r\n"
  23257. "Host: localhost\r\n"
  23258. "Content-Length: 5\r\n"
  23259. "Transfer-Encoding: chunked\r\n"
  23260. "Connection: close\r\n"
  23261. "\r\n"
  23262. "hello";
  23263. std::string response;
  23264. ASSERT_TRUE(send_request(1, req, &response));
  23265. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23266. response.substr(0, response.find("\r\n")));
  23267. }
  23268. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23269. {
  23270. auto req = "POST /test HTTP/1.1\r\n"
  23271. "Host: localhost\r\n"
  23272. "Content-Length: 5\r\n"
  23273. "Transfer-Encoding: gzip, chunked\r\n"
  23274. "Connection: close\r\n"
  23275. "\r\n"
  23276. "hello";
  23277. std::string response;
  23278. ASSERT_TRUE(send_request(1, req, &response));
  23279. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23280. response.substr(0, response.find("\r\n")));
  23281. }
  23282. }
  23283. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23284. Server svr;
  23285. svr.Post("/test", [&](const Request &, Response &res) {
  23286. res.set_content("ok", "text/plain");
  23287. });
  23288. thread t = thread([&] { svr.listen(HOST, PORT); });
  23289. auto se = detail::scope_exit([&] {
  23290. svr.stop();
  23291. t.join();
  23292. ASSERT_FALSE(svr.is_running());
  23293. });
  23294. svr.wait_until_ready();
  23295. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23296. // length cannot be determined, so the server must answer 400 and close
  23297. // rather than treat the request as bodyless and leave the body in the
  23298. // socket for the next request to pick up.
  23299. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23300. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23301. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23302. std::string response;
  23303. ASSERT_TRUE(send_request(1, req, &response));
  23304. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23305. response.substr(0, response.find("\r\n")))
  23306. << transfer_encoding;
  23307. }
  23308. // RFC 9110 5.3: the codings may also be split across several
  23309. // Transfer-Encoding lines, which combine in the order they were received.
  23310. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23311. // just like the single-line "chunked, gzip" above.
  23312. {
  23313. auto req = "POST /test HTTP/1.1\r\n"
  23314. "Host: localhost\r\n"
  23315. "Transfer-Encoding: chunked\r\n"
  23316. "Transfer-Encoding: gzip\r\n"
  23317. "\r\n"
  23318. "0\r\n\r\n";
  23319. std::string response;
  23320. ASSERT_TRUE(send_request(1, req, &response));
  23321. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23322. response.substr(0, response.find("\r\n")));
  23323. }
  23324. // A sequence ending in chunked stays valid.
  23325. auto req = "POST /test HTTP/1.1\r\n"
  23326. "Host: localhost\r\n"
  23327. "Transfer-Encoding: gzip, chunked\r\n"
  23328. "Connection: close\r\n"
  23329. "\r\n"
  23330. "0\r\n\r\n";
  23331. std::string response;
  23332. ASSERT_TRUE(send_request(1, req, &response));
  23333. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23334. // ...including when it is spread over several lines.
  23335. auto split_req = "POST /test HTTP/1.1\r\n"
  23336. "Host: localhost\r\n"
  23337. "Transfer-Encoding: gzip\r\n"
  23338. "Transfer-Encoding: chunked\r\n"
  23339. "Connection: close\r\n"
  23340. "\r\n"
  23341. "0\r\n\r\n";
  23342. std::string split_response;
  23343. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23344. EXPECT_EQ("HTTP/1.1 200 OK",
  23345. split_response.substr(0, split_response.find("\r\n")));
  23346. }
  23347. // Regression for issue #2450: a DELETE without Content-Length on a
  23348. // keep-alive connection must not let the post-response drain consume the
  23349. // next request's bytes.
  23350. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23351. Server svr;
  23352. std::atomic<int> delete_count(0);
  23353. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23354. delete_count++;
  23355. res.status = StatusCode::NoContent_204;
  23356. });
  23357. auto port = svr.bind_to_any_port(HOST);
  23358. thread t = thread([&] { svr.listen_after_bind(); });
  23359. auto se = detail::scope_exit([&] {
  23360. svr.stop();
  23361. t.join();
  23362. });
  23363. svr.wait_until_ready();
  23364. auto error = Error::Success;
  23365. auto sock = detail::create_client_socket(
  23366. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23367. /*connection_timeout_sec=*/2, 0,
  23368. /*read_timeout_sec=*/2, 0,
  23369. /*write_timeout_sec=*/2, 0, std::string(), error);
  23370. ASSERT_NE(INVALID_SOCKET, sock);
  23371. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23372. auto send_request_and_read_response = [&](const std::string &req,
  23373. std::string &out) -> bool {
  23374. auto sent = send(sock, req.data(), req.size(), 0);
  23375. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23376. char buf[4096];
  23377. for (;;) {
  23378. auto n = recv(sock, buf, sizeof(buf), 0);
  23379. if (n <= 0) { return !out.empty(); }
  23380. out.append(buf, static_cast<size_t>(n));
  23381. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23382. }
  23383. };
  23384. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23385. "Host: localhost\r\n"
  23386. "\r\n";
  23387. std::string resp1;
  23388. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23389. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23390. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23391. "Host: localhost\r\n"
  23392. "Connection: close\r\n"
  23393. "\r\n";
  23394. std::string resp2;
  23395. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23396. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23397. EXPECT_EQ(2, delete_count.load());
  23398. }
  23399. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23400. Server svr;
  23401. svr.Post("/ingest", [&](const Request &, Response &res,
  23402. const ContentReader &content_reader) {
  23403. auto consumed = content_reader([](const char *, size_t) { return false; });
  23404. EXPECT_FALSE(consumed);
  23405. res.status = StatusCode::Conflict_409;
  23406. res.set_header("Connection", "close");
  23407. });
  23408. auto port = svr.bind_to_any_port(HOST);
  23409. thread t = thread([&] { svr.listen_after_bind(); });
  23410. auto se = detail::scope_exit([&] {
  23411. svr.stop();
  23412. t.join();
  23413. });
  23414. svr.wait_until_ready();
  23415. auto error = Error::Success;
  23416. auto sock = detail::create_client_socket(
  23417. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23418. /*connection_timeout_sec=*/2, 0,
  23419. /*read_timeout_sec=*/1, 0,
  23420. /*write_timeout_sec=*/2, 0, std::string(), error);
  23421. ASSERT_NE(INVALID_SOCKET, sock);
  23422. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23423. std::string request = "POST /ingest HTTP/1.1\r\n"
  23424. "Host: localhost\r\n"
  23425. "Transfer-Encoding: chunked\r\n"
  23426. "\r\n"
  23427. "4\r\n"
  23428. "data\r\n";
  23429. auto sent = send(sock, request.data(), request.size(), 0);
  23430. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23431. std::string response;
  23432. ssize_t received = 0;
  23433. do {
  23434. char buf[4096];
  23435. received = recv(sock, buf, sizeof(buf), 0);
  23436. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23437. } while (received > 0);
  23438. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23439. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23440. EXPECT_EQ(0, received);
  23441. }
  23442. namespace no_proxy_test {
  23443. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23444. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23445. // calling listen().
  23446. class ScopedServer {
  23447. public:
  23448. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23449. ~ScopedServer() {
  23450. svr_.stop();
  23451. if (th_.joinable()) { th_.join(); }
  23452. }
  23453. Server &svr() { return svr_; }
  23454. int port() const { return port_; }
  23455. void listen() {
  23456. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23457. svr_.wait_until_ready();
  23458. }
  23459. private:
  23460. Server svr_;
  23461. std::thread th_;
  23462. int port_ = 0;
  23463. };
  23464. class ProxyAndTargetServers {
  23465. public:
  23466. ProxyAndTargetServers() {
  23467. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23468. proxy_hits_++;
  23469. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23470. res.set_content("via-proxy", "text/plain");
  23471. });
  23472. target_.Get(".*", [this](const Request &req, Response &res) {
  23473. target_hits_++;
  23474. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23475. res.set_content("direct", "text/plain");
  23476. });
  23477. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23478. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23479. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23480. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23481. proxy_mock_.wait_until_ready();
  23482. target_.wait_until_ready();
  23483. }
  23484. ~ProxyAndTargetServers() {
  23485. proxy_mock_.stop();
  23486. target_.stop();
  23487. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23488. if (target_thread_.joinable()) { target_thread_.join(); }
  23489. }
  23490. Server &proxy_mock() { return proxy_mock_; }
  23491. Server &target() { return target_; }
  23492. int proxy_port() const { return proxy_port_; }
  23493. int target_port() const { return target_port_; }
  23494. int proxy_hits() const { return proxy_hits_.load(); }
  23495. int target_hits() const { return target_hits_.load(); }
  23496. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23497. void reset_counters() {
  23498. proxy_hits_ = 0;
  23499. target_hits_ = 0;
  23500. last_had_proxy_authz_ = false;
  23501. }
  23502. private:
  23503. Server proxy_mock_;
  23504. Server target_;
  23505. std::thread proxy_thread_;
  23506. std::thread target_thread_;
  23507. int proxy_port_ = 0;
  23508. int target_port_ = 0;
  23509. std::atomic<int> proxy_hits_{0};
  23510. std::atomic<int> target_hits_{0};
  23511. std::atomic<bool> last_had_proxy_authz_{false};
  23512. };
  23513. inline std::unique_ptr<Client> make_client(const std::string &host,
  23514. ProxyAndTargetServers &s) {
  23515. auto cli = detail::make_unique<Client>(host, s.target_port());
  23516. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23517. cli->set_proxy("127.0.0.1", s.proxy_port());
  23518. return cli;
  23519. }
  23520. } // namespace no_proxy_test
  23521. using no_proxy_test::make_client;
  23522. using no_proxy_test::ProxyAndTargetServers;
  23523. TEST(NoProxyTest, ExactHostnameBypasses) {
  23524. ProxyAndTargetServers s;
  23525. auto cli = make_client("example.com", s);
  23526. cli->set_no_proxy({"example.com"});
  23527. auto res = cli->Get("/");
  23528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23529. EXPECT_EQ(0, s.proxy_hits());
  23530. EXPECT_EQ(1, s.target_hits());
  23531. }
  23532. TEST(NoProxyTest, SubdomainBypasses) {
  23533. ProxyAndTargetServers s;
  23534. auto cli = make_client("foo.example.com", s);
  23535. cli->set_no_proxy({"example.com"});
  23536. auto res = cli->Get("/");
  23537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23538. EXPECT_EQ(0, s.proxy_hits());
  23539. EXPECT_EQ(1, s.target_hits());
  23540. }
  23541. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23542. // Regression guard: "evilexample.com" must not be considered a subdomain
  23543. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23544. // check would let traffic bypass the proxy and leak credentials direct
  23545. // to the attacker host.
  23546. ProxyAndTargetServers s;
  23547. auto cli = make_client("evilexample.com", s);
  23548. cli->set_no_proxy({"example.com"});
  23549. auto res = cli->Get("/");
  23550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23551. EXPECT_GE(s.proxy_hits(), 1);
  23552. EXPECT_EQ(0, s.target_hits());
  23553. }
  23554. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23555. ProxyAndTargetServers s;
  23556. auto cli = make_client("example.com.evil.com", s);
  23557. cli->set_no_proxy({"example.com"});
  23558. auto res = cli->Get("/");
  23559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23560. EXPECT_GE(s.proxy_hits(), 1);
  23561. EXPECT_EQ(0, s.target_hits());
  23562. }
  23563. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23564. ProxyAndTargetServers s;
  23565. auto cli = make_client("example.com", s);
  23566. cli->set_no_proxy({".example.com"});
  23567. auto res = cli->Get("/");
  23568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23569. EXPECT_EQ(0, s.proxy_hits());
  23570. EXPECT_EQ(1, s.target_hits());
  23571. }
  23572. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23573. ProxyAndTargetServers s;
  23574. auto cli = make_client("Example.COM", s);
  23575. cli->set_no_proxy({"EXAMPLE.com"});
  23576. auto res = cli->Get("/");
  23577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23578. EXPECT_EQ(0, s.proxy_hits());
  23579. EXPECT_EQ(1, s.target_hits());
  23580. }
  23581. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23582. ProxyAndTargetServers s;
  23583. auto cli = make_client("example.com.", s);
  23584. cli->set_no_proxy({"example.com"});
  23585. auto res = cli->Get("/");
  23586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23587. EXPECT_EQ(0, s.proxy_hits());
  23588. EXPECT_EQ(1, s.target_hits());
  23589. }
  23590. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23591. // Trailing dots must be normalized on BOTH sides — host and entry.
  23592. // An implementation that only strips the host-side trailing dot would
  23593. // fail to match host "example.com" against entry "example.com." because
  23594. // a literal substring search would compare 11 chars against 12.
  23595. ProxyAndTargetServers s;
  23596. auto cli = make_client("example.com", s);
  23597. cli->set_no_proxy({"example.com."});
  23598. auto res = cli->Get("/");
  23599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23600. EXPECT_EQ(0, s.proxy_hits());
  23601. EXPECT_EQ(1, s.target_hits());
  23602. }
  23603. TEST(NoProxyTest, WildcardBypassesEverything) {
  23604. ProxyAndTargetServers s;
  23605. auto cli = make_client("anything.invalid.test", s);
  23606. cli->set_no_proxy({"*"});
  23607. auto res = cli->Get("/");
  23608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23609. EXPECT_EQ(0, s.proxy_hits());
  23610. EXPECT_EQ(1, s.target_hits());
  23611. }
  23612. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23613. ProxyAndTargetServers s;
  23614. Client cli("127.0.0.1", s.target_port());
  23615. cli.set_proxy("127.0.0.1", s.proxy_port());
  23616. cli.set_no_proxy({"127.0.0.1"});
  23617. auto res = cli.Get("/");
  23618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23619. EXPECT_EQ(0, s.proxy_hits());
  23620. EXPECT_EQ(1, s.target_hits());
  23621. }
  23622. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23623. ProxyAndTargetServers s;
  23624. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23625. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23626. cli.set_proxy("127.0.0.1", s.proxy_port());
  23627. cli.set_no_proxy({"::1"});
  23628. auto res = cli.Get("/");
  23629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23630. EXPECT_EQ(0, s.proxy_hits());
  23631. EXPECT_EQ(1, s.target_hits());
  23632. }
  23633. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23634. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23635. // must still be recognized as IPv6 for CIDR matching. Implementations
  23636. // that detect IPv6 only when the host begins with '[' would parse the
  23637. // host as a hostname and miss the match.
  23638. ProxyAndTargetServers s;
  23639. Client cli("fe80::1", s.target_port());
  23640. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23641. cli.set_proxy("127.0.0.1", s.proxy_port());
  23642. cli.set_no_proxy({"fe80::/10"});
  23643. auto res = cli.Get("/");
  23644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23645. EXPECT_EQ(0, s.proxy_hits());
  23646. EXPECT_EQ(1, s.target_hits());
  23647. }
  23648. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23649. ProxyAndTargetServers s;
  23650. Client cli("::1", s.target_port());
  23651. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23652. cli.set_proxy("127.0.0.1", s.proxy_port());
  23653. cli.set_no_proxy({"[::1]"});
  23654. auto res = cli.Get("/");
  23655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23656. EXPECT_EQ(0, s.proxy_hits());
  23657. EXPECT_EQ(1, s.target_hits());
  23658. }
  23659. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23660. ProxyAndTargetServers s;
  23661. Client cli("fe80::1", s.target_port());
  23662. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23663. cli.set_proxy("127.0.0.1", s.proxy_port());
  23664. cli.set_no_proxy({"[fe80::]/10"});
  23665. auto res = cli.Get("/");
  23666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23667. EXPECT_EQ(0, s.proxy_hits());
  23668. EXPECT_EQ(1, s.target_hits());
  23669. }
  23670. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23671. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23672. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23673. // tricks via address-family conversion.
  23674. ProxyAndTargetServers s;
  23675. Client cli("::ffff:127.0.0.1", s.target_port());
  23676. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23677. cli.set_proxy("127.0.0.1", s.proxy_port());
  23678. cli.set_no_proxy({"127.0.0.1"});
  23679. auto res = cli.Get("/");
  23680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23681. EXPECT_GE(s.proxy_hits(), 1);
  23682. EXPECT_EQ(0, s.target_hits());
  23683. }
  23684. TEST(NoProxyTest, IPv4CidrMatch) {
  23685. ProxyAndTargetServers s;
  23686. Client cli("127.0.0.1", s.target_port());
  23687. cli.set_proxy("127.0.0.1", s.proxy_port());
  23688. cli.set_no_proxy({"127.0.0.0/8"});
  23689. auto res = cli.Get("/");
  23690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23691. EXPECT_EQ(0, s.proxy_hits());
  23692. EXPECT_EQ(1, s.target_hits());
  23693. }
  23694. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23695. ProxyAndTargetServers s;
  23696. Client cli("127.0.0.1", s.target_port());
  23697. cli.set_proxy("127.0.0.1", s.proxy_port());
  23698. cli.set_no_proxy({"10.0.0.0/8"});
  23699. auto res = cli.Get("/");
  23700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23701. EXPECT_GE(s.proxy_hits(), 1);
  23702. EXPECT_EQ(0, s.target_hits());
  23703. }
  23704. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23705. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23706. // IPv4 target matches.
  23707. ProxyAndTargetServers s;
  23708. Client cli("127.0.0.1", s.target_port());
  23709. cli.set_proxy("127.0.0.1", s.proxy_port());
  23710. cli.set_no_proxy({"0.0.0.0/0"});
  23711. auto res = cli.Get("/");
  23712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23713. EXPECT_EQ(0, s.proxy_hits());
  23714. EXPECT_EQ(1, s.target_hits());
  23715. }
  23716. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23717. ProxyAndTargetServers s;
  23718. Client cli("127.0.0.1", s.target_port());
  23719. cli.set_proxy("127.0.0.1", s.proxy_port());
  23720. cli.set_no_proxy({"127.0.0.1"});
  23721. auto res = cli.Get("/");
  23722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23723. EXPECT_EQ(0, s.proxy_hits());
  23724. EXPECT_EQ(1, s.target_hits());
  23725. }
  23726. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23727. ProxyAndTargetServers s;
  23728. Client cli("127.0.0.1", s.target_port());
  23729. cli.set_proxy("127.0.0.1", s.proxy_port());
  23730. cli.set_no_proxy({"127.0.0.0/33"});
  23731. auto res = cli.Get("/");
  23732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23733. EXPECT_GE(s.proxy_hits(), 1);
  23734. EXPECT_EQ(0, s.target_hits());
  23735. }
  23736. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23737. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23738. ProxyAndTargetServers s;
  23739. Client cli("127.0.0.1", s.target_port());
  23740. cli.set_proxy("127.0.0.1", s.proxy_port());
  23741. cli.set_no_proxy({"127.0.0.1/"});
  23742. auto res = cli.Get("/");
  23743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23744. EXPECT_GE(s.proxy_hits(), 1);
  23745. EXPECT_EQ(0, s.target_hits());
  23746. }
  23747. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23748. ProxyAndTargetServers s;
  23749. auto cli = make_client("internal.corp", s);
  23750. cli->set_proxy_basic_auth("u", "p");
  23751. cli->set_no_proxy({"internal.corp"});
  23752. auto res = cli->Get("/");
  23753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23754. EXPECT_EQ(1, s.target_hits());
  23755. EXPECT_EQ(0, s.proxy_hits());
  23756. EXPECT_FALSE(s.last_had_proxy_authz())
  23757. << "Proxy-Authorization must not be sent direct to the target";
  23758. }
  23759. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23760. ProxyAndTargetServers s;
  23761. auto cli = make_client("public.example", s);
  23762. cli->set_proxy_basic_auth("u", "p");
  23763. cli->set_no_proxy({"internal.corp"}); // does not match
  23764. auto res = cli->Get("/");
  23765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23766. EXPECT_GE(s.proxy_hits(), 1);
  23767. EXPECT_TRUE(s.last_had_proxy_authz());
  23768. }
  23769. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23770. std::atomic<int> hits{0};
  23771. std::atomic<int> hits_with_authz{0};
  23772. no_proxy_test::ScopedServer proxy_mock;
  23773. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23774. hits++;
  23775. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23776. if (req.target.find("/redir") != std::string::npos) {
  23777. res.set_redirect("http://other.example/landed");
  23778. } else {
  23779. res.set_content("via-proxy", "text/plain");
  23780. }
  23781. });
  23782. proxy_mock.listen();
  23783. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23784. hits = 0;
  23785. hits_with_authz = 0;
  23786. Client cli("public.example", 80);
  23787. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23788. cli.set_proxy_basic_auth(c.first, c.second);
  23789. cli.set_follow_location(true);
  23790. // The redirect to another host goes through the proxy as well
  23791. auto res = cli.Get("/redir");
  23792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23793. EXPECT_EQ(2, hits.load());
  23794. EXPECT_EQ(2, hits_with_authz.load());
  23795. }
  23796. }
  23797. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23798. ProxyAndTargetServers s;
  23799. auto cli = make_client("anything.test", s);
  23800. auto res = cli->Get("/");
  23801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23802. EXPECT_GE(s.proxy_hits(), 1);
  23803. EXPECT_EQ(0, s.target_hits());
  23804. }
  23805. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23806. ProxyAndTargetServers s;
  23807. auto cli = make_client("example.com", s);
  23808. cli->set_no_proxy({"example.com:8080"});
  23809. auto res = cli->Get("/");
  23810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23811. EXPECT_GE(s.proxy_hits(), 1);
  23812. EXPECT_EQ(0, s.target_hits());
  23813. }
  23814. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23815. ProxyAndTargetServers s;
  23816. auto cli = make_client("anything.test", s);
  23817. cli->set_no_proxy({"", " ", "\t"});
  23818. auto res = cli->Get("/");
  23819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23820. EXPECT_GE(s.proxy_hits(), 1);
  23821. EXPECT_EQ(0, s.target_hits());
  23822. }
  23823. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23824. // An entry with leading/trailing whitespace must still match — env-style
  23825. // values are commonly pasted with stray spaces and an implementation
  23826. // that feeds the raw token directly to inet_pton would fail to match
  23827. // valid CIDRs because of the spaces.
  23828. ProxyAndTargetServers s;
  23829. Client cli("127.0.0.1", s.target_port());
  23830. cli.set_proxy("127.0.0.1", s.proxy_port());
  23831. cli.set_no_proxy({" 127.0.0.0/8 "});
  23832. auto res = cli.Get("/");
  23833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23834. EXPECT_EQ(0, s.proxy_hits());
  23835. EXPECT_EQ(1, s.target_hits());
  23836. }
  23837. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23838. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23839. // go direct and must NOT carry Proxy-Authorization.
  23840. std::atomic<int> proxy_hits{0};
  23841. std::atomic<int> target_hits{0};
  23842. std::atomic<bool> target_saw_authz{false};
  23843. no_proxy_test::ScopedServer proxy_mock, target;
  23844. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23845. proxy_hits++;
  23846. res.status = 302;
  23847. res.set_header("Location", "http://127.0.0.1:" +
  23848. std::to_string(target.port()) + "/landed");
  23849. });
  23850. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23851. target_hits++;
  23852. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23853. res.set_content("direct", "text/plain");
  23854. });
  23855. proxy_mock.listen();
  23856. target.listen();
  23857. Client cli("public.example", target.port());
  23858. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23859. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23860. cli.set_proxy_basic_auth("u", "p");
  23861. cli.set_no_proxy({"127.0.0.1"});
  23862. cli.set_follow_location(true);
  23863. auto res = cli.Get("/redir");
  23864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23865. EXPECT_GE(proxy_hits.load(), 1);
  23866. EXPECT_GE(target_hits.load(), 1);
  23867. EXPECT_FALSE(target_saw_authz.load());
  23868. }
  23869. #ifdef CPPHTTPLIB_SSL_ENABLED
  23870. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23871. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23872. // proxy creds would be sent to the (possibly hostile) origin.
  23873. std::atomic<int> target_hits{0};
  23874. std::atomic<bool> target_saw_proxy_authz{false};
  23875. no_proxy_test::ScopedServer target;
  23876. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23877. target_hits++;
  23878. if (req.has_header("Proxy-Authorization")) {
  23879. target_saw_proxy_authz = true;
  23880. }
  23881. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23882. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23883. "nonce=\"abc\", algorithm=MD5");
  23884. });
  23885. target.listen();
  23886. // The proxy address is set to the target's port: the bypass MUST kick in;
  23887. // if it doesn't, the test still routes "via proxy" to the same server and
  23888. // the Proxy-Authorization assertion below catches the leak.
  23889. Client cli("evil.example", target.port());
  23890. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23891. cli.set_proxy("127.0.0.1", target.port());
  23892. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23893. cli.set_no_proxy({"evil.example"});
  23894. auto res = cli.Get("/x");
  23895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23896. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23897. EXPECT_EQ(1, target_hits.load());
  23898. EXPECT_FALSE(target_saw_proxy_authz.load());
  23899. }
  23900. #endif
  23901. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23902. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23903. std::atomic<int> proxy_hits{0};
  23904. std::atomic<int> bypass_hits{0};
  23905. std::atomic<bool> proxy_saw_c_url{false};
  23906. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23907. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23908. proxy_hits++;
  23909. if (req.path.find("/start") != std::string::npos) {
  23910. res.status = 302;
  23911. res.set_header("Location", "http://127.0.0.1:" +
  23912. std::to_string(bypass_server.port()) +
  23913. "/middle");
  23914. return;
  23915. }
  23916. if (req.path.find("/end") != std::string::npos) {
  23917. proxy_saw_c_url = true;
  23918. res.set_content("c-via-proxy", "text/plain");
  23919. return;
  23920. }
  23921. res.set_content("unexpected", "text/plain");
  23922. });
  23923. // public.example's "advertised" port is arbitrary (the request never lands
  23924. // there — it goes through the proxy), but use a dynamic value to stay
  23925. // friendly with sharded parallel runs.
  23926. int public_port = bypass_server.port();
  23927. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23928. bypass_hits++;
  23929. res.status = 302;
  23930. res.set_header("Location", "http://public.example:" +
  23931. std::to_string(public_port) + "/end");
  23932. });
  23933. proxy_mock.listen();
  23934. bypass_server.listen();
  23935. Client cli("public.example", public_port);
  23936. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23937. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23938. cli.set_no_proxy({"127.0.0.1"});
  23939. cli.set_follow_location(true);
  23940. auto res = cli.Get("/start");
  23941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23942. EXPECT_EQ(StatusCode::OK_200, res->status);
  23943. EXPECT_EQ("c-via-proxy", res->body);
  23944. EXPECT_GE(proxy_hits.load(), 2);
  23945. EXPECT_GE(bypass_hits.load(), 1);
  23946. EXPECT_TRUE(proxy_saw_c_url.load());
  23947. }
  23948. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23949. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23950. // request reconnects to the correct endpoint.
  23951. std::atomic<int> proxy_hits{0};
  23952. std::atomic<int> target_hits{0};
  23953. no_proxy_test::ScopedServer proxy_mock, target;
  23954. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23955. proxy_hits++;
  23956. res.set_content("via-proxy", "text/plain");
  23957. });
  23958. target.svr().Get(".*", [&](const Request &, Response &res) {
  23959. target_hits++;
  23960. res.set_content("direct", "text/plain");
  23961. });
  23962. proxy_mock.listen();
  23963. target.listen();
  23964. Client cli("public.example", target.port());
  23965. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23966. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23967. cli.set_keep_alive(true);
  23968. auto res1 = cli.Get("/a");
  23969. ASSERT_TRUE(res1);
  23970. EXPECT_EQ("via-proxy", res1->body);
  23971. EXPECT_EQ(1, proxy_hits.load());
  23972. EXPECT_EQ(0, target_hits.load());
  23973. cli.set_no_proxy({"public.example"});
  23974. auto res2 = cli.Get("/b");
  23975. ASSERT_TRUE(res2);
  23976. EXPECT_EQ("direct", res2->body);
  23977. EXPECT_EQ(1, proxy_hits.load());
  23978. EXPECT_EQ(1, target_hits.load());
  23979. }
  23980. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23981. namespace proxy_tunnel_test {
  23982. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23983. class ScopedSSLServer {
  23984. public:
  23985. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23986. port_ = svr_.bind_to_any_port("127.0.0.1");
  23987. }
  23988. ~ScopedSSLServer() {
  23989. svr_.stop();
  23990. if (th_.joinable()) { th_.join(); }
  23991. }
  23992. SSLServer &svr() { return svr_; }
  23993. int port() const { return port_; }
  23994. void listen() {
  23995. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23996. svr_.wait_until_ready();
  23997. }
  23998. private:
  23999. SSLServer svr_;
  24000. std::thread th_;
  24001. int port_ = 0;
  24002. };
  24003. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24004. class ScopedConnectProxy {
  24005. public:
  24006. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24007. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24008. if (listen_fd_ < 0) { return; }
  24009. int yes = 1;
  24010. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24011. sockaddr_in a{};
  24012. a.sin_family = AF_INET;
  24013. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24014. a.sin_port = 0;
  24015. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24016. return;
  24017. }
  24018. socklen_t alen = sizeof(a);
  24019. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24020. 0) {
  24021. return;
  24022. }
  24023. port_ = ntohs(a.sin_port);
  24024. if (::listen(listen_fd_, 1) != 0) { return; }
  24025. th_ = std::thread([this] { run(); });
  24026. }
  24027. ~ScopedConnectProxy() {
  24028. stop_ = true;
  24029. if (listen_fd_ >= 0) {
  24030. ::shutdown(listen_fd_, SHUT_RDWR);
  24031. ::close(listen_fd_);
  24032. }
  24033. if (th_.joinable()) { th_.join(); }
  24034. }
  24035. int port() const { return port_; }
  24036. int connect_hits() const { return connect_hits_.load(); }
  24037. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24038. std::string connect_request() const {
  24039. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24040. return connect_request_;
  24041. }
  24042. private:
  24043. void run() {
  24044. while (!stop_.load()) {
  24045. fd_set rfds;
  24046. FD_ZERO(&rfds);
  24047. FD_SET(listen_fd_, &rfds);
  24048. timeval tv{0, 100 * 1000};
  24049. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24050. if (sel <= 0) { continue; }
  24051. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24052. if (client_fd < 0) { continue; }
  24053. std::string req;
  24054. char buf[2048];
  24055. while (req.find("\r\n\r\n") == std::string::npos) {
  24056. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24057. if (n <= 0) { break; }
  24058. req.append(buf, static_cast<size_t>(n));
  24059. }
  24060. if (req.compare(0, 7, "CONNECT") != 0) {
  24061. ::close(client_fd);
  24062. continue;
  24063. }
  24064. connect_hits_++;
  24065. {
  24066. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24067. connect_request_ = req;
  24068. }
  24069. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24070. ::send(client_fd, ok, std::strlen(ok), 0);
  24071. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24072. sockaddr_in o{};
  24073. o.sin_family = AF_INET;
  24074. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24075. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24076. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24077. 0) {
  24078. ::close(client_fd);
  24079. ::close(origin_fd);
  24080. continue;
  24081. }
  24082. auto forward = [](int from, int to) {
  24083. char b[8192];
  24084. for (;;) {
  24085. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24086. if (n <= 0) { break; }
  24087. ssize_t off = 0;
  24088. while (off < n) {
  24089. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24090. if (s <= 0) {
  24091. off = n;
  24092. break;
  24093. }
  24094. off += s;
  24095. }
  24096. }
  24097. ::shutdown(to, SHUT_WR);
  24098. };
  24099. std::thread t1([&] { forward(client_fd, origin_fd); });
  24100. std::thread t2([&] { forward(origin_fd, client_fd); });
  24101. t1.join();
  24102. t2.join();
  24103. ::close(client_fd);
  24104. ::close(origin_fd);
  24105. }
  24106. }
  24107. int forward_port_ = -1;
  24108. int listen_fd_ = -1;
  24109. int port_ = 0;
  24110. std::thread th_;
  24111. std::atomic<bool> stop_{false};
  24112. std::atomic<int> connect_hits_{0};
  24113. mutable std::mutex connect_request_mutex_;
  24114. std::string connect_request_;
  24115. };
  24116. // Sends one request through the CONNECT proxy to the TLS origin with a
  24117. // credential configured for each hop, and checks that each credential reaches
  24118. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24119. // origin's (every header in origin_headers) on the tunnelled request.
  24120. void CredentialsStayWithTheirHop(
  24121. const std::function<void(SSLClient &)> &set_credentials,
  24122. const std::string &scheme,
  24123. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24124. std::atomic<int> origin_hits{0};
  24125. std::atomic<bool> origin_saw_proxy_authz{false};
  24126. std::atomic<bool> origin_saw_headers{false};
  24127. ScopedSSLServer origin;
  24128. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24129. origin_hits++;
  24130. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24131. origin_saw_headers =
  24132. std::all_of(origin_headers.begin(), origin_headers.end(),
  24133. [&](const std::string &h) { return req.has_header(h); });
  24134. res.set_content("ok", "text/plain");
  24135. });
  24136. origin.listen();
  24137. ScopedConnectProxy proxy(origin.port());
  24138. ASSERT_NE(0, proxy.port());
  24139. // Pinned to 127.0.0.1 for the same reason as the test below.
  24140. SSLClient cli("127.0.0.1", origin.port());
  24141. cli.enable_server_certificate_verification(false);
  24142. cli.set_proxy("127.0.0.1", proxy.port());
  24143. set_credentials(cli);
  24144. auto res = cli.Get("/x");
  24145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24146. EXPECT_EQ(StatusCode::OK_200, res->status);
  24147. EXPECT_EQ(1, origin_hits.load());
  24148. EXPECT_EQ(1, proxy.connect_hits());
  24149. EXPECT_TRUE(origin_saw_headers.load());
  24150. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24151. << "Proxy-Authorization must not be sent inside the tunnel";
  24152. auto connect_req = proxy.connect_request();
  24153. EXPECT_NE(std::string::npos,
  24154. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24155. for (const auto &h : origin_headers) {
  24156. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24157. << h << " must not be sent to the proxy on CONNECT";
  24158. }
  24159. }
  24160. } // namespace proxy_tunnel_test
  24161. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24162. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24163. [](SSLClient &cli) {
  24164. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24165. cli.set_basic_auth("origin-user", "origin-pass");
  24166. },
  24167. "Basic");
  24168. }
  24169. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24170. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24171. [](SSLClient &cli) {
  24172. cli.set_proxy_bearer_token_auth("proxy-token");
  24173. cli.set_bearer_token_auth("origin-token");
  24174. },
  24175. "Bearer");
  24176. }
  24177. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24178. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24179. [](SSLClient &cli) {
  24180. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24181. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24182. {"Cookie", "sid=origin-session"},
  24183. {"X-Api-Key", "origin-key"}});
  24184. },
  24185. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24186. }
  24187. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24188. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24189. // retry; otherwise proxy creds would be sent to the origin.
  24190. std::atomic<int> origin_hits{0};
  24191. std::atomic<bool> origin_saw_proxy_authz{false};
  24192. proxy_tunnel_test::ScopedSSLServer origin;
  24193. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24194. origin_hits++;
  24195. if (req.has_header("Proxy-Authorization")) {
  24196. origin_saw_proxy_authz = true;
  24197. }
  24198. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24199. res.set_header("Proxy-Authenticate",
  24200. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24201. "algorithm=MD5");
  24202. });
  24203. origin.listen();
  24204. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24205. ASSERT_NE(0, proxy.port());
  24206. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24207. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24208. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24209. // and answer with its own status, making this test flaky.
  24210. SSLClient cli("127.0.0.1", origin.port());
  24211. cli.enable_server_certificate_verification(false);
  24212. cli.set_proxy("127.0.0.1", proxy.port());
  24213. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24214. auto res = cli.Get("/x");
  24215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24216. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24217. EXPECT_EQ(1, origin_hits.load());
  24218. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24219. EXPECT_EQ(1, proxy.connect_hits());
  24220. }
  24221. #endif