test.cc 996 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641
  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 definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1949. }
  1950. {
  1951. Ranges ranges;
  1952. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1953. EXPECT_TRUE(ret);
  1954. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1955. }
  1956. {
  1957. Ranges ranges;
  1958. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1959. EXPECT_FALSE(ret);
  1960. }
  1961. {
  1962. Ranges ranges;
  1963. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1964. EXPECT_TRUE(ret);
  1965. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret =
  1970. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1977. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1989. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1990. EXPECT_FALSE(
  1991. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1992. EXPECT_TRUE(ranges.empty());
  1993. }
  1994. {
  1995. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1996. // remainder of the representation, so it stays accepted.
  1997. Ranges ranges;
  1998. auto ret =
  1999. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2000. EXPECT_TRUE(ret);
  2001. ASSERT_EQ(1u, ranges.size());
  2002. EXPECT_EQ(0, ranges[0].first);
  2003. EXPECT_EQ(-1, ranges[0].second);
  2004. }
  2005. // RFC 9110 14.1: range unit names are case-insensitive.
  2006. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2007. Ranges ranges;
  2008. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2009. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2010. }
  2011. }
  2012. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2013. Request req;
  2014. req.set_header("Accept-Encoding", "gzip");
  2015. Response res;
  2016. res.set_header("Content-Type", "text/plain");
  2017. auto ret = detail::encoding_type(req, res);
  2018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2019. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2020. #else
  2021. EXPECT_TRUE(ret == detail::EncodingType::None);
  2022. #endif
  2023. }
  2024. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2025. Request req;
  2026. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2027. Response res;
  2028. res.set_header("Content-Type", "text/plain");
  2029. auto ret = detail::encoding_type(req, res);
  2030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2031. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2032. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding",
  2043. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2044. Response res;
  2045. res.set_header("Content-Type", "text/plain");
  2046. auto ret = detail::encoding_type(req, res);
  2047. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2049. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2050. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2051. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2052. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2053. #else
  2054. EXPECT_TRUE(ret == detail::EncodingType::None);
  2055. #endif
  2056. }
  2057. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2058. // All supported encodings rejected with q=0 should return None
  2059. Request req;
  2060. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2061. Response res;
  2062. res.set_header("Content-Type", "text/plain");
  2063. auto ret = detail::encoding_type(req, res);
  2064. EXPECT_TRUE(ret == detail::EncodingType::None);
  2065. }
  2066. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2067. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2068. Request req;
  2069. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2070. Response res;
  2071. res.set_header("Content-Type", "text/plain");
  2072. auto ret = detail::encoding_type(req, res);
  2073. EXPECT_TRUE(ret == detail::EncodingType::None);
  2074. }
  2075. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2076. Request req;
  2077. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2078. Response res;
  2079. res.set_header("Content-Type", "text/plain");
  2080. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2081. }
  2082. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2083. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2092. // RFC 7231: Accept-Encoding values are case-insensitive
  2093. Request req;
  2094. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2095. Response res;
  2096. res.set_header("Content-Type", "text/plain");
  2097. auto ret = detail::encoding_type(req, res);
  2098. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2102. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2103. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2104. #else
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. #endif
  2107. }
  2108. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2109. // q value should determine priority, not hardcoded order
  2110. Request req;
  2111. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2112. Response res;
  2113. res.set_header("Content-Type", "text/plain");
  2114. auto ret = detail::encoding_type(req, res);
  2115. // gzip has highest q=1.0, so it should be selected even though
  2116. // br and zstd are also supported
  2117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2118. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2119. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2120. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2121. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2122. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2123. #else
  2124. EXPECT_TRUE(ret == detail::EncodingType::None);
  2125. #endif
  2126. }
  2127. TEST(BufferStreamTest, read) {
  2128. detail::BufferStream strm1;
  2129. Stream &strm = strm1;
  2130. EXPECT_EQ(5, strm.write("hello"));
  2131. char buf[512];
  2132. EXPECT_EQ(2, strm.read(buf, 2));
  2133. EXPECT_EQ('h', buf[0]);
  2134. EXPECT_EQ('e', buf[1]);
  2135. EXPECT_EQ(2, strm.read(buf, 2));
  2136. EXPECT_EQ('l', buf[0]);
  2137. EXPECT_EQ('l', buf[1]);
  2138. EXPECT_EQ(1, strm.read(buf, 1));
  2139. EXPECT_EQ('o', buf[0]);
  2140. EXPECT_EQ(0, strm.read(buf, 1));
  2141. }
  2142. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2143. auto host = "www.httpwatch.com";
  2144. auto ip = hosted_at(host);
  2145. EXPECT_EQ("23.96.13.243", ip);
  2146. std::vector<std::string> addrs;
  2147. hosted_at(host, addrs);
  2148. EXPECT_EQ(1u, addrs.size());
  2149. }
  2150. #if 0 // It depends on each test environment...
  2151. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2152. auto host = "www.youtube.com";
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(20u, addrs.size());
  2156. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2157. EXPECT_TRUE(it != addrs.end());
  2158. }
  2159. #endif
  2160. class ChunkedEncodingTest : public ::testing::Test {
  2161. protected:
  2162. ChunkedEncodingTest()
  2163. : cli_(HOST, PORT)
  2164. #ifdef CPPHTTPLIB_SSL_ENABLED
  2165. ,
  2166. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2167. #endif
  2168. {
  2169. cli_.set_connection_timeout(2);
  2170. #ifdef CPPHTTPLIB_SSL_ENABLED
  2171. cli_.enable_server_certificate_verification(false);
  2172. #endif
  2173. }
  2174. virtual void SetUp() {
  2175. read_file("./image.jpg", image_data_);
  2176. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2177. res.set_content("Hello World!", "text/plain");
  2178. });
  2179. svr_.Get(
  2180. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2181. res.set_chunked_content_provider(
  2182. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2183. size_t remaining = image_data_.size() - offset;
  2184. if (remaining == 0) {
  2185. sink.done();
  2186. } else {
  2187. constexpr size_t CHUNK_SIZE = 1024;
  2188. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2189. sink.write(&image_data_[offset], send_size);
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2191. }
  2192. return true;
  2193. });
  2194. });
  2195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2196. svr_.wait_until_ready();
  2197. }
  2198. virtual void TearDown() {
  2199. svr_.stop();
  2200. if (!request_threads_.empty()) {
  2201. std::this_thread::sleep_for(std::chrono::seconds(1));
  2202. for (auto &t : request_threads_) {
  2203. t.join();
  2204. }
  2205. }
  2206. t_.join();
  2207. }
  2208. #ifdef CPPHTTPLIB_SSL_ENABLED
  2209. SSLClient cli_;
  2210. SSLServer svr_;
  2211. #else
  2212. Client cli_;
  2213. Server svr_;
  2214. #endif
  2215. thread t_;
  2216. std::vector<thread> request_threads_;
  2217. std::string image_data_;
  2218. };
  2219. TEST_F(ChunkedEncodingTest, NormalGet) {
  2220. auto res = cli_.Get("/chunked");
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. std::string out;
  2223. read_file("./image.jpg", out);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. EXPECT_EQ(out, res->body);
  2226. }
  2227. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2228. std::string body;
  2229. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2230. body.append(data, data_length);
  2231. return true;
  2232. });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. std::string out;
  2235. read_file("./image.jpg", out);
  2236. EXPECT_EQ(StatusCode::OK_200, res->status);
  2237. EXPECT_EQ(out, body);
  2238. }
  2239. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2240. std::string body;
  2241. auto res = cli_.Get(
  2242. "/chunked",
  2243. [&](const Response &response) {
  2244. EXPECT_EQ(StatusCode::OK_200, response.status);
  2245. return true;
  2246. },
  2247. [&](const char *data, size_t data_length) {
  2248. body.append(data, data_length);
  2249. return true;
  2250. });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. std::string out;
  2253. read_file("./image.jpg", out);
  2254. EXPECT_EQ(StatusCode::OK_200, res->status);
  2255. EXPECT_EQ(out, body);
  2256. }
  2257. TEST(RangeTest, FromHTTPBin_Online) {
  2258. auto host = "httpbingo.org";
  2259. auto path = std::string{"/range/32"};
  2260. #ifdef CPPHTTPLIB_SSL_ENABLED
  2261. auto port = 443;
  2262. SSLClient cli(host, port);
  2263. #else
  2264. auto port = 80;
  2265. Client cli(host, port);
  2266. #endif
  2267. cli.set_connection_timeout(5);
  2268. {
  2269. auto res = cli.Get(path);
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2272. EXPECT_EQ(StatusCode::OK_200, res->status);
  2273. }
  2274. {
  2275. Headers headers = {make_range_header({{1, -1}})};
  2276. auto res = cli.Get(path, headers);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, 10}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijk", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2289. // entire resource, while the original httpbin returned 200. Both are
  2290. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2291. {
  2292. Headers headers = {make_range_header({{0, 31}})};
  2293. auto res = cli.Get(path, headers);
  2294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2296. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2297. res->status == StatusCode::PartialContent_206);
  2298. }
  2299. {
  2300. Headers headers = {make_range_header({{0, -1}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2305. res->status == StatusCode::PartialContent_206);
  2306. }
  2307. // go-httpbin returns 206 with clamped range for over-range requests,
  2308. // while the original httpbin returned 416. Both behaviors are observed
  2309. // in real servers, so we only verify the request succeeds.
  2310. {
  2311. Headers headers = {make_range_header({{0, 32}})};
  2312. auto res = cli.Get(path, headers);
  2313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2314. }
  2315. }
  2316. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2317. auto host = "unresolvableaddress.local";
  2318. auto path = std::string{"/"};
  2319. #ifdef CPPHTTPLIB_SSL_ENABLED
  2320. auto port = 443;
  2321. SSLClient cli(host, port);
  2322. #else
  2323. auto port = 80;
  2324. Client cli(host, port);
  2325. #endif
  2326. cli.set_connection_timeout(1);
  2327. {
  2328. auto res = cli.Get(path);
  2329. ASSERT_FALSE(res);
  2330. }
  2331. std::this_thread::sleep_for(std::chrono::seconds(8));
  2332. }
  2333. #if defined(__linux__) && defined(__GLIBC__) && \
  2334. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2335. // Forward declaration: in split builds split.py strips `inline` and moves the
  2336. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2337. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2338. // against the symbol in both header-only and split builds.
  2339. namespace httplib {
  2340. namespace detail {
  2341. int getaddrinfo_with_timeout(const char *node, const char *service,
  2342. const struct addrinfo *hints,
  2343. struct addrinfo **res, time_t timeout_sec);
  2344. } // namespace detail
  2345. } // namespace httplib
  2346. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2347. //
  2348. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2349. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2350. // gai_suspend() call hits the connection timeout the function calls
  2351. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2352. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2353. // still alive and still references the now-destroyed stack frame.
  2354. //
  2355. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2356. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2357. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2358. // and runs them in a container.
  2359. namespace {
  2360. bool should_run_issue_2431_tests() {
  2361. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2362. return v && *v && std::string(v) != "0";
  2363. }
  2364. std::string unique_unresolvable_host(int n) {
  2365. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2366. // glibc still asks the configured nameserver — which is exactly the path
  2367. // we want to exercise. A unique label per call avoids the resolver cache.
  2368. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2369. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2370. std::to_string(n) + ".invalid";
  2371. }
  2372. } // namespace
  2373. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2374. if (!should_run_issue_2431_tests()) {
  2375. GTEST_SKIP()
  2376. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2377. }
  2378. for (int i = 0; i < 8; ++i) {
  2379. struct addrinfo hints;
  2380. memset(&hints, 0, sizeof(hints));
  2381. hints.ai_family = AF_UNSPEC;
  2382. hints.ai_socktype = SOCK_STREAM;
  2383. auto host = unique_unresolvable_host(i);
  2384. struct addrinfo *result = nullptr;
  2385. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2386. &result, /*timeout_sec=*/1);
  2387. if (rc == 0 && result) { freeaddrinfo(result); }
  2388. }
  2389. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2390. // stack region they still believe holds their gaicb.
  2391. std::this_thread::sleep_for(std::chrono::seconds(3));
  2392. }
  2393. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2394. if (!should_run_issue_2431_tests()) {
  2395. GTEST_SKIP()
  2396. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2397. }
  2398. std::atomic<bool> stop{false};
  2399. std::vector<std::thread> threads;
  2400. for (int t = 0; t < 8; ++t) {
  2401. threads.emplace_back([t, &stop] {
  2402. int i = 0;
  2403. while (!stop.load(std::memory_order_relaxed)) {
  2404. struct addrinfo hints;
  2405. memset(&hints, 0, sizeof(hints));
  2406. hints.ai_family = AF_UNSPEC;
  2407. hints.ai_socktype = SOCK_STREAM;
  2408. auto host = unique_unresolvable_host(t * 100000 + i++);
  2409. struct addrinfo *result = nullptr;
  2410. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2411. &result, /*timeout_sec=*/1);
  2412. if (rc == 0 && result) { freeaddrinfo(result); }
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2424. if (!should_run_issue_2431_tests()) {
  2425. GTEST_SKIP()
  2426. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2427. }
  2428. std::atomic<bool> stop{false};
  2429. std::vector<std::thread> threads;
  2430. for (int t = 0; t < 8; ++t) {
  2431. threads.emplace_back([t, &stop] {
  2432. int i = 0;
  2433. while (!stop.load(std::memory_order_relaxed)) {
  2434. auto host = unique_unresolvable_host(t * 100000 + i++);
  2435. Client cli(host, 80);
  2436. cli.set_connection_timeout(1, 0);
  2437. cli.set_read_timeout(1, 0);
  2438. cli.set_write_timeout(1, 0);
  2439. (void)cli.Get("/");
  2440. }
  2441. });
  2442. }
  2443. std::this_thread::sleep_for(std::chrono::seconds(8));
  2444. stop.store(true, std::memory_order_relaxed);
  2445. for (auto &th : threads) {
  2446. th.join();
  2447. }
  2448. std::this_thread::sleep_for(std::chrono::seconds(3));
  2449. }
  2450. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2451. TEST(ConnectionErrorTest, InvalidHost) {
  2452. auto host = "-abcde.com";
  2453. #ifdef CPPHTTPLIB_SSL_ENABLED
  2454. auto port = 443;
  2455. SSLClient cli(host, port);
  2456. #else
  2457. auto port = 80;
  2458. Client cli(host, port);
  2459. #endif
  2460. cli.set_connection_timeout(std::chrono::seconds(2));
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::Connection, res.error());
  2464. }
  2465. TEST(ConnectionErrorTest, InvalidHost2) {
  2466. auto host = "httpcan.org/";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host);
  2469. #else
  2470. Client cli(host);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_EQ(Error::Connection, res.error());
  2476. }
  2477. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2478. auto host = "httpcan.org/";
  2479. #ifdef CPPHTTPLIB_SSL_ENABLED
  2480. SSLClient cli(host);
  2481. #else
  2482. Client cli(host);
  2483. #endif
  2484. cli.set_connection_timeout(std::chrono::seconds(2));
  2485. auto res = cli.Get("/");
  2486. ASSERT_TRUE(!res);
  2487. stringstream s;
  2488. s << "error code: " << res.error();
  2489. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidPort) {
  2492. auto host = "localhost";
  2493. auto port = 44380;
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. SSLClient cli(host, port);
  2496. #else
  2497. Client cli(host, port);
  2498. #endif
  2499. cli.set_connection_timeout(std::chrono::seconds(2));
  2500. auto res = cli.Get("/");
  2501. ASSERT_TRUE(!res);
  2502. EXPECT_TRUE(Error::Connection == res.error() ||
  2503. Error::ConnectionTimeout == res.error());
  2504. }
  2505. TEST(ConnectionErrorTest, Timeout_Online) {
  2506. auto host = "google.com";
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. auto port = 44380;
  2509. SSLClient cli(host, port);
  2510. #else
  2511. auto port = 8080;
  2512. Client cli(host, port);
  2513. #endif
  2514. cli.set_connection_timeout(std::chrono::seconds(2));
  2515. // only probe one address type so that the error reason
  2516. // correlates to the timed-out IPv4, not the unsupported
  2517. // IPv6 connection attempt
  2518. cli.set_address_family(AF_INET);
  2519. auto res = cli.Get("/");
  2520. ASSERT_TRUE(!res);
  2521. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2522. }
  2523. TEST(CancelTest, NoCancel_Online) {
  2524. auto host = "httpbingo.org";
  2525. auto path = std::string{"/range/32"};
  2526. #ifdef CPPHTTPLIB_SSL_ENABLED
  2527. auto port = 443;
  2528. SSLClient cli(host, port);
  2529. #else
  2530. auto port = 80;
  2531. Client cli(host, port);
  2532. #endif
  2533. cli.set_connection_timeout(std::chrono::seconds(5));
  2534. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2540. // Use /bytes with a large payload so that the DownloadProgress callback
  2541. // (which only fires for Content-Length responses) is invoked before the
  2542. // entire body is received, giving cancellation a chance to fire.
  2543. auto host = "httpbingo.org";
  2544. auto path = std::string{"/bytes/524288"};
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. auto port = 443;
  2547. SSLClient cli(host, port);
  2548. #else
  2549. auto port = 80;
  2550. Client cli(host, port);
  2551. #endif
  2552. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2553. cli.set_connection_timeout(std::chrono::seconds(5));
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayload_Online) {
  2558. auto host = "httpbingo.org";
  2559. auto path = std::string{"/bytes/524288"};
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. auto port = 443;
  2562. SSLClient cli(host, port);
  2563. #else
  2564. auto port = 80;
  2565. Client cli(host, port);
  2566. #endif
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. uint32_t count = 0;
  2569. auto res =
  2570. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, NoCancelPost) {
  2575. Server svr;
  2576. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2577. res.set_content("Hello World!", "text/plain");
  2578. });
  2579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(HOST, PORT);
  2587. cli.set_connection_timeout(std::chrono::seconds(5));
  2588. auto res =
  2589. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2590. "application/json", [](uint64_t, uint64_t) { return true; });
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ("Hello World!", res->body);
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. }
  2595. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2596. Server svr;
  2597. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2598. res.set_content("Hello World!", "text/plain");
  2599. });
  2600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2601. auto se = detail::scope_exit([&] {
  2602. svr.stop();
  2603. thread.join();
  2604. ASSERT_FALSE(svr.is_running());
  2605. });
  2606. svr.wait_until_ready();
  2607. Client cli(HOST, PORT);
  2608. cli.set_connection_timeout(std::chrono::seconds(5));
  2609. auto res =
  2610. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2611. "application/json", [](uint64_t, uint64_t) { return false; });
  2612. ASSERT_TRUE(!res);
  2613. EXPECT_EQ(Error::Canceled, res.error());
  2614. }
  2615. TEST(CancelTest, WithCancelLargePayloadPost) {
  2616. Server svr;
  2617. svr.set_payload_max_length(200 * 1024 * 1024);
  2618. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2619. res.set_content(LARGE_DATA, "text/plain");
  2620. });
  2621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2622. auto se = detail::scope_exit([&] {
  2623. svr.stop();
  2624. thread.join();
  2625. ASSERT_FALSE(svr.is_running());
  2626. });
  2627. svr.wait_until_ready();
  2628. Client cli(HOST, PORT);
  2629. cli.set_payload_max_length(200 * 1024 * 1024);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, NoCancelPut) {
  2638. Server svr;
  2639. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2640. res.set_content("Hello World!", "text/plain");
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. Client cli(HOST, PORT);
  2650. cli.set_connection_timeout(std::chrono::seconds(5));
  2651. auto res =
  2652. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2653. "application/json", [](uint64_t, uint64_t) { return true; });
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. EXPECT_EQ(StatusCode::OK_200, res->status);
  2657. }
  2658. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2659. Server svr;
  2660. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2661. res.set_content("Hello World!", "text/plain");
  2662. });
  2663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2664. auto se = detail::scope_exit([&] {
  2665. svr.stop();
  2666. thread.join();
  2667. ASSERT_FALSE(svr.is_running());
  2668. });
  2669. svr.wait_until_ready();
  2670. Client cli(HOST, PORT);
  2671. cli.set_connection_timeout(std::chrono::seconds(5));
  2672. auto res =
  2673. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2674. "application/json", [](uint64_t, uint64_t) { return false; });
  2675. ASSERT_TRUE(!res);
  2676. EXPECT_EQ(Error::Canceled, res.error());
  2677. }
  2678. TEST(CancelTest, WithCancelLargePayloadPut) {
  2679. Server svr;
  2680. svr.set_payload_max_length(200 * 1024 * 1024);
  2681. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2682. res.set_content(LARGE_DATA, "text/plain");
  2683. });
  2684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2685. auto se = detail::scope_exit([&] {
  2686. svr.stop();
  2687. thread.join();
  2688. ASSERT_FALSE(svr.is_running());
  2689. });
  2690. svr.wait_until_ready();
  2691. Client cli(HOST, PORT);
  2692. cli.set_payload_max_length(200 * 1024 * 1024);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, NoCancelPatch) {
  2701. Server svr;
  2702. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2703. res.set_content("Hello World!", "text/plain");
  2704. });
  2705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2706. auto se = detail::scope_exit([&] {
  2707. svr.stop();
  2708. thread.join();
  2709. ASSERT_FALSE(svr.is_running());
  2710. });
  2711. svr.wait_until_ready();
  2712. Client cli(HOST, PORT);
  2713. cli.set_connection_timeout(std::chrono::seconds(5));
  2714. auto res =
  2715. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2716. "application/json", [](uint64_t, uint64_t) { return true; });
  2717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2718. EXPECT_EQ("Hello World!", res->body);
  2719. EXPECT_EQ(StatusCode::OK_200, res->status);
  2720. }
  2721. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2722. Server svr;
  2723. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2724. res.set_content("Hello World!", "text/plain");
  2725. });
  2726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2727. auto se = detail::scope_exit([&] {
  2728. svr.stop();
  2729. thread.join();
  2730. ASSERT_FALSE(svr.is_running());
  2731. });
  2732. svr.wait_until_ready();
  2733. Client cli(HOST, PORT);
  2734. cli.set_connection_timeout(std::chrono::seconds(5));
  2735. auto res =
  2736. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2737. "application/json", [](uint64_t, uint64_t) { return false; });
  2738. ASSERT_TRUE(!res);
  2739. EXPECT_EQ(Error::Canceled, res.error());
  2740. }
  2741. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2742. Server svr;
  2743. svr.set_payload_max_length(200 * 1024 * 1024);
  2744. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2745. res.set_content(LARGE_DATA, "text/plain");
  2746. });
  2747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2748. auto se = detail::scope_exit([&] {
  2749. svr.stop();
  2750. thread.join();
  2751. ASSERT_FALSE(svr.is_running());
  2752. });
  2753. svr.wait_until_ready();
  2754. Client cli(HOST, PORT);
  2755. cli.set_payload_max_length(200 * 1024 * 1024);
  2756. cli.set_connection_timeout(std::chrono::seconds(5));
  2757. auto res =
  2758. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2759. "application/json", [](uint64_t, uint64_t) { return false; });
  2760. ASSERT_TRUE(!res);
  2761. EXPECT_EQ(Error::Canceled, res.error());
  2762. }
  2763. TEST(CancelTest, NoCancelDelete) {
  2764. Server svr;
  2765. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2766. res.set_content("Hello World!", "text/plain");
  2767. });
  2768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2769. auto se = detail::scope_exit([&] {
  2770. svr.stop();
  2771. thread.join();
  2772. ASSERT_FALSE(svr.is_running());
  2773. });
  2774. svr.wait_until_ready();
  2775. Client cli(HOST, PORT);
  2776. cli.set_connection_timeout(std::chrono::seconds(5));
  2777. auto res =
  2778. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2779. "application/json", [](uint64_t, uint64_t) { return true; });
  2780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2781. EXPECT_EQ("Hello World!", res->body);
  2782. EXPECT_EQ(StatusCode::OK_200, res->status);
  2783. }
  2784. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2785. Server svr;
  2786. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("Hello World!", "text/plain");
  2788. });
  2789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2790. auto se = detail::scope_exit([&] {
  2791. svr.stop();
  2792. thread.join();
  2793. ASSERT_FALSE(svr.is_running());
  2794. });
  2795. svr.wait_until_ready();
  2796. Client cli(HOST, PORT);
  2797. cli.set_connection_timeout(std::chrono::seconds(5));
  2798. auto res =
  2799. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2800. "application/json", [](uint64_t, uint64_t) { return false; });
  2801. ASSERT_TRUE(!res);
  2802. EXPECT_EQ(Error::Canceled, res.error());
  2803. }
  2804. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2805. Server svr;
  2806. svr.set_payload_max_length(200 * 1024 * 1024);
  2807. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2808. res.set_content(LARGE_DATA, "text/plain");
  2809. });
  2810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2811. auto se = detail::scope_exit([&] {
  2812. svr.stop();
  2813. thread.join();
  2814. ASSERT_FALSE(svr.is_running());
  2815. });
  2816. svr.wait_until_ready();
  2817. Client cli(HOST, PORT);
  2818. cli.set_payload_max_length(200 * 1024 * 1024);
  2819. cli.set_connection_timeout(std::chrono::seconds(5));
  2820. auto res =
  2821. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2822. "application/json", [](uint64_t, uint64_t) { return false; });
  2823. ASSERT_TRUE(!res);
  2824. EXPECT_EQ(Error::Canceled, res.error());
  2825. }
  2826. static std::string remove_whitespace(const std::string &input) {
  2827. std::string output;
  2828. output.reserve(input.size());
  2829. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2830. [](unsigned char c) { return !std::isspace(c); });
  2831. return output;
  2832. }
  2833. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2834. auto host = "httpbingo.org";
  2835. auto path = std::string{"/basic-auth/hello/world"};
  2836. #ifdef CPPHTTPLIB_SSL_ENABLED
  2837. auto port = 443;
  2838. SSLClient cli(host, port);
  2839. #else
  2840. auto port = 80;
  2841. Client cli(host, port);
  2842. #endif
  2843. {
  2844. auto res = cli.Get(path);
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2847. }
  2848. {
  2849. auto res = cli.Get(
  2850. path, Headers{make_basic_authentication_header("hello", "world")});
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. auto body = remove_whitespace(res->body);
  2853. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2854. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2855. EXPECT_EQ(StatusCode::OK_200, res->status);
  2856. }
  2857. {
  2858. cli.set_basic_auth("hello", "world");
  2859. auto res = cli.Get(path);
  2860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2861. auto body = remove_whitespace(res->body);
  2862. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2863. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2864. EXPECT_EQ(StatusCode::OK_200, res->status);
  2865. }
  2866. {
  2867. cli.set_basic_auth("hello", "bad");
  2868. auto res = cli.Get(path);
  2869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2870. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2871. }
  2872. {
  2873. cli.set_basic_auth("bad", "world");
  2874. auto res = cli.Get(path);
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2877. }
  2878. }
  2879. #ifdef CPPHTTPLIB_SSL_ENABLED
  2880. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2881. auto host = "httpbingo.org";
  2882. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2883. auto paths = std::vector<std::string>{
  2884. "/digest-auth/auth/hello/world/MD5",
  2885. "/digest-auth/auth/hello/world/SHA-256",
  2886. };
  2887. auto port = 443;
  2888. SSLClient cli(host, port);
  2889. {
  2890. auto res = cli.Get(unauth_path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. {
  2895. cli.set_digest_auth("hello", "world");
  2896. for (const auto &path : paths) {
  2897. auto res = cli.Get(path.c_str());
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. auto body = remove_whitespace(res->body);
  2900. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2901. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2902. EXPECT_EQ(StatusCode::OK_200, res->status);
  2903. }
  2904. cli.set_digest_auth("hello", "bad");
  2905. for (const auto &path : paths) {
  2906. auto res = cli.Get(path.c_str());
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. }
  2911. }
  2912. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2913. // comma-separated list of challenges, and each challenge may itself carry a
  2914. // comma-separated auth-param list, so a server can legally offer Basic
  2915. // before Digest, either as two field lines or packed into one. Runs one 401
  2916. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2917. // value() joins them in receipt order) and checks that the retry carries a
  2918. // well-formed Digest Authorization header naming expected_realm.
  2919. static void
  2920. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2921. const std::string &expected_realm) {
  2922. std::atomic<int> hits{0};
  2923. Server svr;
  2924. svr.Get("/x", [&](const Request &req, Response &res) {
  2925. if (++hits == 1) {
  2926. res.status = StatusCode::Unauthorized_401;
  2927. for (const auto &challenge : challenges) {
  2928. res.set_header("WWW-Authenticate", challenge);
  2929. }
  2930. } else {
  2931. auto authorization = req.get_header_value("Authorization");
  2932. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2933. EXPECT_NE(std::string::npos,
  2934. authorization.find("realm=\"" + expected_realm + "\""));
  2935. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2936. res.set_content("ok", "text/plain");
  2937. }
  2938. });
  2939. auto port = svr.bind_to_any_port(HOST);
  2940. std::thread t([&]() { svr.listen_after_bind(); });
  2941. auto se = detail::scope_exit([&] {
  2942. svr.stop();
  2943. t.join();
  2944. });
  2945. svr.wait_until_ready();
  2946. Client cli(HOST, port);
  2947. cli.set_digest_auth("hello", "world");
  2948. auto res = cli.Get("/x");
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(2, hits.load());
  2951. }
  2952. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2953. static const char *kDigestChallenge =
  2954. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2955. "algorithm=MD5";
  2956. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2957. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2958. "testrealm");
  2959. }
  2960. // Same challenge list with the schemes in the opposite order, to make sure
  2961. // the fix above didn't just special-case "Basic first".
  2962. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2963. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2964. "testrealm");
  2965. }
  2966. // A comma inside a quoted auth-param value must not be mistaken for the
  2967. // separator between two challenges (or two auth-params).
  2968. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2969. run_digest_challenge_list_test(
  2970. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5"},
  2972. "test,realm");
  2973. }
  2974. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2975. // the params and leaves out the fragment.
  2976. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2977. Server svr;
  2978. std::string uri, target;
  2979. svr.Get("/a b", [&](const Request &req, Response &res) {
  2980. auto auth = req.get_header_value("Authorization");
  2981. if (auth.empty()) {
  2982. res.status = StatusCode::Unauthorized_401;
  2983. res.set_header("WWW-Authenticate",
  2984. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2985. return;
  2986. }
  2987. auto b = auth.find("uri=\"") + 5;
  2988. uri = auth.substr(b, auth.find('"', b) - b);
  2989. target = req.target;
  2990. });
  2991. auto port = svr.bind_to_any_port(HOST);
  2992. std::thread t([&]() { svr.listen_after_bind(); });
  2993. auto se = detail::scope_exit([&] {
  2994. svr.stop();
  2995. t.join();
  2996. });
  2997. svr.wait_until_ready();
  2998. Client cli(HOST, port);
  2999. cli.set_digest_auth("hello", "world");
  3000. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ("/a%20b?x=1", target);
  3003. EXPECT_EQ(target, uri);
  3004. }
  3005. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3006. // make_digest_authentication_header() dereferences both unconditionally, so
  3007. // a server sending a challenge missing either one must not be treated as
  3008. // usable -- doing so used to crash the client with std::out_of_range.
  3009. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3010. Server svr;
  3011. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3012. res.status = StatusCode::Unauthorized_401;
  3013. res.set_header("WWW-Authenticate", challenge);
  3014. });
  3015. auto port = svr.bind_to_any_port(HOST);
  3016. std::thread t([&]() { svr.listen_after_bind(); });
  3017. auto se = detail::scope_exit([&] {
  3018. svr.stop();
  3019. t.join();
  3020. });
  3021. svr.wait_until_ready();
  3022. Client cli(HOST, port);
  3023. cli.set_digest_auth("hello", "world");
  3024. auto res = cli.Get("/x");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3027. }
  3028. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3029. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3030. }
  3031. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3032. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3033. }
  3034. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3035. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3036. }
  3037. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3038. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3039. // when storing the values, so the header builder has to re-escape them (and
  3040. // keep algorithm a bare token); otherwise the value breaks out of its
  3041. // quoted-string and injects extra auth-params into the client's Authorization.
  3042. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3043. std::atomic<int> hits{0};
  3044. std::string authorization;
  3045. Server svr;
  3046. svr.Get("/x", [&](const Request &req, Response &res) {
  3047. if (++hits == 1) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. // On the wire the quotes embedded in the values are backslash-escaped.
  3050. res.set_header("WWW-Authenticate",
  3051. "Digest realm=\"testrealm\", "
  3052. "nonce=\"n\\\"; injected=\\\"x\", "
  3053. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3054. } else {
  3055. authorization = req.get_header_value("Authorization");
  3056. res.set_content("ok", "text/plain");
  3057. }
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. std::thread t([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. t.join();
  3064. });
  3065. svr.wait_until_ready();
  3066. Client cli(HOST, port);
  3067. cli.set_digest_auth("hello", "world");
  3068. auto res = cli.Get("/x");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(2, hits.load());
  3071. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3072. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3073. // inside its quoted-string rather than starting an "injected" auth-param.
  3074. EXPECT_NE(std::string::npos,
  3075. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3076. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3077. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3078. }
  3079. #endif
  3080. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3081. auto host = "google.com";
  3082. auto another_host = "example.com";
  3083. auto wrong_ip = "0.0.0.0";
  3084. #ifdef CPPHTTPLIB_SSL_ENABLED
  3085. SSLClient cli(host);
  3086. #else
  3087. Client cli(host);
  3088. #endif
  3089. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3090. auto res = cli.Get("/");
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3093. }
  3094. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3095. auto host = "google.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(!res);
  3105. EXPECT_EQ(Error::Connection, res.error());
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3108. // A mapped value that is not an IP literal must be resolved. "localhost"
  3109. // resolves from the hosts file, so this test needs no external DNS.
  3110. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3111. auto host = "target.invalid";
  3112. Server svr;
  3113. std::string received_host;
  3114. svr.Get("/hi", [&](const Request &req, Response &res) {
  3115. received_host = req.get_header_value("Host");
  3116. res.set_content("Hello World!", "text/plain");
  3117. });
  3118. auto port = svr.bind_to_any_port(HOST);
  3119. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3120. auto se = detail::scope_exit([&] {
  3121. svr.stop();
  3122. thread.join();
  3123. ASSERT_FALSE(svr.is_running());
  3124. });
  3125. svr.wait_until_ready();
  3126. Client cli(host, port);
  3127. cli.set_hostname_addr_map({{host, HOST}});
  3128. auto res = cli.Get("/hi");
  3129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3130. EXPECT_EQ(StatusCode::OK_200, res->status);
  3131. // The mapping only redirects the connection; the identity stays host_.
  3132. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3133. }
  3134. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3135. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3136. auto host = "target.invalid";
  3137. Server svr;
  3138. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port("127.0.0.1");
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. }
  3155. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3156. // An empty mapped value must leave host_ as the connection target. Without
  3157. // that guard the empty value would become the host argument, getaddrinfo
  3158. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3159. // loopback - silently connecting somewhere the caller never asked for.
  3160. // The server listens on loopback, so such a fallback would succeed and is
  3161. // therefore observable as a failure of this test.
  3162. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3163. Server svr;
  3164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3165. res.set_content("Hello World!", "text/plain");
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. Client cli(blackhole, port);
  3176. cli.set_hostname_addr_map({{blackhole, ""}});
  3177. cli.set_connection_timeout(1);
  3178. auto res = cli.Get("/hi");
  3179. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3180. }
  3181. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3182. auto host = "httpbingo.org";
  3183. auto path = std::string{"/absolute-redirect/3"};
  3184. #ifdef CPPHTTPLIB_SSL_ENABLED
  3185. SSLClient cli(host);
  3186. #else
  3187. Client cli(host);
  3188. #endif
  3189. cli.set_follow_location(true);
  3190. auto res = cli.Get(path);
  3191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. }
  3194. TEST(RedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RelativeRedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/relative-redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(TooManyRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/redirect/21"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(!res);
  3231. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3232. }
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. TEST(YahooRedirectTest, Redirect_Online) {
  3235. Client cli("yahoo.com");
  3236. auto res = cli.Get("/");
  3237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3238. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3239. cli.set_follow_location(true);
  3240. res = cli.Get("/");
  3241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3244. }
  3245. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3246. #define REDIR_HOST "httpbingo.org"
  3247. #define REDIR_PATH "/redirect-to"
  3248. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3249. SSLClient cli(REDIR_HOST);
  3250. cli.set_follow_location(true);
  3251. auto res =
  3252. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3257. SSLClient cli(REDIR_HOST);
  3258. cli.set_follow_location(true);
  3259. Params params;
  3260. params.emplace("url", "http://example.com");
  3261. params.emplace("status_code", "302");
  3262. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. }
  3266. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3267. SSLClient cli(REDIR_HOST);
  3268. cli.set_follow_location(true);
  3269. Params params;
  3270. params.emplace("url", "http://example.com");
  3271. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3273. EXPECT_EQ(StatusCode::OK_200, res->status);
  3274. }
  3275. TEST(UrlWithSpace, Redirect_Online) {
  3276. SSLClient cli("edge.forgecdn.net");
  3277. cli.set_follow_location(true);
  3278. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3282. }
  3283. #endif
  3284. #if !defined(_WIN32) && !defined(_WIN64)
  3285. TEST(ReceiveSignals, Signal) {
  3286. auto setupSignalHandlers = []() {
  3287. struct sigaction act;
  3288. sigemptyset(&act.sa_mask);
  3289. act.sa_flags = SA_SIGINFO;
  3290. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3291. switch (sig) {
  3292. case SIGINT:
  3293. default: break;
  3294. }
  3295. };
  3296. ::sigaction(SIGINT, &act, nullptr);
  3297. };
  3298. Server svr;
  3299. int port = 0;
  3300. auto thread = std::thread([&]() {
  3301. setupSignalHandlers();
  3302. port = svr.bind_to_any_port(HOST);
  3303. svr.listen_after_bind();
  3304. });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. ASSERT_TRUE(svr.is_running());
  3312. pthread_kill(thread.native_handle(), SIGINT);
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3314. ASSERT_TRUE(svr.is_running());
  3315. }
  3316. #endif
  3317. TEST(RedirectToDifferentPort, Redirect) {
  3318. Server svr1;
  3319. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. });
  3322. int svr1_port = 0;
  3323. auto thread1 = std::thread([&]() {
  3324. svr1_port = svr1.bind_to_any_port(HOST);
  3325. svr1.listen_after_bind();
  3326. });
  3327. Server svr2;
  3328. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3329. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3330. });
  3331. int svr2_port = 0;
  3332. auto thread2 = std::thread([&]() {
  3333. svr2_port = svr2.bind_to_any_port(HOST);
  3334. svr2.listen_after_bind();
  3335. });
  3336. auto se = detail::scope_exit([&] {
  3337. svr2.stop();
  3338. thread2.join();
  3339. svr1.stop();
  3340. thread1.join();
  3341. ASSERT_FALSE(svr2.is_running());
  3342. ASSERT_FALSE(svr1.is_running());
  3343. });
  3344. svr1.wait_until_ready();
  3345. svr2.wait_until_ready();
  3346. Client cli("localhost", svr2_port);
  3347. cli.set_follow_location(true);
  3348. auto res = cli.Get("/2");
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("Hello World!", res->body);
  3352. }
  3353. // GET /redir on one server redirects to /target on another port, so the
  3354. // client follows it with a new client.
  3355. static Result
  3356. GetThroughRedirectToDifferentPort(Server::Handler target,
  3357. const std::function<void(Client &)> &setup,
  3358. const Headers &headers = Headers()) {
  3359. Server target_svr;
  3360. target_svr.Get("/target", target);
  3361. int target_port = 0;
  3362. auto target_thread = std::thread([&]() {
  3363. target_port = target_svr.bind_to_any_port(HOST);
  3364. target_svr.listen_after_bind();
  3365. });
  3366. Server origin_svr;
  3367. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3368. res.set_redirect(
  3369. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3370. });
  3371. int origin_port = 0;
  3372. auto origin_thread = std::thread([&]() {
  3373. origin_port = origin_svr.bind_to_any_port(HOST);
  3374. origin_svr.listen_after_bind();
  3375. });
  3376. auto se = detail::scope_exit([&] {
  3377. origin_svr.stop();
  3378. origin_thread.join();
  3379. target_svr.stop();
  3380. target_thread.join();
  3381. });
  3382. target_svr.wait_until_ready();
  3383. origin_svr.wait_until_ready();
  3384. Client cli("localhost", origin_port);
  3385. cli.set_follow_location(true);
  3386. setup(cli);
  3387. return cli.Get("/redir", headers);
  3388. }
  3389. static void
  3390. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3391. std::string captured_authorization;
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [&](const Request &req, Response &res) {
  3394. captured_authorization = req.get_header_value("Authorization");
  3395. res.set_content("OK", "text/plain");
  3396. },
  3397. set_auth);
  3398. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3399. EXPECT_EQ(StatusCode::OK_200, result->status);
  3400. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3401. EXPECT_TRUE(captured_authorization.empty());
  3402. }
  3403. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3404. TestDoNotForwardCredentialsOnRedirect(
  3405. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3406. }
  3407. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3408. TestDoNotForwardCredentialsOnRedirect(
  3409. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3410. }
  3411. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3412. std::string captured_cookie;
  3413. auto result = GetThroughRedirectToDifferentPort(
  3414. [&](const Request &req, Response &res) {
  3415. captured_cookie = req.get_header_value("Cookie");
  3416. res.set_content("OK", "text/plain");
  3417. },
  3418. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3419. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3420. EXPECT_EQ(StatusCode::OK_200, result->status);
  3421. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3422. EXPECT_TRUE(captured_cookie.empty());
  3423. }
  3424. TEST(RedirectToSamePort, ForwardCookie) {
  3425. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3426. // header so that ordinary session flows keep working.
  3427. Server svr;
  3428. std::string captured_cookie;
  3429. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3430. res.set_redirect("/target", 302);
  3431. });
  3432. svr.Get("/target", [&](const Request &req, Response &res) {
  3433. captured_cookie = req.get_header_value("Cookie");
  3434. res.set_content("OK", "text/plain");
  3435. });
  3436. auto port = svr.bind_to_any_port(HOST);
  3437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3438. auto se = detail::scope_exit([&] {
  3439. svr.stop();
  3440. thread.join();
  3441. ASSERT_FALSE(svr.is_running());
  3442. });
  3443. svr.wait_until_ready();
  3444. Client cli(HOST, port);
  3445. cli.set_follow_location(true);
  3446. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3447. auto res = cli.Get("/redir", headers);
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3451. }
  3452. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3453. std::string authorization;
  3454. std::string trace_id;
  3455. auto result = GetThroughRedirectToDifferentPort(
  3456. [&](const Request &req, Response &res) {
  3457. authorization = req.get_header_value("Authorization");
  3458. trace_id = req.get_header_value("X-Trace-Id");
  3459. res.set_content("OK", "text/plain");
  3460. },
  3461. [](Client &cli) {
  3462. cli.set_default_headers(
  3463. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3464. });
  3465. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3466. EXPECT_EQ(StatusCode::OK_200, result->status);
  3467. // Like a header given with the request, a default one goes along unless it
  3468. // carries credentials (RFC 9110 15.4).
  3469. EXPECT_TRUE(authorization.empty());
  3470. EXPECT_EQ("42", trace_id);
  3471. }
  3472. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3473. auto result = GetThroughRedirectToDifferentPort(
  3474. [](const Request &, Response &res) {
  3475. res.set_content(std::string(2048, 'x'), "text/plain");
  3476. },
  3477. [](Client &cli) { cli.set_payload_max_length(1024); });
  3478. EXPECT_FALSE(result);
  3479. }
  3480. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3481. auto result = GetThroughRedirectToDifferentPort(
  3482. [](const Request &req, Response &res) {
  3483. // Answer after a second, or once the client gives up.
  3484. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3485. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3486. }
  3487. res.set_content("late", "text/plain");
  3488. },
  3489. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3490. ASSERT_FALSE(result);
  3491. EXPECT_EQ(Error::Read, result.error());
  3492. }
  3493. #ifdef CPPHTTPLIB_SSL_ENABLED
  3494. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &, Response &res) {
  3497. res.status = StatusCode::Unauthorized_401;
  3498. res.set_header("WWW-Authenticate",
  3499. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3500. },
  3501. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3502. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3503. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3504. }
  3505. #endif
  3506. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3507. Server svr;
  3508. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3509. // Port number that overflows int — should not crash
  3510. res.set_redirect("http://localhost:99999999999999999999/target");
  3511. });
  3512. auto port = svr.bind_to_any_port(HOST);
  3513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3514. auto se = detail::scope_exit([&] {
  3515. svr.stop();
  3516. thread.join();
  3517. ASSERT_FALSE(svr.is_running());
  3518. });
  3519. svr.wait_until_ready();
  3520. Client cli(HOST, port);
  3521. cli.set_follow_location(true);
  3522. auto res = cli.Get("/redir");
  3523. // Should fail gracefully, not crash (no valid response due to bad port)
  3524. EXPECT_FALSE(res);
  3525. }
  3526. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3527. Server svr;
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3530. // The server's own port followed by junk must not be followed
  3531. res.set_redirect("http://" + std::string(HOST) + ":" +
  3532. std::to_string(port) + "junk/target");
  3533. });
  3534. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3535. res.set_content("target", "text/plain");
  3536. });
  3537. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3538. auto se = detail::scope_exit([&] {
  3539. svr.stop();
  3540. thread.join();
  3541. ASSERT_FALSE(svr.is_running());
  3542. });
  3543. svr.wait_until_ready();
  3544. Client cli(HOST, port);
  3545. cli.set_follow_location(true);
  3546. auto res = cli.Get("/redir");
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectFromPageWithContent, Redirect) {
  3550. Server svr;
  3551. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3552. res.set_content("___", "text/plain");
  3553. res.set_redirect("/2");
  3554. });
  3555. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3556. res.set_content("Hello World!", "text/plain");
  3557. });
  3558. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3559. auto se = detail::scope_exit([&] {
  3560. svr.stop();
  3561. th.join();
  3562. ASSERT_FALSE(svr.is_running());
  3563. });
  3564. svr.wait_until_ready();
  3565. {
  3566. Client cli("localhost", PORT);
  3567. cli.set_follow_location(true);
  3568. std::string body;
  3569. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3570. body.append(data, data_length);
  3571. return true;
  3572. });
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::OK_200, res->status);
  3575. EXPECT_EQ("Hello World!", body);
  3576. }
  3577. {
  3578. Client cli("localhost", PORT);
  3579. std::string body;
  3580. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3581. body.append(data, data_length);
  3582. return true;
  3583. });
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::Found_302, res->status);
  3586. EXPECT_EQ("___", body);
  3587. }
  3588. }
  3589. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3590. Server svr;
  3591. auto port_str = std::to_string(PORT);
  3592. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3593. auto expected_host = "[::1]:" + port_str;
  3594. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3595. res.set_content("___", "text/plain");
  3596. // res.set_redirect("/2");
  3597. res.set_redirect(redirect_url);
  3598. });
  3599. svr.Get("/2", [&](const Request &req, Response &res) {
  3600. auto host_header = req.headers.find("Host");
  3601. ASSERT_TRUE(host_header != req.headers.end());
  3602. EXPECT_EQ(expected_host, host_header->second);
  3603. res.set_content("Hello World!", "text/plain");
  3604. });
  3605. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. th.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3612. // actually starts anything, so the condition !svr.is_running() will
  3613. // always remain true, and the loop never stops.
  3614. // This basically counts how many milliseconds have passed since the
  3615. // call to svr.listen(), and if after 5 seconds nothing started yet
  3616. // aborts the test.
  3617. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3618. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3619. ASSERT_LT(milliseconds, 5000U);
  3620. }
  3621. {
  3622. Client cli("::1", PORT);
  3623. cli.set_follow_location(true);
  3624. std::string body;
  3625. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3626. body.append(data, data_length);
  3627. return true;
  3628. });
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. EXPECT_EQ("Hello World!", body);
  3632. }
  3633. {
  3634. Client cli("::1", PORT);
  3635. std::string body;
  3636. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3637. body.append(data, data_length);
  3638. return true;
  3639. });
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::Found_302, res->status);
  3642. EXPECT_EQ("___", body);
  3643. }
  3644. }
  3645. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3646. Server svr;
  3647. svr.Get("/foo", [](const Request &req, Response &res) {
  3648. auto a = req.params.find("a");
  3649. if (a != req.params.end()) {
  3650. res.set_content((*a).second, "text/plain");
  3651. res.status = StatusCode::OK_200;
  3652. } else {
  3653. res.status = StatusCode::BadRequest_400;
  3654. }
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. cli.set_path_encode(false);
  3666. auto res = cli.Get("/foo?a=explicitly+encoded");
  3667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. // This expects it back with a space, as the `+` won't have been
  3670. // url-encoded, and server-side the params get decoded turning `+`
  3671. // into spaces.
  3672. EXPECT_EQ("explicitly encoded", res->body);
  3673. }
  3674. }
  3675. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3676. // When path encoding is disabled the client must transmit the supplied
  3677. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3678. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3679. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3680. // than a space (0x20). Assert on the raw wire target to catch this.
  3681. Server svr;
  3682. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3683. svr.Get("/foo", [&](const Request &req, Response &res) {
  3684. EXPECT_EQ(expected_target, req.target);
  3685. res.status = StatusCode::OK_200;
  3686. });
  3687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3688. auto se = detail::scope_exit([&] {
  3689. svr.stop();
  3690. thread.join();
  3691. ASSERT_FALSE(svr.is_running());
  3692. });
  3693. svr.wait_until_ready();
  3694. {
  3695. Client cli(HOST, PORT);
  3696. cli.set_path_encode(false);
  3697. auto res = cli.Get(expected_target.c_str());
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. }
  3701. }
  3702. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3703. // `open_stream()` used to skip the path encoding that the buffered send
  3704. // path applies, so the same `path` produced different bytes in the request
  3705. // line depending on which API was used. Assert the two agree.
  3706. Server svr;
  3707. std::string target;
  3708. svr.Get(".*", [&](const Request &req, Response &res) {
  3709. target = req.target;
  3710. res.status = StatusCode::OK_200;
  3711. });
  3712. auto port = svr.bind_to_any_port(HOST);
  3713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3714. auto se = detail::scope_exit([&] {
  3715. svr.stop();
  3716. thread.join();
  3717. ASSERT_FALSE(svr.is_running());
  3718. });
  3719. svr.wait_until_ready();
  3720. struct {
  3721. const char *path;
  3722. const char *expected;
  3723. } cases[] = {
  3724. {"/a b?x=1", "/a%20b?x=1"},
  3725. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3726. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3727. };
  3728. for (const auto &c : cases) {
  3729. Client cli(HOST, port);
  3730. target.clear();
  3731. auto res = cli.Get(c.path);
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3734. auto buffered_target = target;
  3735. target.clear();
  3736. auto handle = cli.open_stream("GET", c.path);
  3737. EXPECT_TRUE(handle.is_valid())
  3738. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3739. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3740. }
  3741. }
  3742. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3743. // The `set_path_encode(false)` contract — transmit the supplied target
  3744. // verbatim — must hold for the streaming API too.
  3745. Server svr;
  3746. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3747. std::string target;
  3748. svr.Get("/foo", [&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. });
  3752. auto port = svr.bind_to_any_port(HOST);
  3753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3754. auto se = detail::scope_exit([&] {
  3755. svr.stop();
  3756. thread.join();
  3757. ASSERT_FALSE(svr.is_running());
  3758. });
  3759. svr.wait_until_ready();
  3760. {
  3761. Client cli(HOST, port);
  3762. cli.set_path_encode(false);
  3763. auto handle = cli.open_stream("GET", expected_target);
  3764. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3765. EXPECT_EQ(expected_target, target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3769. // With path encoding enabled a CR/LF in the target is percent-encoded
  3770. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3771. // write_request_line still backstops `set_path_encode(false)`, which is
  3772. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3773. Server svr;
  3774. // Captured before routing: the decoded path contains a newline, which a
  3775. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3776. std::string target;
  3777. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3778. target = req.target;
  3779. res.status = StatusCode::OK_200;
  3780. return Server::HandlerResponse::Handled;
  3781. });
  3782. auto port = svr.bind_to_any_port(HOST);
  3783. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3784. auto se = detail::scope_exit([&] {
  3785. svr.stop();
  3786. thread.join();
  3787. ASSERT_FALSE(svr.is_running());
  3788. });
  3789. svr.wait_until_ready();
  3790. {
  3791. Client cli(HOST, port);
  3792. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3793. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3794. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3798. // Every control character is percent-encoded, not just CR/LF, so the target
  3799. // passes the request-target check in write_request_line.
  3800. Server svr;
  3801. std::string target;
  3802. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3803. target = req.target;
  3804. res.status = StatusCode::OK_200;
  3805. return Server::HandlerResponse::Handled;
  3806. });
  3807. auto port = svr.bind_to_any_port(HOST);
  3808. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3809. auto se = detail::scope_exit([&] {
  3810. svr.stop();
  3811. thread.join();
  3812. ASSERT_FALSE(svr.is_running());
  3813. });
  3814. svr.wait_until_ready();
  3815. {
  3816. Client cli(HOST, port);
  3817. auto res = cli.Get("/a\tb\x1b\x7f");
  3818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3819. EXPECT_EQ("/a%09b%1B%7F", target);
  3820. }
  3821. }
  3822. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3823. // Nothing may reach the wire: a raw CR/LF target would split the request
  3824. // line and inject headers.
  3825. Server svr;
  3826. // Pre-routing so that "not called" means nothing reached the server at all,
  3827. // rather than merely failing to match a handler pattern.
  3828. auto handler_called = false;
  3829. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3830. handler_called = true;
  3831. res.status = StatusCode::OK_200;
  3832. return Server::HandlerResponse::Handled;
  3833. });
  3834. auto port = svr.bind_to_any_port(HOST);
  3835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. thread.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. {
  3843. Client cli(HOST, port);
  3844. cli.set_path_encode(false);
  3845. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3846. EXPECT_FALSE(handle.is_valid());
  3847. EXPECT_EQ(Error::Write, handle.error);
  3848. EXPECT_FALSE(handler_called);
  3849. }
  3850. }
  3851. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3852. // Which of the two branches runs is decided by whether the query component
  3853. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3854. // an empty query and must still fall back to building one from
  3855. // `req.params`, while a non-empty query must win over `req.params`.
  3856. Server svr;
  3857. std::string target;
  3858. svr.Get("/foo", [&](const Request &req, Response &res) {
  3859. target = req.target;
  3860. res.status = StatusCode::OK_200;
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. // Trailing `?` -> empty query component -> `req.params` is used.
  3872. Client cli(HOST, port);
  3873. Request req;
  3874. req.method = "GET";
  3875. req.path = "/foo?";
  3876. req.params.emplace("a", "1");
  3877. target.clear();
  3878. auto res = cli.send(req);
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ("/foo?a=1", target);
  3881. }
  3882. {
  3883. // Non-empty query in `req.path` -> `req.params` is not appended.
  3884. Client cli(HOST, port);
  3885. Request req;
  3886. req.method = "GET";
  3887. req.path = "/foo?b=2";
  3888. req.params.emplace("a", "1");
  3889. target.clear();
  3890. auto res = cli.send(req);
  3891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3892. EXPECT_EQ("/foo?b=2", target);
  3893. }
  3894. }
  3895. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3896. Server svr;
  3897. svr.Get("/", [](const Request &req, Response &) {
  3898. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3899. });
  3900. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. Client cli(HOST, PORT);
  3909. cli.set_path_encode(false);
  3910. auto res = cli.Get("/?something=%0A");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. }
  3914. }
  3915. TEST(BindServerTest, BindDualStack) {
  3916. Server svr;
  3917. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3918. res.set_content("Hello World!", "text/plain");
  3919. });
  3920. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3921. auto se = detail::scope_exit([&] {
  3922. svr.stop();
  3923. thread.join();
  3924. ASSERT_FALSE(svr.is_running());
  3925. });
  3926. svr.wait_until_ready();
  3927. {
  3928. Client cli("127.0.0.1", PORT);
  3929. auto res = cli.Get("/1");
  3930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("Hello World!", res->body);
  3933. }
  3934. {
  3935. Client cli("::1", PORT);
  3936. auto res = cli.Get("/1");
  3937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("Hello World!", res->body);
  3940. }
  3941. }
  3942. TEST(BindServerTest, BindAndListenSeparately) {
  3943. Server svr;
  3944. int port = svr.bind_to_any_port("0.0.0.0");
  3945. ASSERT_TRUE(svr.is_valid());
  3946. ASSERT_TRUE(port > 0);
  3947. svr.stop();
  3948. }
  3949. // Reports whether anything is still listening on a loopback port. A plain
  3950. // connect() is used instead of a Client request because a socket left bound by
  3951. // mistake accepts the connection into its backlog and never answers, which
  3952. // would hang the test instead of failing it.
  3953. static bool is_loopback_port_accepting(int port) {
  3954. sockaddr_in addr{};
  3955. addr.sin_family = AF_INET;
  3956. addr.sin_port = htons(static_cast<uint16_t>(port));
  3957. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3958. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3959. EXPECT_NE(sock, INVALID_SOCKET);
  3960. if (sock == INVALID_SOCKET) { return false; }
  3961. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3962. static_cast<socklen_t>(sizeof(addr)));
  3963. detail::close_socket(sock);
  3964. return ret == 0;
  3965. }
  3966. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3967. Server svr;
  3968. auto port = svr.bind_to_any_port("127.0.0.1");
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. // bind_to_any_port() already called listen(2), so until stop() closed the
  3972. // descriptor the port kept accepting connections into the backlog. ASSERT
  3973. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3974. // below blocks forever in the accept loop.
  3975. ASSERT_FALSE(is_loopback_port_accepting(port));
  3976. // Nothing is left to accept on, so listen_after_bind() must report failure
  3977. // instead of returning success without ever serving.
  3978. EXPECT_FALSE(svr.listen_after_bind());
  3979. // The failed listen marks the server decommissioned, so a waiter returns
  3980. // instead of spinning forever.
  3981. svr.wait_until_ready();
  3982. }
  3983. #ifdef CPPHTTPLIB_SSL_ENABLED
  3984. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3986. CLIENT_CA_CERT_DIR);
  3987. int port = svr.bind_to_any_port("0.0.0.0");
  3988. ASSERT_TRUE(svr.is_valid());
  3989. ASSERT_TRUE(port > 0);
  3990. svr.stop();
  3991. }
  3992. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3993. // or a rejected CustomRoute() registration would not stop the server binding.
  3994. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3996. CLIENT_CA_CERT_DIR);
  3997. ASSERT_TRUE(svr.is_valid());
  3998. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3999. EXPECT_FALSE(svr.is_valid());
  4000. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4001. }
  4002. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4003. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4004. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4005. int port = svr.bind_to_any_port("0.0.0.0");
  4006. ASSERT_TRUE(svr.is_valid());
  4007. ASSERT_TRUE(port > 0);
  4008. svr.stop();
  4009. }
  4010. TEST(BindServerTest, UpdateCertsPem) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4012. int port = svr.bind_to_any_port("0.0.0.0");
  4013. ASSERT_TRUE(svr.is_valid());
  4014. ASSERT_TRUE(port > 0);
  4015. // Read PEM files
  4016. std::string cert_pem, key_pem, ca_pem;
  4017. read_file(SERVER_CERT_FILE, cert_pem);
  4018. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4019. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4020. // Update server certificates using PEM API
  4021. ASSERT_TRUE(
  4022. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4023. ASSERT_TRUE(svr.is_valid());
  4024. svr.stop();
  4025. }
  4026. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4027. // Start server with client CA (enables client auth)
  4028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4029. ASSERT_TRUE(svr.is_valid());
  4030. bool handler_called = false;
  4031. svr.Get("/test", [&](const Request &req, Response &res) {
  4032. handler_called = true;
  4033. // Verify client certificate is present
  4034. auto cert = req.peer_cert();
  4035. EXPECT_TRUE(static_cast<bool>(cert));
  4036. res.set_content("ok", "text/plain");
  4037. });
  4038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4039. auto se = detail::scope_exit([&] {
  4040. svr.stop();
  4041. t.join();
  4042. ASSERT_FALSE(svr.is_running());
  4043. });
  4044. svr.wait_until_ready();
  4045. // Read PEM files
  4046. std::string cert_pem, key_pem, ca_pem;
  4047. read_file(SERVER_CERT_FILE, cert_pem);
  4048. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4049. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4050. // Update server certificates and client CA using PEM API while server running
  4051. ASSERT_TRUE(
  4052. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4053. // Connect with client certificate
  4054. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4055. cli.enable_server_certificate_verification(false);
  4056. cli.set_connection_timeout(30);
  4057. auto res = cli.Get("/test");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. ASSERT_EQ(StatusCode::OK_200, res->status);
  4060. ASSERT_TRUE(handler_called);
  4061. EXPECT_EQ("ok", res->body);
  4062. }
  4063. // Puts a CA that did not sign the client's certificate in the old one's place.
  4064. static bool replace_client_ca(SSLServer &svr) {
  4065. std::string cert_pem, key_pem, ca_pem;
  4066. read_file(SERVER_CERT_FILE, cert_pem);
  4067. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4068. read_file(SERVER_CERT2_FILE, ca_pem);
  4069. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4070. ca_pem.c_str());
  4071. }
  4072. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4074. ASSERT_TRUE(svr.is_valid());
  4075. svr.Get("/test", [](const Request &, Response &res) {
  4076. res.set_content("ok", "text/plain");
  4077. });
  4078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4079. auto se = detail::scope_exit([&] {
  4080. svr.stop();
  4081. t.join();
  4082. ASSERT_FALSE(svr.is_running());
  4083. });
  4084. svr.wait_until_ready();
  4085. auto get = [] {
  4086. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4087. cli.enable_server_certificate_verification(false);
  4088. return cli.Get("/test");
  4089. };
  4090. ASSERT_TRUE(get());
  4091. ASSERT_TRUE(replace_client_ca(svr));
  4092. EXPECT_FALSE(get());
  4093. }
  4094. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4095. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. tls::set_verify_callback(svr.tls_context(),
  4099. [](const tls::VerifyContext &) -> bool {
  4100. throw std::runtime_error("verify");
  4101. });
  4102. svr.Get("/test", [](const Request &, Response &res) {
  4103. res.set_content("ok", "text/plain");
  4104. });
  4105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4106. auto se = detail::scope_exit([&] {
  4107. svr.stop();
  4108. t.join();
  4109. ASSERT_FALSE(svr.is_running());
  4110. });
  4111. svr.wait_until_ready();
  4112. auto get = [] {
  4113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4114. cli.enable_server_certificate_verification(false);
  4115. return cli.Get("/test");
  4116. };
  4117. EXPECT_FALSE(get());
  4118. // The handshake is over, so an update does not wait for it.
  4119. std::string cert_pem, key_pem;
  4120. read_file(SERVER_CERT_FILE, cert_pem);
  4121. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4122. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4123. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4124. return v.preverify_ok;
  4125. });
  4126. auto res = get();
  4127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4128. EXPECT_EQ("ok", res->body);
  4129. }
  4130. #endif
  4131. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4132. // Sends each request over a new connection with a client certificate,
  4133. // resuming the session of the one before when there is one.
  4134. class ResumingClient {
  4135. public:
  4136. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4137. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4138. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4139. SSL_FILETYPE_PEM);
  4140. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4141. // callback, not through SSL_get1_session().
  4142. SSL_CTX_set_app_data(ctx_, this);
  4143. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4144. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4145. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4146. auto self = static_cast<ResumingClient *>(
  4147. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4148. SSL_SESSION_free(self->session_);
  4149. self->session_ = session;
  4150. return 1; // Keeps the reference
  4151. });
  4152. }
  4153. ~ResumingClient() {
  4154. SSL_SESSION_free(session_);
  4155. SSL_CTX_free(ctx_);
  4156. }
  4157. // Tells whether the request was answered.
  4158. bool get() {
  4159. auto error = Error::Success;
  4160. auto sock = detail::create_client_socket(
  4161. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4162. /*connection_timeout_sec=*/5, 0,
  4163. /*read_timeout_sec=*/5, 0,
  4164. /*write_timeout_sec=*/5, 0, std::string(), error);
  4165. if (sock == INVALID_SOCKET) { return false; }
  4166. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4167. auto ssl = SSL_new(ctx_);
  4168. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4169. SSL_set_fd(ssl, static_cast<int>(sock));
  4170. if (session_) { SSL_set_session(ssl, session_); }
  4171. if (SSL_connect(ssl) != 1) { return false; }
  4172. reused_ = SSL_session_reused(ssl) == 1;
  4173. // Reading the response also takes in a TLS 1.3 session ticket.
  4174. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4175. "Connection: close\r\n\r\n";
  4176. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4177. std::string res;
  4178. char buf[256];
  4179. int n;
  4180. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4181. res.append(buf, static_cast<size_t>(n));
  4182. }
  4183. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4184. SSL_shutdown(ssl);
  4185. return res.find("200 OK") != std::string::npos;
  4186. }
  4187. // Whether the last connection resumed a session
  4188. bool reused() const { return reused_; }
  4189. private:
  4190. SSL_CTX *ctx_;
  4191. SSL_SESSION *session_ = nullptr;
  4192. bool reused_ = false;
  4193. };
  4194. // A client that resumes its session gets through, but not once the client CA
  4195. // has changed, as a resumed session does not show the certificate again.
  4196. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4198. ASSERT_TRUE(svr.is_valid());
  4199. svr.Get("/test", [](const Request &, Response &res) {
  4200. res.set_content("ok", "text/plain");
  4201. });
  4202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4203. auto se = detail::scope_exit([&] {
  4204. svr.stop();
  4205. t.join();
  4206. ASSERT_FALSE(svr.is_running());
  4207. });
  4208. svr.wait_until_ready();
  4209. ResumingClient cli;
  4210. ASSERT_TRUE(cli.get());
  4211. ASSERT_TRUE(cli.get());
  4212. EXPECT_TRUE(cli.reused());
  4213. ASSERT_TRUE(replace_client_ca(svr));
  4214. EXPECT_FALSE(cli.get());
  4215. }
  4216. // A resumed session does not show the certificate again, so the server does
  4217. // not resume one with a verify callback to run on it.
  4218. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4220. ASSERT_TRUE(svr.is_valid());
  4221. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4222. return v.preverify_ok;
  4223. });
  4224. svr.Get("/test", [](const Request &, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4228. auto se = detail::scope_exit([&] {
  4229. svr.stop();
  4230. t.join();
  4231. ASSERT_FALSE(svr.is_running());
  4232. });
  4233. svr.wait_until_ready();
  4234. ResumingClient cli;
  4235. ASSERT_TRUE(cli.get());
  4236. ASSERT_TRUE(cli.get());
  4237. EXPECT_FALSE(cli.reused());
  4238. }
  4239. #endif
  4240. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4241. // wolfSSL shares its session cache between contexts, so a resumed session
  4242. // could carry a client certificate checked against another server's CA, or
  4243. // against a client CA since replaced.
  4244. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4246. ASSERT_TRUE(svr.is_valid());
  4247. // Trusts a CA that did not sign the client's certificate.
  4248. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4249. ASSERT_TRUE(other.is_valid());
  4250. for (auto s : {&svr, &other}) {
  4251. s->Get("/test", [](const Request &, Response &res) {
  4252. res.set_content("ok", "text/plain");
  4253. });
  4254. }
  4255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4256. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4257. auto se = detail::scope_exit([&] {
  4258. other.stop();
  4259. svr.stop();
  4260. t2.join();
  4261. t.join();
  4262. });
  4263. svr.wait_until_ready();
  4264. other.wait_until_ready();
  4265. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4266. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4267. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4268. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4269. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4270. ASSERT_EQ(WOLFSSL_SUCCESS,
  4271. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4272. WOLFSSL_FILETYPE_PEM));
  4273. WOLFSSL_SESSION *session = nullptr;
  4274. auto session_se = detail::scope_exit([&] {
  4275. if (session) { wolfSSL_SESSION_free(session); }
  4276. });
  4277. // A request over a new connection, resuming `session` when there is one and
  4278. // keeping the connection's own in its place. Tells whether it was answered.
  4279. auto get = [&](int port) {
  4280. auto error = Error::Success;
  4281. auto sock = detail::create_client_socket(
  4282. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4283. /*connection_timeout_sec=*/5, 0,
  4284. /*read_timeout_sec=*/5, 0,
  4285. /*write_timeout_sec=*/5, 0, std::string(), error);
  4286. if (sock == INVALID_SOCKET) { return false; }
  4287. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4288. auto ssl = wolfSSL_new(ctx);
  4289. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4290. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4291. if (session) { wolfSSL_set_session(ssl, session); }
  4292. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4293. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4294. "Connection: close\r\n\r\n";
  4295. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4296. std::string res;
  4297. char buf[256];
  4298. int n;
  4299. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4300. res.append(buf, static_cast<size_t>(n));
  4301. }
  4302. wolfSSL_shutdown(ssl);
  4303. if (session) { wolfSSL_SESSION_free(session); }
  4304. session = wolfSSL_get1_session(ssl);
  4305. return res.find("200 OK") != std::string::npos;
  4306. };
  4307. ASSERT_TRUE(get(PORT));
  4308. EXPECT_FALSE(get(PORT + 1));
  4309. ASSERT_TRUE(get(PORT));
  4310. ASSERT_TRUE(replace_client_ca(svr));
  4311. EXPECT_FALSE(get(PORT));
  4312. }
  4313. #endif
  4314. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4316. ASSERT_TRUE(svr.is_valid());
  4317. svr.Get("/test", [](const Request &, Response &res) {
  4318. res.set_content("ok", "text/plain");
  4319. });
  4320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. t.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. svr.wait_until_ready();
  4327. // A connection that sends no ClientHello keeps its handshake in progress,
  4328. // once the server has had a moment to start it.
  4329. auto error = Error::Success;
  4330. auto sock = detail::create_client_socket(
  4331. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4332. /*connection_timeout_sec=*/5, 0,
  4333. /*read_timeout_sec=*/5, 0,
  4334. /*write_timeout_sec=*/5, 0, std::string(), error);
  4335. ASSERT_NE(INVALID_SOCKET, sock);
  4336. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4337. std::string cert_pem, key_pem;
  4338. read_file(SERVER_CERT_FILE, cert_pem);
  4339. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4340. auto update = std::async(std::launch::async, [&]() {
  4341. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4342. });
  4343. EXPECT_EQ(std::future_status::timeout,
  4344. update.wait_for(std::chrono::milliseconds(200)));
  4345. detail::close_socket(sock);
  4346. EXPECT_TRUE(update.get());
  4347. SSLClient cli(HOST, PORT);
  4348. cli.enable_server_certificate_verification(false);
  4349. auto res = cli.Get("/test");
  4350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4351. EXPECT_EQ(StatusCode::OK_200, res->status);
  4352. }
  4353. #endif
  4354. TEST(ErrorHandlerTest, ContentLength) {
  4355. Server svr;
  4356. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4357. res.status = StatusCode::OK_200;
  4358. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4359. "text/html"); // <= Content-Length still 13
  4360. });
  4361. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4362. res.set_content("Hello World!\n", "text/plain");
  4363. res.status = 524;
  4364. });
  4365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4366. auto se = detail::scope_exit([&] {
  4367. svr.stop();
  4368. thread.join();
  4369. ASSERT_FALSE(svr.is_running());
  4370. });
  4371. svr.wait_until_ready();
  4372. {
  4373. Client cli(HOST, PORT);
  4374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::OK_200, res->status);
  4377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4380. }
  4381. }
  4382. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4383. TEST(ExceptionTest, WithoutExceptionHandler) {
  4384. Server svr;
  4385. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4386. throw std::runtime_error("exception...");
  4387. });
  4388. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4389. throw std::runtime_error("exception\r\n...");
  4390. });
  4391. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. listen_thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. Client cli("localhost", PORT);
  4399. {
  4400. auto res = cli.Get("/exception");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4403. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4404. }
  4405. {
  4406. auto res = cli.Get("/unknown");
  4407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4408. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4409. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4410. }
  4411. }
  4412. TEST(ExceptionTest, WithExceptionHandler) {
  4413. Server svr;
  4414. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4415. std::exception_ptr ep) {
  4416. EXPECT_FALSE(ep == nullptr);
  4417. try {
  4418. std::rethrow_exception(ep);
  4419. } catch (std::exception &e) {
  4420. EXPECT_EQ("abc", std::string(e.what()));
  4421. } catch (...) {}
  4422. res.status = StatusCode::InternalServerError_500;
  4423. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4424. "text/html"); // <= Content-Length still 13 at this point
  4425. });
  4426. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4427. res.set_content("Hello World!\n", "text/plain");
  4428. throw std::runtime_error("abc");
  4429. });
  4430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4431. auto se = detail::scope_exit([&] {
  4432. svr.stop();
  4433. thread.join();
  4434. ASSERT_FALSE(svr.is_running());
  4435. });
  4436. svr.wait_until_ready();
  4437. for (size_t i = 0; i < 10; i++) {
  4438. Client cli(HOST, PORT);
  4439. for (size_t j = 0; j < 100; j++) {
  4440. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4442. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4443. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4444. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4445. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4446. }
  4447. cli.set_keep_alive(true);
  4448. for (size_t j = 0; j < 100; j++) {
  4449. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4452. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4453. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4454. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4455. }
  4456. }
  4457. }
  4458. TEST(ExceptionTest, AndErrorHandler) {
  4459. Server svr;
  4460. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4461. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4462. });
  4463. svr.set_exception_handler(
  4464. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4465. EXPECT_FALSE(ep == nullptr);
  4466. try {
  4467. std::rethrow_exception(ep);
  4468. } catch (std::exception &e) {
  4469. res.set_content(e.what(), "text/html");
  4470. } catch (...) {}
  4471. res.status = StatusCode::InternalServerError_500;
  4472. });
  4473. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4474. throw std::runtime_error("EXCEPTION");
  4475. });
  4476. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4477. res.set_content("ERROR", "text/html");
  4478. res.status = StatusCode::InternalServerError_500;
  4479. });
  4480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli(HOST, PORT);
  4488. {
  4489. auto res = cli.Get("/exception");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4492. EXPECT_EQ("EXCEPTION", res->body);
  4493. }
  4494. {
  4495. auto res = cli.Get("/error");
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4498. EXPECT_EQ("ERROR", res->body);
  4499. }
  4500. {
  4501. auto res = cli.Get("/invalid");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4504. EXPECT_EQ("NOT_FOUND", res->body);
  4505. }
  4506. }
  4507. #endif
  4508. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4509. // process_request() wraps only routing() in a try/catch, so an exception from
  4510. // any other user callback used to unwind into the task queue - which does not
  4511. // catch - and terminate the process. Each test below runs the server on a
  4512. // single worker thread: a guard that catches the exception but still loses the
  4513. // thread would otherwise be hidden by a spare worker serving the follow-up
  4514. // request. Note that a regression here aborts the whole test binary rather
  4515. // than failing one test.
  4516. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4517. Server svr;
  4518. svr.new_task_queue = [] { return new ThreadPool(1); };
  4519. std::atomic<int> reported{0};
  4520. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4521. if (err == Error::UserCallbackException) { reported++; }
  4522. });
  4523. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4524. res.set_content_provider(
  4525. 1024, "text/plain",
  4526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4527. sink.write("hello", 5);
  4528. throw std::runtime_error("from the content provider");
  4529. });
  4530. });
  4531. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4532. res.set_content("ok", "text/plain");
  4533. });
  4534. auto port = svr.bind_to_any_port(HOST);
  4535. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. listen_thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. Client cli(HOST, port);
  4544. cli.set_read_timeout(5, 0);
  4545. EXPECT_FALSE(cli.Get("/throw"));
  4546. }
  4547. EXPECT_TRUE(svr.is_running());
  4548. EXPECT_EQ(1, reported.load());
  4549. // A request on a fresh connection is still served.
  4550. {
  4551. Client cli(HOST, port);
  4552. auto res = cli.Get("/ok");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("ok", res->body);
  4556. }
  4557. }
  4558. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4559. Server svr;
  4560. svr.new_task_queue = [] { return new ThreadPool(1); };
  4561. std::atomic<bool> should_throw{true};
  4562. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4563. res.set_content("hi", "text/plain");
  4564. });
  4565. svr.set_post_routing_handler(
  4566. [&](const Request & /*req*/, Response & /*res*/) {
  4567. if (should_throw) {
  4568. throw std::runtime_error("from the post-routing handler");
  4569. }
  4570. });
  4571. auto port = svr.bind_to_any_port(HOST);
  4572. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. listen_thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, port);
  4581. cli.set_read_timeout(5, 0);
  4582. EXPECT_FALSE(cli.Get("/hi"));
  4583. }
  4584. EXPECT_TRUE(svr.is_running());
  4585. should_throw = false;
  4586. {
  4587. Client cli(HOST, port);
  4588. auto res = cli.Get("/hi");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("hi", res->body);
  4592. }
  4593. }
  4594. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4595. // The guard reports the caught exception through the error logger, which is
  4596. // a user callback too. A logger that throws has to be contained as well, or
  4597. // the process would terminate from inside the catch.
  4598. Server svr;
  4599. svr.new_task_queue = [] { return new ThreadPool(1); };
  4600. std::atomic<int> reported{0};
  4601. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4602. if (err == Error::UserCallbackException) {
  4603. reported++;
  4604. throw std::runtime_error("from the error logger");
  4605. }
  4606. });
  4607. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4608. res.set_content_provider(
  4609. 1024, "text/plain",
  4610. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4611. sink.write("hello", 5);
  4612. throw std::runtime_error("from the content provider");
  4613. });
  4614. });
  4615. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4616. res.set_content("ok", "text/plain");
  4617. });
  4618. auto port = svr.bind_to_any_port(HOST);
  4619. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4620. auto se = detail::scope_exit([&] {
  4621. svr.stop();
  4622. listen_thread.join();
  4623. ASSERT_FALSE(svr.is_running());
  4624. });
  4625. svr.wait_until_ready();
  4626. {
  4627. Client cli(HOST, port);
  4628. cli.set_read_timeout(5, 0);
  4629. EXPECT_FALSE(cli.Get("/throw"));
  4630. }
  4631. EXPECT_TRUE(svr.is_running());
  4632. EXPECT_EQ(1, reported.load());
  4633. {
  4634. Client cli(HOST, port);
  4635. auto res = cli.Get("/ok");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("ok", res->body);
  4639. }
  4640. }
  4641. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4642. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4643. // so the exception unwinds through the ws::WebSocket object on its way to
  4644. // the guard. None of the HTTP cases above cross that.
  4645. Server svr;
  4646. svr.new_task_queue = [] { return new ThreadPool(1); };
  4647. std::atomic<int> reported{0};
  4648. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4649. if (err == Error::UserCallbackException) { reported++; }
  4650. });
  4651. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4652. throw std::runtime_error("from the WebSocket handler");
  4653. });
  4654. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4655. res.set_content("ok", "text/plain");
  4656. });
  4657. auto port = svr.bind_to_any_port(HOST);
  4658. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4659. auto se = detail::scope_exit([&] {
  4660. svr.stop();
  4661. listen_thread.join();
  4662. ASSERT_FALSE(svr.is_running());
  4663. });
  4664. svr.wait_until_ready();
  4665. {
  4666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4667. "/ws");
  4668. auto res = client.connect();
  4669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4670. // The server dropped the connection instead of dying.
  4671. std::string msg;
  4672. EXPECT_FALSE(client.read(msg));
  4673. client.close();
  4674. }
  4675. EXPECT_TRUE(svr.is_running());
  4676. EXPECT_EQ(1, reported.load());
  4677. {
  4678. Client cli(HOST, port);
  4679. auto res = cli.Get("/ok");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. EXPECT_EQ("ok", res->body);
  4683. }
  4684. }
  4685. #ifdef CPPHTTPLIB_SSL_ENABLED
  4686. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4687. // SSLServer::process_and_close_socket() is a separate overload with its own
  4688. // guard, so it is exercised on its own.
  4689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. ASSERT_TRUE(svr.is_valid());
  4691. svr.new_task_queue = [] { return new ThreadPool(1); };
  4692. std::atomic<int> reported{0};
  4693. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4694. if (err == Error::UserCallbackException) { reported++; }
  4695. });
  4696. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4697. res.set_content_provider(
  4698. 1024, "text/plain",
  4699. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4700. sink.write("hello", 5);
  4701. throw std::runtime_error("from the content provider");
  4702. });
  4703. });
  4704. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4705. res.set_content("ok", "text/plain");
  4706. });
  4707. auto port = svr.bind_to_any_port(HOST);
  4708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. listen_thread.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. {
  4716. SSLClient cli(HOST, port);
  4717. cli.enable_server_certificate_verification(false);
  4718. cli.set_read_timeout(5, 0);
  4719. EXPECT_FALSE(cli.Get("/throw"));
  4720. }
  4721. EXPECT_TRUE(svr.is_running());
  4722. EXPECT_EQ(1, reported.load());
  4723. {
  4724. SSLClient cli(HOST, port);
  4725. cli.enable_server_certificate_verification(false);
  4726. auto res = cli.Get("/ok");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ("ok", res->body);
  4730. }
  4731. }
  4732. #endif
  4733. #endif
  4734. TEST(NoContentTest, ContentLength) {
  4735. Server svr;
  4736. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4737. res.status = StatusCode::NoContent_204;
  4738. });
  4739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, PORT);
  4748. auto res = cli.Get("/hi");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4751. // RFC 9110 8.6: none in a 204 response
  4752. EXPECT_FALSE(res->has_header("Content-Length"));
  4753. }
  4754. }
  4755. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4756. Server svr;
  4757. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4758. res.set_header("Content-Length", "5");
  4759. res.set_content("hello world", "text/plain");
  4760. });
  4761. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4762. // A body that reads as the last chunk, were it taken as chunked
  4763. res.set_header("Transfer-Encoding", "chunked");
  4764. res.set_content("0\r\n\r\n", "text/plain");
  4765. });
  4766. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4767. res.set_header("Content-Length", "2");
  4768. res.set_content_provider(5, "text/plain",
  4769. [](size_t offset, size_t length, DataSink &sink) {
  4770. sink.write(&"hello"[offset], length);
  4771. return true;
  4772. });
  4773. });
  4774. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4775. res.set_header("Content-Length", "1234");
  4776. });
  4777. thread t = thread([&] { svr.listen(HOST, PORT); });
  4778. auto se = detail::scope_exit([&] {
  4779. svr.stop();
  4780. t.join();
  4781. ASSERT_FALSE(svr.is_running());
  4782. });
  4783. svr.wait_until_ready();
  4784. Client cli(HOST, PORT);
  4785. cli.set_read_timeout(1, 0);
  4786. auto expect_body = [&](const Result &res, const std::string &body) {
  4787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4788. EXPECT_EQ(body, res->body);
  4789. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4790. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4791. };
  4792. Headers identity{{"Accept-Encoding", ""}};
  4793. expect_body(cli.Get("/body", identity), "hello world");
  4794. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4795. expect_body(cli.Get("/body",
  4796. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4797. "he");
  4798. expect_body(cli.Get("/provider", identity), "hello");
  4799. expect_body(cli.Get("/empty", identity), "");
  4800. // A HEAD response may give the length of the body a GET would get.
  4801. auto res = cli.Head("/empty");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4804. }
  4805. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4806. Server svr;
  4807. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4808. res.set_content("short", "text/plain");
  4809. });
  4810. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4811. res.body += " with a footer";
  4812. res.set_header("Transfer-Encoding", "chunked");
  4813. });
  4814. thread t = thread([&] { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. t.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. Client cli(HOST, PORT);
  4822. cli.set_read_timeout(1, 0);
  4823. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ("short with a footer", res->body);
  4826. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4827. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4828. }
  4829. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4830. Server svr;
  4831. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4832. res.set_header("Content-Length", "3");
  4833. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4834. sink.write("abc", 3);
  4835. sink.done();
  4836. return true;
  4837. });
  4838. });
  4839. thread t = thread([&] { svr.listen(HOST, PORT); });
  4840. auto se = detail::scope_exit([&] {
  4841. svr.stop();
  4842. t.join();
  4843. ASSERT_FALSE(svr.is_running());
  4844. });
  4845. svr.wait_until_ready();
  4846. Client cli(HOST, PORT);
  4847. cli.set_keep_alive(true);
  4848. auto res = cli.Get("/");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ("abc", res->body);
  4851. EXPECT_FALSE(res->has_header("Content-Length"));
  4852. EXPECT_EQ("close", res->get_header_value("Connection"));
  4853. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4854. // No body to delimit
  4855. auto head = cli.Head("/");
  4856. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4857. EXPECT_FALSE(head->has_header("Connection"));
  4858. }
  4859. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4860. #ifdef CPPHTTPLIB_SSL_ENABLED
  4861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4862. ASSERT_TRUE(svr.is_valid());
  4863. #else
  4864. Server svr;
  4865. #endif
  4866. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4867. if (req.path == "/routing_handler") {
  4868. res.set_header("PRE_ROUTING", "on");
  4869. res.set_content("Routing Handler", "text/plain");
  4870. return httplib::Server::HandlerResponse::Handled;
  4871. }
  4872. return httplib::Server::HandlerResponse::Unhandled;
  4873. });
  4874. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4875. res.set_content("Error", "text/html");
  4876. });
  4877. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4878. if (req.path == "/routing_handler") {
  4879. res.set_header("POST_ROUTING", "on");
  4880. }
  4881. });
  4882. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4883. res.set_content("Hello World!\n", "text/plain");
  4884. });
  4885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4886. auto se = detail::scope_exit([&] {
  4887. svr.stop();
  4888. thread.join();
  4889. ASSERT_FALSE(svr.is_running());
  4890. });
  4891. svr.wait_until_ready();
  4892. {
  4893. #ifdef CPPHTTPLIB_SSL_ENABLED
  4894. SSLClient cli(HOST, PORT);
  4895. cli.enable_server_certificate_verification(false);
  4896. #else
  4897. Client cli(HOST, PORT);
  4898. #endif
  4899. auto res = cli.Get("/routing_handler");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("Routing Handler", res->body);
  4903. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4904. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4905. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4906. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4907. }
  4908. {
  4909. #ifdef CPPHTTPLIB_SSL_ENABLED
  4910. SSLClient cli(HOST, PORT);
  4911. cli.enable_server_certificate_verification(false);
  4912. #else
  4913. Client cli(HOST, PORT);
  4914. #endif
  4915. auto res = cli.Get("/hi");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("Hello World!\n", res->body);
  4919. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4920. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4921. }
  4922. {
  4923. #ifdef CPPHTTPLIB_SSL_ENABLED
  4924. SSLClient cli(HOST, PORT);
  4925. cli.enable_server_certificate_verification(false);
  4926. #else
  4927. Client cli(HOST, PORT);
  4928. #endif
  4929. auto res = cli.Get("/aaa");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4932. EXPECT_EQ("Error", res->body);
  4933. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4934. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4935. }
  4936. }
  4937. TEST(RequestHandlerTest, PreRequestHandler) {
  4938. auto route_path = "/user/:user";
  4939. Server svr;
  4940. svr.Get("/hi", [](const Request &, Response &res) {
  4941. res.set_content("hi", "text/plain");
  4942. });
  4943. svr.Get(route_path, [](const Request &req, Response &res) {
  4944. res.set_content(req.path_params.at("user"), "text/plain");
  4945. });
  4946. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4947. if (req.matched_route == route_path) {
  4948. auto user = req.path_params.at("user");
  4949. if (user != "john") {
  4950. res.status = StatusCode::Forbidden_403;
  4951. res.set_content("error", "text/html");
  4952. return Server::HandlerResponse::Handled;
  4953. }
  4954. }
  4955. return Server::HandlerResponse::Unhandled;
  4956. });
  4957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4958. auto se = detail::scope_exit([&] {
  4959. svr.stop();
  4960. thread.join();
  4961. ASSERT_FALSE(svr.is_running());
  4962. });
  4963. svr.wait_until_ready();
  4964. Client cli(HOST, PORT);
  4965. {
  4966. auto res = cli.Get("/hi");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("hi", res->body);
  4970. }
  4971. {
  4972. auto res = cli.Get("/user/john");
  4973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. EXPECT_EQ("john", res->body);
  4976. }
  4977. {
  4978. auto res = cli.Get("/user/invalid-user");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4981. EXPECT_EQ("error", res->body);
  4982. }
  4983. }
  4984. // The pre-request handler must run before the request body is read, so a
  4985. // rejected request never forces the server to buffer a (potentially large)
  4986. // body. Here the posted body is larger than the payload limit: if the body
  4987. // were read first the server would answer 413, but because the pre-request
  4988. // handler runs first it answers 403 and the body is never read.
  4989. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4990. Server svr;
  4991. svr.set_payload_max_length(8);
  4992. auto handler_ran = false;
  4993. svr.Post("/reject", [&](const Request &req, Response &res) {
  4994. handler_ran = true;
  4995. res.set_content(req.body, "text/plain");
  4996. });
  4997. svr.Post("/accept", [](const Request &req, Response &res) {
  4998. res.set_content(req.body, "text/plain");
  4999. });
  5000. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5001. if (req.matched_route == "/reject") {
  5002. res.status = StatusCode::Forbidden_403;
  5003. res.set_content("denied", "text/plain");
  5004. return Server::HandlerResponse::Handled;
  5005. }
  5006. return Server::HandlerResponse::Unhandled;
  5007. });
  5008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli(HOST, PORT);
  5016. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5017. // rejects with 403 before the body is read, so 413 is never reached.
  5018. {
  5019. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5021. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5022. EXPECT_EQ("denied", res->body);
  5023. EXPECT_FALSE(handler_ran);
  5024. }
  5025. // An approved route still reads the body and enforces the payload limit.
  5026. {
  5027. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5030. }
  5031. }
  5032. TEST(UserDataTest, BasicOperations) {
  5033. httplib::UserData ud;
  5034. // Initially empty
  5035. EXPECT_FALSE(ud.has("key"));
  5036. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5037. // set and get
  5038. ud.set("key", 42);
  5039. EXPECT_TRUE(ud.has("key"));
  5040. auto *p = ud.get<int>("key");
  5041. ASSERT_NE(nullptr, p);
  5042. EXPECT_EQ(42, *p);
  5043. // Type mismatch → nullptr
  5044. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5045. // Overwrite with different type
  5046. ud.set("key", std::string("hello"));
  5047. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5048. auto *s = ud.get<std::string>("key");
  5049. ASSERT_NE(nullptr, s);
  5050. EXPECT_EQ("hello", *s);
  5051. // erase
  5052. ud.erase("key");
  5053. EXPECT_FALSE(ud.has("key"));
  5054. // clear
  5055. ud.set("a", 1);
  5056. ud.set("b", 2);
  5057. ud.clear();
  5058. EXPECT_FALSE(ud.has("a"));
  5059. EXPECT_FALSE(ud.has("b"));
  5060. }
  5061. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5062. struct AuthCtx {
  5063. std::string user_id;
  5064. };
  5065. Server svr;
  5066. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5067. res.user_data.set("auth", AuthCtx{"alice"});
  5068. return Server::HandlerResponse::Unhandled;
  5069. });
  5070. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5071. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5072. ASSERT_NE(nullptr, ctx);
  5073. res.set_content("Hello " + ctx->user_id, "text/plain");
  5074. });
  5075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5076. auto se = detail::scope_exit([&] {
  5077. svr.stop();
  5078. thread.join();
  5079. ASSERT_FALSE(svr.is_running());
  5080. });
  5081. svr.wait_until_ready();
  5082. Client cli(HOST, PORT);
  5083. auto res = cli.Get("/me");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("Hello alice", res->body);
  5087. }
  5088. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5089. struct RoleCtx {
  5090. std::string role;
  5091. };
  5092. Server svr;
  5093. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5094. res.user_data.set("role", RoleCtx{"admin"});
  5095. return Server::HandlerResponse::Unhandled;
  5096. });
  5097. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5098. auto *ctx = res.user_data.get<RoleCtx>("role");
  5099. ASSERT_NE(nullptr, ctx);
  5100. res.set_content(ctx->role, "text/plain");
  5101. });
  5102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5103. auto se = detail::scope_exit([&] {
  5104. svr.stop();
  5105. thread.join();
  5106. ASSERT_FALSE(svr.is_running());
  5107. });
  5108. svr.wait_until_ready();
  5109. Client cli(HOST, PORT);
  5110. auto res = cli.Get("/role");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. EXPECT_EQ("admin", res->body);
  5114. }
  5115. TEST(InvalidFormatTest, StatusCode) {
  5116. Server svr;
  5117. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5118. res.set_content("Hello World!\n", "text/plain");
  5119. res.status = 9999; // Status should be a three-digit code...
  5120. });
  5121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5122. auto se = detail::scope_exit([&] {
  5123. svr.stop();
  5124. thread.join();
  5125. ASSERT_FALSE(svr.is_running());
  5126. });
  5127. svr.wait_until_ready();
  5128. {
  5129. Client cli(HOST, PORT);
  5130. auto res = cli.Get("/hi");
  5131. ASSERT_FALSE(res);
  5132. }
  5133. }
  5134. TEST(URLFragmentTest, WithFragment) {
  5135. Server svr;
  5136. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5137. EXPECT_TRUE(req.target == "/hi");
  5138. });
  5139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5140. auto se = detail::scope_exit([&] {
  5141. svr.stop();
  5142. thread.join();
  5143. ASSERT_FALSE(svr.is_running());
  5144. });
  5145. svr.wait_until_ready();
  5146. {
  5147. Client cli(HOST, PORT);
  5148. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5149. EXPECT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. res = cli.Get("/hi%23key1=val1=key2=val2");
  5152. EXPECT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5154. }
  5155. }
  5156. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5157. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5158. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5159. Server svr;
  5160. std::vector<std::string> targets;
  5161. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5162. targets.push_back(req.target);
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5173. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5175. // A '?' after the '#' belongs to the fragment, not to the query.
  5176. Request req;
  5177. req.method = "GET";
  5178. req.path = "/hi#f?x=1";
  5179. req.params.emplace("a", "1");
  5180. Response res;
  5181. auto error = Error::Success;
  5182. EXPECT_TRUE(cli.send(req, res, error));
  5183. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5184. "/hi?a=1"}),
  5185. targets);
  5186. }
  5187. TEST(HeaderWriter, SetHeaderWriter) {
  5188. Server svr;
  5189. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5190. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5191. return detail::write_headers(strm, hdrs);
  5192. });
  5193. svr.Get("/hi", [](const Request &req, Response &res) {
  5194. auto it = req.headers.find("CustomClientHeader");
  5195. EXPECT_TRUE(it != req.headers.end());
  5196. EXPECT_EQ(it->second, "CustomClientValue");
  5197. res.set_content("Hello World!\n", "text/plain");
  5198. });
  5199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5200. auto se = detail::scope_exit([&] {
  5201. svr.stop();
  5202. thread.join();
  5203. ASSERT_FALSE(svr.is_running());
  5204. });
  5205. svr.wait_until_ready();
  5206. {
  5207. Client cli(HOST, PORT);
  5208. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5209. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5210. return detail::write_headers(strm, hdrs);
  5211. });
  5212. auto res = cli.Get("/hi");
  5213. EXPECT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. auto it = res->headers.find("CustomServerHeader");
  5216. EXPECT_TRUE(it != res->headers.end());
  5217. EXPECT_EQ(it->second, "CustomServerValue");
  5218. }
  5219. }
  5220. class ServerTest : public ::testing::Test {
  5221. protected:
  5222. ServerTest()
  5223. : cli_(HOST, PORT)
  5224. #ifdef CPPHTTPLIB_SSL_ENABLED
  5225. ,
  5226. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5227. #endif
  5228. {
  5229. #ifdef CPPHTTPLIB_SSL_ENABLED
  5230. cli_.enable_server_certificate_verification(false);
  5231. #endif
  5232. // Allow LARGE_DATA (100MB) responses
  5233. cli_.set_payload_max_length(200 * 1024 * 1024);
  5234. }
  5235. virtual void SetUp() {
  5236. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5237. svr_.set_payload_max_length(200 * 1024 * 1024);
  5238. svr_.set_mount_point("/", "./www");
  5239. svr_.set_mount_point("/mount", "./www2");
  5240. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5241. svr_.Get("/hi",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("Hello World!", "text/plain");
  5244. })
  5245. .Get("/file_content",
  5246. [&](const Request & /*req*/, Response &res) {
  5247. res.set_file_content("./www/dir/test.html");
  5248. })
  5249. .Get("/file_content_with_content_type",
  5250. [&](const Request & /*req*/, Response &res) {
  5251. res.set_file_content("./www/file", "text/plain");
  5252. })
  5253. .Get("/invalid_file_content",
  5254. [&](const Request & /*req*/, Response &res) {
  5255. res.set_file_content("./www/dir/invalid_file_path");
  5256. })
  5257. .Get("/http_response_splitting",
  5258. [&](const Request & /*req*/, Response &res) {
  5259. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5260. EXPECT_EQ(0U, res.headers.size());
  5261. EXPECT_FALSE(res.has_header("a"));
  5262. res.set_header("a", "1\nSet-Cookie: a=1");
  5263. EXPECT_EQ(0U, res.headers.size());
  5264. EXPECT_FALSE(res.has_header("a"));
  5265. res.set_header("a", "1\rSet-Cookie: a=1");
  5266. EXPECT_EQ(0U, res.headers.size());
  5267. EXPECT_FALSE(res.has_header("a"));
  5268. res.set_header("a\r\nb", "0");
  5269. EXPECT_EQ(0U, res.headers.size());
  5270. EXPECT_FALSE(res.has_header("a"));
  5271. res.set_header("a\rb", "0");
  5272. EXPECT_EQ(0U, res.headers.size());
  5273. EXPECT_FALSE(res.has_header("a"));
  5274. res.set_header("a\nb", "0");
  5275. EXPECT_EQ(0U, res.headers.size());
  5276. EXPECT_FALSE(res.has_header("a"));
  5277. res.set_redirect("1\r\nSet-Cookie: a=1");
  5278. EXPECT_EQ(0U, res.headers.size());
  5279. EXPECT_FALSE(res.has_header("Location"));
  5280. })
  5281. .Get("/slow",
  5282. [&](const Request & /*req*/, Response &res) {
  5283. std::this_thread::sleep_for(std::chrono::seconds(4));
  5284. res.set_content("slow", "text/plain");
  5285. })
  5286. #if 0
  5287. .Post("/slowpost",
  5288. [&](const Request & /*req*/, Response &res) {
  5289. std::this_thread::sleep_for(std::chrono::seconds(2));
  5290. res.set_content("slow", "text/plain");
  5291. })
  5292. #endif
  5293. .Get("/remote_addr",
  5294. [&](const Request &req, Response &res) {
  5295. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5296. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5297. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5298. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5300. #endif
  5301. res.set_content(req.remote_addr, "text/plain");
  5302. })
  5303. .Get("/local_addr",
  5304. [&](const Request &req, Response &res) {
  5305. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5306. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5308. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5310. #endif
  5311. auto local_addr = req.local_addr;
  5312. auto local_port = std::to_string(req.local_port);
  5313. res.set_content(local_addr.append(":").append(local_port),
  5314. "text/plain");
  5315. })
  5316. .Get("/endwith%",
  5317. [&](const Request & /*req*/, Response &res) {
  5318. res.set_content("Hello World!", "text/plain");
  5319. })
  5320. .Get("/a\\+\\+b",
  5321. [&](const Request &req, Response &res) {
  5322. ASSERT_TRUE(req.has_param("a +b"));
  5323. auto val = req.get_param_value("a +b");
  5324. res.set_content(val, "text/plain");
  5325. })
  5326. .Get("/", [&](const Request & /*req*/,
  5327. Response &res) { res.set_redirect("/hi"); })
  5328. .Post("/1",
  5329. [](const Request & /*req*/, Response &res) {
  5330. res.set_redirect("/2", StatusCode::SeeOther_303);
  5331. })
  5332. .Get("/2",
  5333. [](const Request & /*req*/, Response &res) {
  5334. res.set_content("redirected.", "text/plain");
  5335. res.status = StatusCode::OK_200;
  5336. })
  5337. .Post("/person",
  5338. [&](const Request &req, Response &res) {
  5339. if (req.has_param("name") && req.has_param("note")) {
  5340. persons_[req.get_param_value("name")] =
  5341. req.get_param_value("note");
  5342. } else {
  5343. res.status = StatusCode::BadRequest_400;
  5344. }
  5345. })
  5346. .Put("/person",
  5347. [&](const Request &req, Response &res) {
  5348. if (req.has_param("name") && req.has_param("note")) {
  5349. persons_[req.get_param_value("name")] =
  5350. req.get_param_value("note");
  5351. } else {
  5352. res.status = StatusCode::BadRequest_400;
  5353. }
  5354. })
  5355. .Get("/person/(.*)",
  5356. [&](const Request &req, Response &res) {
  5357. string name = req.matches[1];
  5358. if (persons_.find(name) != persons_.end()) {
  5359. auto note = persons_[name];
  5360. res.set_content(note, "text/plain");
  5361. } else {
  5362. res.status = StatusCode::NotFound_404;
  5363. }
  5364. })
  5365. .Delete("/person",
  5366. [&](const Request &req, Response &res) {
  5367. if (req.has_param("name")) {
  5368. string name = req.get_param_value("name");
  5369. if (persons_.find(name) != persons_.end()) {
  5370. persons_.erase(name);
  5371. res.set_content("DELETED", "text/plain");
  5372. } else {
  5373. res.status = StatusCode::NotFound_404;
  5374. }
  5375. } else {
  5376. res.status = StatusCode::BadRequest_400;
  5377. }
  5378. })
  5379. .Post("/x-www-form-urlencoded-json",
  5380. [&](const Request &req, Response &res) {
  5381. auto json = req.get_param_value("json");
  5382. ASSERT_EQ(JSON_DATA, json);
  5383. res.set_content(json, "appliation/json");
  5384. res.status = StatusCode::OK_200;
  5385. })
  5386. .Get("/streamed-chunked",
  5387. [&](const Request & /*req*/, Response &res) {
  5388. res.set_chunked_content_provider(
  5389. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5390. sink.os << "123";
  5391. sink.os << "456";
  5392. sink.os << "789";
  5393. sink.done();
  5394. return true;
  5395. });
  5396. })
  5397. .Get("/streamed-chunked-with-prohibited-trailer",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. auto i = new int(0);
  5400. // Declare both a prohibited trailer (Content-Length) and an
  5401. // allowed one
  5402. res.set_header("Trailer", "Content-Length, X-Allowed");
  5403. res.set_chunked_content_provider(
  5404. "text/plain",
  5405. [i](size_t /*offset*/, DataSink &sink) {
  5406. switch (*i) {
  5407. case 0: sink.os << "123"; break;
  5408. case 1: sink.os << "456"; break;
  5409. case 2: sink.os << "789"; break;
  5410. case 3: {
  5411. sink.done_with_trailer(
  5412. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5413. } break;
  5414. }
  5415. (*i)++;
  5416. return true;
  5417. },
  5418. [i](bool success) {
  5419. EXPECT_TRUE(success);
  5420. delete i;
  5421. });
  5422. })
  5423. .Get("/streamed-chunked2",
  5424. [&](const Request & /*req*/, Response &res) {
  5425. auto i = new int(0);
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: sink.done(); break;
  5434. }
  5435. (*i)++;
  5436. return true;
  5437. },
  5438. [i](bool success) {
  5439. EXPECT_TRUE(success);
  5440. delete i;
  5441. });
  5442. })
  5443. .Get("/streamed-chunked-with-trailer",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. auto i = new int(0);
  5446. res.set_header("Trailer", "Dummy1, Dummy2");
  5447. res.set_chunked_content_provider(
  5448. "text/plain",
  5449. [i](size_t /*offset*/, DataSink &sink) {
  5450. switch (*i) {
  5451. case 0: sink.os << "123"; break;
  5452. case 1: sink.os << "456"; break;
  5453. case 2: sink.os << "789"; break;
  5454. case 3: {
  5455. sink.done_with_trailer(
  5456. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5457. } break;
  5458. }
  5459. (*i)++;
  5460. return true;
  5461. },
  5462. [i](bool success) {
  5463. EXPECT_TRUE(success);
  5464. delete i;
  5465. });
  5466. })
  5467. .Get("/streamed",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content_provider(
  5470. 6, "text/plain",
  5471. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5472. sink.os << (offset < 3 ? "a" : "b");
  5473. return true;
  5474. });
  5475. })
  5476. .Get("/streamed-without-length",
  5477. [&](const Request & /*req*/, Response &res) {
  5478. auto data = new std::string("abcdefg");
  5479. res.set_content_provider(
  5480. "text/plain",
  5481. [data](size_t offset, DataSink &sink) {
  5482. if (offset < data->size()) {
  5483. sink.os << data->substr(offset);
  5484. }
  5485. sink.done();
  5486. return true;
  5487. },
  5488. [data](bool success) {
  5489. EXPECT_TRUE(success);
  5490. delete data;
  5491. });
  5492. })
  5493. .Get("/streamed-with-range",
  5494. [&](const Request &req, Response &res) {
  5495. auto data = new std::string("abcdefg");
  5496. // An explicit status keeps the server from picking the 206 it
  5497. // would otherwise choose for a ranged request, so the response
  5498. // is not a partial representation.
  5499. auto status = req.get_param_value("status");
  5500. if (status == "200") {
  5501. res.status = StatusCode::OK_200;
  5502. } else if (status == "403") {
  5503. res.status = StatusCode::Forbidden_403;
  5504. }
  5505. res.set_content_provider(
  5506. data->size(), "text/plain",
  5507. [data](size_t offset, size_t length, DataSink &sink) {
  5508. size_t DATA_CHUNK_SIZE = 4;
  5509. const auto &d = *data;
  5510. auto out_len =
  5511. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5512. auto ret =
  5513. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5514. EXPECT_TRUE(ret);
  5515. return true;
  5516. },
  5517. [data, &req](bool success) {
  5518. EXPECT_EQ(success, !req.has_param("error"));
  5519. delete data;
  5520. });
  5521. })
  5522. .Get("/streamed-cancel",
  5523. [&](const Request & /*req*/, Response &res) {
  5524. res.set_content_provider(
  5525. size_t(-1), "text/plain",
  5526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5527. sink.os << "data_chunk";
  5528. return true;
  5529. });
  5530. })
  5531. .Get("/regex-with-delimiter",
  5532. [&](const Request &req, Response & /*res*/) {
  5533. ASSERT_TRUE(req.has_param("key"));
  5534. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5535. })
  5536. .Get("/with-range",
  5537. [&](const Request & /*req*/, Response &res) {
  5538. res.set_content("abcdefg", "text/plain");
  5539. })
  5540. .Get("/test-start-time",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_NE(req.start_time_,
  5543. std::chrono::steady_clock::time_point::min());
  5544. })
  5545. .Get("/with-range-customized-response",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.status = StatusCode::BadRequest_400;
  5548. res.set_content(JSON_DATA, "application/json");
  5549. })
  5550. .Post("/chunked",
  5551. [&](const Request &req, Response & /*res*/) {
  5552. EXPECT_EQ(req.body, "dechunked post body");
  5553. })
  5554. .Post("/large-chunked",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. std::string expected(6 * 30 * 1024u, 'a');
  5557. EXPECT_EQ(req.body, expected);
  5558. })
  5559. .Post("/multipart",
  5560. [&](const Request &req, Response & /*res*/) {
  5561. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5562. req.form.get_field_count("text2") +
  5563. req.form.get_field_count("file3") +
  5564. req.form.get_field_count("file4"));
  5565. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5566. req.form.get_file_count("file2"));
  5567. ASSERT_TRUE(!req.form.has_file("???"));
  5568. ASSERT_TRUE(!req.form.has_field("???"));
  5569. ASSERT_TRUE(req.body.empty());
  5570. {
  5571. const auto &text = req.form.get_field("text1");
  5572. EXPECT_EQ("text default", text);
  5573. }
  5574. {
  5575. const auto &text = req.form.get_field("text2");
  5576. EXPECT_EQ("aωb", text);
  5577. }
  5578. {
  5579. const auto &file = req.form.get_file("file1");
  5580. EXPECT_EQ("hello.txt", file.filename);
  5581. EXPECT_EQ("text/plain", file.content_type);
  5582. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5583. }
  5584. {
  5585. const auto &file = req.form.get_file("file2");
  5586. EXPECT_EQ("world.json", file.filename);
  5587. EXPECT_EQ("application/json", file.content_type);
  5588. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5589. }
  5590. {
  5591. const auto &text = req.form.get_field("file3");
  5592. EXPECT_EQ(0u, text.size());
  5593. }
  5594. {
  5595. const auto &text = req.form.get_field("file4");
  5596. EXPECT_EQ(0u, text.size());
  5597. }
  5598. })
  5599. .Post("/multipart/multi_file_values",
  5600. [&](const Request &req, Response & /*res*/) {
  5601. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5602. req.form.get_field_count("multi_text1"));
  5603. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5604. ASSERT_TRUE(!req.form.has_file("???"));
  5605. ASSERT_TRUE(!req.form.has_field("???"));
  5606. ASSERT_TRUE(req.body.empty());
  5607. {
  5608. const auto &text = req.form.get_field("text");
  5609. EXPECT_EQ("default text", text);
  5610. }
  5611. {
  5612. const auto &text1_values = req.form.get_fields("multi_text1");
  5613. EXPECT_EQ(2u, text1_values.size());
  5614. EXPECT_EQ("aaaaa", text1_values[0]);
  5615. EXPECT_EQ("bbbbb", text1_values[1]);
  5616. }
  5617. {
  5618. const auto &file1_values = req.form.get_files("multi_file1");
  5619. EXPECT_EQ(2u, file1_values.size());
  5620. auto file1 = file1_values[0];
  5621. EXPECT_EQ(file1.filename, "hello.txt");
  5622. EXPECT_EQ(file1.content_type, "text/plain");
  5623. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5624. auto file2 = file1_values[1];
  5625. EXPECT_EQ(file2.filename, "world.json");
  5626. EXPECT_EQ(file2.content_type, "application/json");
  5627. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5628. }
  5629. })
  5630. .Post("/empty",
  5631. [&](const Request &req, Response &res) {
  5632. EXPECT_EQ(req.body, "");
  5633. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5635. res.set_content("empty", "text/plain");
  5636. })
  5637. .Post("/empty-no-content-type",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(req.body, "");
  5640. EXPECT_FALSE(req.has_header("Content-Type"));
  5641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5642. res.set_content("empty-no-content-type", "text/plain");
  5643. })
  5644. .Post("/path-only",
  5645. [&](const Request &req, Response &res) {
  5646. EXPECT_EQ(req.body, "");
  5647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5649. res.set_content("path-only", "text/plain");
  5650. })
  5651. .Post("/path-headers-only",
  5652. [&](const Request &req, Response &res) {
  5653. EXPECT_EQ(req.body, "");
  5654. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5655. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5656. EXPECT_EQ("world", req.get_header_value("hello"));
  5657. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5658. res.set_content("path-headers-only", "text/plain");
  5659. })
  5660. .Post("/post-large",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, LARGE_DATA);
  5663. res.set_content(req.body, "text/plain");
  5664. })
  5665. .Post("/post-loopback",
  5666. [&](const Request &, Response &res,
  5667. ContentReader const &content_reader) {
  5668. std::string body;
  5669. content_reader([&](const char *data, size_t data_length) {
  5670. body.append(data, data_length);
  5671. return true;
  5672. });
  5673. res.set_content(body, "text/plain");
  5674. })
  5675. .Put("/put-loopback",
  5676. [&](const Request &, Response &res,
  5677. ContentReader const &content_reader) {
  5678. std::string body;
  5679. content_reader([&](const char *data, size_t data_length) {
  5680. body.append(data, data_length);
  5681. return true;
  5682. });
  5683. res.set_content(body, "text/plain");
  5684. })
  5685. .Patch("/patch-loopback",
  5686. [&](const Request &, Response &res,
  5687. ContentReader const &content_reader) {
  5688. std::string body;
  5689. content_reader([&](const char *data, size_t data_length) {
  5690. body.append(data, data_length);
  5691. return true;
  5692. });
  5693. res.set_content(body, "text/plain");
  5694. })
  5695. .Put("/empty-no-content-type",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "");
  5698. EXPECT_FALSE(req.has_header("Content-Type"));
  5699. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5700. res.set_content("empty-no-content-type", "text/plain");
  5701. })
  5702. .Put("/put",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, "PUT");
  5705. res.set_content(req.body, "text/plain");
  5706. })
  5707. .Put("/put-large",
  5708. [&](const Request &req, Response &res) {
  5709. EXPECT_EQ(req.body, LARGE_DATA);
  5710. res.set_content(req.body, "text/plain");
  5711. })
  5712. .Patch("/patch",
  5713. [&](const Request &req, Response &res) {
  5714. EXPECT_EQ(req.body, "PATCH");
  5715. res.set_content(req.body, "text/plain");
  5716. })
  5717. .Delete("/delete",
  5718. [&](const Request & /*req*/, Response &res) {
  5719. res.set_content("DELETE", "text/plain");
  5720. })
  5721. .Delete("/delete-body",
  5722. [&](const Request &req, Response &res) {
  5723. EXPECT_EQ(req.body, "content");
  5724. res.set_content(req.body, "text/plain");
  5725. })
  5726. .Options(R"(\*)",
  5727. [&](const Request & /*req*/, Response &res) {
  5728. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5729. })
  5730. .CustomRoute("PROPFIND", "/dav/:id",
  5731. [&](const Request &req, Response &res) {
  5732. res.set_header("x-body-size",
  5733. std::to_string(req.body.size()));
  5734. res.set_header("x-matched-route", req.matched_route);
  5735. res.set_header("x-dav-id", req.path_params.at("id"));
  5736. res.status = StatusCode::MultiStatus_207;
  5737. res.set_content(req.body, "application/xml");
  5738. })
  5739. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5740. [&](const Request &req, Response &res) {
  5741. res.set_header("x-dav-match", req.matches[1]);
  5742. res.status = StatusCode::MultiStatus_207;
  5743. })
  5744. .CustomRoute("MKCOL", "/dav-mkcol",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_TRUE(req.body.empty());
  5747. res.status = StatusCode::Created_201;
  5748. })
  5749. .CustomRoute(
  5750. "REPORT", "/dav-report",
  5751. [&](const Request & /*req*/, Response &res,
  5752. const ContentReader &content_reader) {
  5753. std::string body;
  5754. content_reader([&](const char *data, size_t data_length) {
  5755. body.append(data, data_length);
  5756. return true;
  5757. });
  5758. res.set_header("x-body-size", std::to_string(body.size()));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(body, "application/xml");
  5761. })
  5762. .Get("/request-target",
  5763. [&](const Request &req, Response & /*res*/) {
  5764. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5765. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5766. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5767. })
  5768. .Get("/long-query-value",
  5769. [&](const Request &req, Response & /*res*/) {
  5770. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5771. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5772. })
  5773. .Get("/too-long-query-value",
  5774. [&](const Request &req, Response & /*res*/) {
  5775. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5776. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5777. })
  5778. .Get("/array-param",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5781. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5782. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5783. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5784. })
  5785. .Get("/array-param-values",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. auto values = req.get_param_values("array");
  5788. EXPECT_EQ(3u, values.size());
  5789. EXPECT_EQ("value1", values[0]);
  5790. EXPECT_EQ("value2", values[1]);
  5791. EXPECT_EQ("value3", values[2]);
  5792. auto empty = req.get_param_values("nonexistent");
  5793. EXPECT_TRUE(empty.empty());
  5794. })
  5795. .Post("/validate-no-multiple-headers",
  5796. [&](const Request &req, Response & /*res*/) {
  5797. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5798. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5799. })
  5800. .Post("/content_receiver",
  5801. [&](const Request &req, Response &res,
  5802. const ContentReader &content_reader) {
  5803. if (req.is_multipart_form_data()) {
  5804. std::vector<FormData> items;
  5805. content_reader(
  5806. [&](const FormData &file) {
  5807. items.push_back(file);
  5808. return true;
  5809. },
  5810. [&](const char *data, size_t data_length) {
  5811. items.back().content.append(data, data_length);
  5812. return true;
  5813. });
  5814. EXPECT_EQ(5u, items.size());
  5815. {
  5816. const auto &file = get_file_value(items, "text1");
  5817. EXPECT_TRUE(file.filename.empty());
  5818. EXPECT_EQ("text default", file.content);
  5819. }
  5820. {
  5821. const auto &file = get_file_value(items, "text2");
  5822. EXPECT_TRUE(file.filename.empty());
  5823. EXPECT_EQ("aωb", file.content);
  5824. }
  5825. {
  5826. const auto &file = get_file_value(items, "file1");
  5827. EXPECT_EQ("hello.txt", file.filename);
  5828. EXPECT_EQ("text/plain", file.content_type);
  5829. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5830. }
  5831. {
  5832. const auto &file = get_file_value(items, "file2");
  5833. EXPECT_EQ("world.json", file.filename);
  5834. EXPECT_EQ("application/json", file.content_type);
  5835. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5836. }
  5837. {
  5838. const auto &file = get_file_value(items, "file3");
  5839. EXPECT_TRUE(file.filename.empty());
  5840. EXPECT_EQ("application/octet-stream", file.content_type);
  5841. EXPECT_EQ(0u, file.content.size());
  5842. }
  5843. } else {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. EXPECT_EQ(7U, data_length);
  5847. body.append(data, data_length);
  5848. return true;
  5849. });
  5850. EXPECT_EQ(body, "content");
  5851. res.set_content(body, "text/plain");
  5852. }
  5853. })
  5854. .Put("/content_receiver",
  5855. [&](const Request & /*req*/, Response &res,
  5856. const ContentReader &content_reader) {
  5857. std::string body;
  5858. content_reader([&](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. EXPECT_EQ(body, "content");
  5863. res.set_content(body, "text/plain");
  5864. })
  5865. .Patch("/content_receiver",
  5866. [&](const Request & /*req*/, Response &res,
  5867. const ContentReader &content_reader) {
  5868. std::string body;
  5869. content_reader([&](const char *data, size_t data_length) {
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. })
  5876. .Post("/query-string-and-body",
  5877. [&](const Request &req, Response & /*res*/) {
  5878. ASSERT_TRUE(req.has_param("key"));
  5879. EXPECT_EQ(req.get_param_value("key"), "value");
  5880. EXPECT_EQ(req.body, "content");
  5881. })
  5882. .Get("/last-request",
  5883. [&](const Request &req, Response & /*res*/) {
  5884. EXPECT_EQ("close", req.get_header_value("Connection"));
  5885. })
  5886. .Get(R"(/redirect/(\d+))",
  5887. [&](const Request &req, Response &res) {
  5888. auto num = std::stoi(req.matches[1]) + 1;
  5889. std::string url = "/redirect/" + std::to_string(num);
  5890. res.set_redirect(url);
  5891. })
  5892. .Post("/binary",
  5893. [&](const Request &req, Response &res) {
  5894. EXPECT_EQ(4U, req.body.size());
  5895. EXPECT_EQ("application/octet-stream",
  5896. req.get_header_value("Content-Type"));
  5897. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5898. res.set_content(req.body, "application/octet-stream");
  5899. })
  5900. .Put("/binary",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_EQ(4U, req.body.size());
  5903. EXPECT_EQ("application/octet-stream",
  5904. req.get_header_value("Content-Type"));
  5905. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5906. res.set_content(req.body, "application/octet-stream");
  5907. })
  5908. .Patch("/binary",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(4U, req.body.size());
  5911. EXPECT_EQ("application/octet-stream",
  5912. req.get_header_value("Content-Type"));
  5913. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5914. res.set_content(req.body, "application/octet-stream");
  5915. })
  5916. .Delete("/binary",
  5917. [&](const Request &req, Response &res) {
  5918. EXPECT_EQ(4U, req.body.size());
  5919. EXPECT_EQ("application/octet-stream",
  5920. req.get_header_value("Content-Type"));
  5921. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5922. res.set_content(req.body, "application/octet-stream");
  5923. })
  5924. .Get("/issue1772",
  5925. [&](const Request & /*req*/, Response &res) {
  5926. res.status = 401;
  5927. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5928. })
  5929. .Delete("/issue609",
  5930. [](const httplib::Request &, httplib::Response &res,
  5931. const httplib::ContentReader &) {
  5932. res.set_content("ok", "text/plain");
  5933. })
  5934. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5935. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5936. .Get("/compress",
  5937. [&](const Request & /*req*/, Response &res) {
  5938. res.set_content(
  5939. "12345678901234567890123456789012345678901234567890123456789"
  5940. "01234567890123456789012345678901234567890",
  5941. "text/plain");
  5942. })
  5943. .Get("/compress-with-charset",
  5944. [&](const Request & /*req*/, Response &res) {
  5945. res.set_content(
  5946. "12345678901234567890123456789012345678901234567890123456789"
  5947. "01234567890123456789012345678901234567890",
  5948. "application/json; charset=utf-8");
  5949. })
  5950. .Get("/nocompress",
  5951. [&](const Request & /*req*/, Response &res) {
  5952. res.set_content(
  5953. "12345678901234567890123456789012345678901234567890123456789"
  5954. "01234567890123456789012345678901234567890",
  5955. "application/octet-stream");
  5956. })
  5957. .Post("/compress-multipart",
  5958. [&](const Request &req, Response & /*res*/) {
  5959. EXPECT_EQ(2u, req.form.fields.size());
  5960. ASSERT_TRUE(!req.form.has_field("???"));
  5961. {
  5962. const auto &text = req.form.get_field("key1");
  5963. EXPECT_EQ("test", text);
  5964. }
  5965. {
  5966. const auto &text = req.form.get_field("key2");
  5967. EXPECT_EQ("--abcdefg123", text);
  5968. }
  5969. })
  5970. #endif
  5971. ;
  5972. persons_["john"] = "programmer";
  5973. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5974. svr_.wait_until_ready();
  5975. }
  5976. virtual void TearDown() {
  5977. svr_.stop();
  5978. if (!request_threads_.empty()) {
  5979. std::this_thread::sleep_for(std::chrono::seconds(1));
  5980. for (auto &t : request_threads_) {
  5981. t.join();
  5982. }
  5983. }
  5984. t_.join();
  5985. }
  5986. map<string, string> persons_;
  5987. #ifdef CPPHTTPLIB_SSL_ENABLED
  5988. SSLClient cli_;
  5989. SSLServer svr_;
  5990. #else
  5991. Client cli_;
  5992. Server svr_;
  5993. #endif
  5994. thread t_;
  5995. std::vector<thread> request_threads_;
  5996. };
  5997. TEST_F(ServerTest, GetMethod200) {
  5998. auto res = cli_.Get("/hi");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ("HTTP/1.1", res->version);
  6001. EXPECT_EQ(StatusCode::OK_200, res->status);
  6002. EXPECT_EQ("OK", res->reason);
  6003. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6004. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6005. EXPECT_EQ("Hello World!", res->body);
  6006. }
  6007. TEST_F(ServerTest, GetEmptyFile) {
  6008. auto res = cli_.Get("/empty_file");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6012. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6013. EXPECT_EQ("", res->body);
  6014. }
  6015. TEST_F(ServerTest, GetFileContent) {
  6016. auto res = cli_.Get("/file_content");
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetFileContentWithRange) {
  6024. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6027. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6029. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6030. EXPECT_EQ("est", res->body);
  6031. }
  6032. TEST_F(ServerTest, GetFileContentWithContentType) {
  6033. auto res = cli_.Get("/file_content_with_content_type");
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6038. EXPECT_EQ("file\n", res->body);
  6039. }
  6040. TEST_F(ServerTest, GetInvalidFileContent) {
  6041. auto res = cli_.Get("/invalid_file_content");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6044. }
  6045. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6046. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ("HTTP/1.1", res->version);
  6049. EXPECT_EQ(StatusCode::OK_200, res->status);
  6050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6052. EXPECT_EQ("Hello World!", res->body);
  6053. }
  6054. TEST_F(ServerTest, GetMethod302) {
  6055. auto res = cli_.Get("/");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::Found_302, res->status);
  6058. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6059. }
  6060. TEST_F(ServerTest, GetMethod302Redirect) {
  6061. cli_.set_follow_location(true);
  6062. auto res = cli_.Get("/");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. EXPECT_EQ("Hello World!", res->body);
  6066. EXPECT_EQ("/hi", res->location);
  6067. }
  6068. TEST_F(ServerTest, GetMethod404) {
  6069. auto res = cli_.Get("/invalid");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6072. }
  6073. TEST_F(ServerTest, HeadMethod200) {
  6074. auto res = cli_.Head("/hi");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6078. EXPECT_TRUE(res->body.empty());
  6079. }
  6080. TEST_F(ServerTest, HeadMethod200Static) {
  6081. auto res = cli_.Head("/mount/dir/index.html");
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6085. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6086. EXPECT_TRUE(res->body.empty());
  6087. }
  6088. TEST_F(ServerTest, HeadMethod404) {
  6089. auto res = cli_.Head("/invalid");
  6090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6092. EXPECT_TRUE(res->body.empty());
  6093. }
  6094. TEST_F(ServerTest, GetMethodPersonJohn) {
  6095. auto res = cli_.Get("/person/john");
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. EXPECT_EQ(StatusCode::OK_200, res->status);
  6098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6099. EXPECT_EQ("programmer", res->body);
  6100. }
  6101. TEST_F(ServerTest, PostMethod1) {
  6102. auto res = cli_.Get("/person/john1");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6105. res = cli_.Post("/person", "name=john1&note=coder",
  6106. "application/x-www-form-urlencoded");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. ASSERT_EQ(StatusCode::OK_200, res->status);
  6109. res = cli_.Get("/person/john1");
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. ASSERT_EQ(StatusCode::OK_200, res->status);
  6112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6113. ASSERT_EQ("coder", res->body);
  6114. }
  6115. TEST_F(ServerTest, PostMethod2) {
  6116. auto res = cli_.Get("/person/john2");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6119. Params params;
  6120. params.emplace("name", "john2");
  6121. params.emplace("note", "coder");
  6122. res = cli_.Post("/person", params);
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. ASSERT_EQ(StatusCode::OK_200, res->status);
  6125. res = cli_.Get("/person/john2");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::OK_200, res->status);
  6128. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. ASSERT_EQ("coder", res->body);
  6130. }
  6131. TEST_F(ServerTest, PutMethod3) {
  6132. auto res = cli_.Get("/person/john3");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6135. Params params;
  6136. params.emplace("name", "john3");
  6137. params.emplace("note", "coder");
  6138. res = cli_.Put("/person", params);
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. res = cli_.Get("/person/john3");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6145. ASSERT_EQ("coder", res->body);
  6146. }
  6147. TEST_F(ServerTest, DeleteMethod1) {
  6148. auto res = cli_.Get("/person/john4");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6151. Params params;
  6152. params.emplace("name", "john4");
  6153. params.emplace("note", "coder");
  6154. res = cli_.Post("/person", params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. res = cli_.Get("/person/john4");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. ASSERT_EQ("coder", res->body);
  6162. Params delete_params;
  6163. delete_params.emplace("name", "john4");
  6164. res = cli_.Delete("/person", delete_params);
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("DELETED", res->body);
  6168. res = cli_.Get("/person/john4");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6171. }
  6172. TEST_F(ServerTest, DeleteMethod2) {
  6173. auto res = cli_.Get("/person/john5");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6176. Params params;
  6177. params.emplace("name", "john5");
  6178. params.emplace("note", "developer");
  6179. res = cli_.Post("/person", params);
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. ASSERT_EQ(StatusCode::OK_200, res->status);
  6182. res = cli_.Get("/person/john5");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6186. ASSERT_EQ("developer", res->body);
  6187. Params delete_params;
  6188. delete_params.emplace("name", "john5");
  6189. Headers headers;
  6190. headers.emplace("Custom-Header", "test-value");
  6191. res = cli_.Delete("/person", headers, delete_params);
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::OK_200, res->status);
  6194. ASSERT_EQ("DELETED", res->body);
  6195. res = cli_.Get("/person/john5");
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6198. }
  6199. TEST_F(ServerTest, DeleteMethod3) {
  6200. auto res = cli_.Get("/person/john6");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6203. Params params;
  6204. params.emplace("name", "john6");
  6205. params.emplace("note", "tester");
  6206. res = cli_.Post("/person", params);
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. ASSERT_EQ(StatusCode::OK_200, res->status);
  6209. res = cli_.Get("/person/john6");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. ASSERT_EQ(StatusCode::OK_200, res->status);
  6212. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6213. ASSERT_EQ("tester", res->body);
  6214. Params delete_params;
  6215. delete_params.emplace("name", "john6");
  6216. Headers headers;
  6217. headers.emplace("Custom-Header", "test-value");
  6218. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::OK_200, res->status);
  6221. ASSERT_EQ("DELETED", res->body);
  6222. res = cli_.Get("/person/john6");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6225. }
  6226. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6227. Params params;
  6228. params.emplace("json", JSON_DATA);
  6229. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ(JSON_DATA, res->body);
  6233. }
  6234. TEST_F(ServerTest, PostEmptyContent) {
  6235. auto res = cli_.Post("/empty", "", "text/plain");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. ASSERT_EQ(StatusCode::OK_200, res->status);
  6238. ASSERT_EQ("empty", res->body);
  6239. }
  6240. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6241. auto res = cli_.Post("/empty-no-content-type");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("empty-no-content-type", res->body);
  6245. }
  6246. TEST_F(ServerTest, PostPathOnly) {
  6247. auto res = cli_.Post("/path-only");
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. ASSERT_EQ(StatusCode::OK_200, res->status);
  6250. ASSERT_EQ("path-only", res->body);
  6251. }
  6252. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6253. auto res = cli_.Post("/path-headers-only",
  6254. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. ASSERT_EQ(StatusCode::OK_200, res->status);
  6257. ASSERT_EQ("path-headers-only", res->body);
  6258. }
  6259. TEST_F(ServerTest, PostLarge) {
  6260. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. ASSERT_EQ(StatusCode::OK_200, res->status);
  6263. EXPECT_EQ(LARGE_DATA, res->body);
  6264. }
  6265. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6266. auto res = cli_.Put("/empty-no-content-type");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::OK_200, res->status);
  6269. ASSERT_EQ("empty-no-content-type", res->body);
  6270. }
  6271. TEST_F(ServerTest, GetMethodDir) {
  6272. auto res = cli_.Get("/dir/");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6276. auto body = R"(<html>
  6277. <head>
  6278. </head>
  6279. <body>
  6280. <a href="/dir/test.html">Test</a>
  6281. <a href="/hi">hi</a>
  6282. </body>
  6283. </html>
  6284. )";
  6285. EXPECT_EQ(body, res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDirTest) {
  6288. auto res = cli_.Get("/dir/test.html");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6292. EXPECT_EQ("test.html", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6295. auto res = cli_.Get("/dir/../dir/test.html");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. EXPECT_EQ("test.html", res->body);
  6300. }
  6301. TEST_F(ServerTest, GetMethodInvalidPath) {
  6302. auto res = cli_.Get("/dir/../test.html");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6307. auto res = cli_.Get("/../www/dir/test.html");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6310. }
  6311. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6312. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetMethodDirMountTest) {
  6317. auto res = cli_.Get("/mount/dir/test.html");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("test.html", res->body);
  6322. }
  6323. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6324. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6328. EXPECT_EQ("test.html", res->body);
  6329. }
  6330. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6331. auto res = cli_.Get("/mount/dir/../test.html");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. }
  6335. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6336. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. }
  6340. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6341. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6344. }
  6345. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6346. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6351. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6356. auto res = cli_.Get("/mount/dir");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6359. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6360. }
  6361. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6362. auto res = cli_.Get("//dir");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6365. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6366. }
  6367. TEST_F(ServerTest, PostMethod303) {
  6368. auto res = cli_.Post("/1", "body", "text/plain");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6371. EXPECT_EQ("/2", res->get_header_value("Location"));
  6372. }
  6373. TEST_F(ServerTest, PostMethod303Redirect) {
  6374. cli_.set_follow_location(true);
  6375. auto res = cli_.Post("/1", "body", "text/plain");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::OK_200, res->status);
  6378. EXPECT_EQ("redirected.", res->body);
  6379. EXPECT_EQ("/2", res->location);
  6380. }
  6381. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6382. auto res = cli_.Get("/dir/test.abcde");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6386. EXPECT_EQ("abcde", res->body);
  6387. }
  6388. TEST_F(ServerTest, StaticFileRange) {
  6389. auto res =
  6390. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6393. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6394. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6395. EXPECT_EQ(true, res->has_header("Content-Range"));
  6396. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6397. EXPECT_EQ(std::string("cd"), res->body);
  6398. }
  6399. TEST_F(ServerTest, StaticFileRanges) {
  6400. auto res = cli_.Get("/dir/test.abcde",
  6401. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6404. EXPECT_TRUE(
  6405. res->get_header_value("Content-Type")
  6406. .find(
  6407. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6408. 0);
  6409. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6410. }
  6411. TEST_F(ServerTest, StaticFileRangeHead) {
  6412. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6415. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6416. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6417. EXPECT_EQ(true, res->has_header("Content-Range"));
  6418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6419. }
  6420. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6421. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6425. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6426. EXPECT_EQ(true, res->has_header("Content-Range"));
  6427. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6428. res->get_header_value("Content-Range"));
  6429. EXPECT_EQ("LAST\n", res->body);
  6430. }
  6431. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6432. auto res =
  6433. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6437. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6438. EXPECT_EQ(true, res->has_header("Content-Range"));
  6439. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6440. }
  6441. TEST_F(ServerTest, StaticFileBigFile) {
  6442. auto res = cli_.Get("/dir/1MB.txt");
  6443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6446. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6447. }
  6448. TEST_F(ServerTest, InvalidBaseDirMount) {
  6449. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6450. }
  6451. TEST_F(ServerTest, Binary) {
  6452. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6453. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6454. "application/octet-stream");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. ASSERT_EQ(StatusCode::OK_200, res->status);
  6457. ASSERT_EQ(4U, res->body.size());
  6458. res = cli_.Put("/binary", binary.data(), binary.size(),
  6459. "application/octet-stream");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. ASSERT_EQ(StatusCode::OK_200, res->status);
  6462. ASSERT_EQ(4U, res->body.size());
  6463. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6464. "application/octet-stream");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. ASSERT_EQ(StatusCode::OK_200, res->status);
  6467. ASSERT_EQ(4U, res->body.size());
  6468. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6469. "application/octet-stream");
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ(4U, res->body.size());
  6473. }
  6474. TEST_F(ServerTest, BinaryString) {
  6475. auto binary = std::string("\x00\x01\x02\x03", 4);
  6476. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. ASSERT_EQ(StatusCode::OK_200, res->status);
  6479. ASSERT_EQ(4U, res->body.size());
  6480. res = cli_.Put("/binary", binary, "application/octet-stream");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. ASSERT_EQ(StatusCode::OK_200, res->status);
  6483. ASSERT_EQ(4U, res->body.size());
  6484. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. ASSERT_EQ(4U, res->body.size());
  6488. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, EmptyRequest) {
  6494. auto res = cli_.Get("");
  6495. ASSERT_TRUE(!res);
  6496. EXPECT_EQ(Error::Connection, res.error());
  6497. }
  6498. TEST_F(ServerTest, LongRequest) {
  6499. std::string request;
  6500. for (size_t i = 0; i < 545; i++) {
  6501. request += "/TooLongRequest";
  6502. }
  6503. request += "OK";
  6504. auto res = cli_.Get(request.c_str());
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST_F(ServerTest, TooLongRequest) {
  6509. std::string request;
  6510. for (size_t i = 0; i < 546; i++) {
  6511. request += "/TooLongRequest";
  6512. }
  6513. request += "_NG";
  6514. auto start = std::chrono::high_resolution_clock::now();
  6515. cli_.set_keep_alive(true);
  6516. auto res = cli_.Get(request.c_str());
  6517. auto end = std::chrono::high_resolution_clock::now();
  6518. auto elapsed =
  6519. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6520. .count();
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6523. EXPECT_LE(elapsed, 1000);
  6524. EXPECT_EQ("close", res->get_header_value("Connection"));
  6525. EXPECT_FALSE(cli_.is_socket_open());
  6526. }
  6527. TEST_F(ServerTest, AlmostTooLongRequest) {
  6528. // test for #2046 - URI length check shouldn't include other content on req
  6529. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6530. // leading /, space, HTTP/1.1)
  6531. std::string request =
  6532. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6533. auto res = cli_.Get(request.c_str());
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, LongHeader) {
  6538. Request req;
  6539. req.method = "GET";
  6540. req.path = "/hi";
  6541. std::string host_and_port;
  6542. host_and_port += HOST;
  6543. host_and_port += ":";
  6544. host_and_port += std::to_string(PORT);
  6545. req.headers.emplace("Host", host_and_port.c_str());
  6546. req.headers.emplace("Accept", "*/*");
  6547. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6548. req.headers.emplace(
  6549. "Header-Name",
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@");
  6579. auto res = std::make_shared<Response>();
  6580. auto error = Error::Success;
  6581. auto ret = cli_.send(req, *res, error);
  6582. ASSERT_TRUE(ret);
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. }
  6585. TEST_F(ServerTest, LongQueryValue) {
  6586. auto start = std::chrono::high_resolution_clock::now();
  6587. cli_.set_keep_alive(true);
  6588. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6589. auto end = std::chrono::high_resolution_clock::now();
  6590. auto elapsed =
  6591. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6592. .count();
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6595. EXPECT_LE(elapsed, 1000);
  6596. EXPECT_EQ("close", res->get_header_value("Connection"));
  6597. EXPECT_FALSE(cli_.is_socket_open());
  6598. }
  6599. TEST_F(ServerTest, TooLongQueryValue) {
  6600. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6601. ASSERT_FALSE(res);
  6602. EXPECT_EQ(Error::Read, res.error());
  6603. }
  6604. TEST_F(ServerTest, TooLongHeader) {
  6605. Request req;
  6606. req.method = "GET";
  6607. req.path = "/hi";
  6608. std::string host_and_port;
  6609. host_and_port += HOST;
  6610. host_and_port += ":";
  6611. host_and_port += std::to_string(PORT);
  6612. req.headers.emplace("Host", host_and_port.c_str());
  6613. req.headers.emplace("Accept", "*/*");
  6614. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6615. req.headers.emplace(
  6616. "Header-Name",
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@");
  6646. auto res = std::make_shared<Response>();
  6647. auto error = Error::Success;
  6648. auto ret = cli_.send(req, *res, error);
  6649. ASSERT_TRUE(ret);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. TEST_F(ServerTest, HeaderCountAtLimit) {
  6653. // Test with headers just under the 100 limit
  6654. httplib::Headers headers;
  6655. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6656. // This should keep us just under the 100 header limit
  6657. for (int i = 0; i < 95; i++) {
  6658. std::string name = "X-Test-Header-" + std::to_string(i);
  6659. std::string value = "value" + std::to_string(i);
  6660. headers.emplace(name, value);
  6661. }
  6662. // This should work fine as we're under the limit
  6663. auto res = cli_.Get("/hi", headers);
  6664. EXPECT_TRUE(res);
  6665. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6666. }
  6667. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6668. // Test with many headers to exceed the 100 limit
  6669. httplib::Headers headers;
  6670. // Add 150 headers to definitely exceed the 100 limit
  6671. for (int i = 0; i < 150; i++) {
  6672. std::string name = "X-Test-Header-" + std::to_string(i);
  6673. std::string value = "value" + std::to_string(i);
  6674. headers.emplace(name, value);
  6675. }
  6676. // This should fail due to exceeding header count limit
  6677. cli_.set_keep_alive(true);
  6678. auto res = cli_.Get("/hi", headers);
  6679. // The server should respond with 400 Bad Request
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6682. EXPECT_EQ("close", res->get_header_value("Connection"));
  6683. EXPECT_FALSE(cli_.is_socket_open());
  6684. }
  6685. TEST_F(ServerTest, PercentEncoding) {
  6686. auto res = cli_.Get("/e%6edwith%");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. }
  6690. TEST_F(ServerTest, PercentEncodingUnicode) {
  6691. auto res = cli_.Get("/e%u006edwith%");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, InvalidPercentEncoding) {
  6696. auto res = cli_.Get("/%endwith%");
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. }
  6700. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6701. auto res = cli_.Get("/%uendwith%");
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6704. }
  6705. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6706. auto res = cli_.Get("/hello?aaa=bbb%");
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6709. }
  6710. TEST_F(ServerTest, PlusSignEncoding) {
  6711. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. EXPECT_EQ("a +b", res->body);
  6715. }
  6716. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6717. // This test simulates a potential DoS attack using many headers
  6718. // to verify our security fix prevents memory exhaustion
  6719. httplib::Headers attack_headers;
  6720. // Attempt to add many headers like an attacker would (200 headers to far
  6721. // exceed limit)
  6722. for (int i = 0; i < 200; i++) {
  6723. std::string name = "X-Attack-Header-" + std::to_string(i);
  6724. std::string value = "attack_payload_" + std::to_string(i);
  6725. attack_headers.emplace(name, value);
  6726. }
  6727. // Try to POST with excessive headers
  6728. cli_.set_keep_alive(true);
  6729. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6730. // Should either fail or return 400 Bad Request due to security limit
  6731. if (res) {
  6732. // If we get a response, it should be 400 Bad Request
  6733. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6734. EXPECT_EQ("close", res->get_header_value("Connection"));
  6735. }
  6736. EXPECT_FALSE(cli_.is_socket_open());
  6737. }
  6738. TEST_F(ServerTest, MultipartFormData) {
  6739. UploadFormDataItems items = {
  6740. {"text1", "text default", "", ""},
  6741. {"text2", "aωb", "", ""},
  6742. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6743. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6744. {"file3", "", "", "application/octet-stream"},
  6745. {"file4", "", "", " application/json tmp-string "}};
  6746. auto res = cli_.Post("/multipart", items);
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. }
  6750. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6751. UploadFormDataItems items = {
  6752. {"text", "default text", "", ""},
  6753. {"multi_text1", "aaaaa", "", ""},
  6754. {"multi_text1", "bbbbb", "", ""},
  6755. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6756. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6757. "application/json"},
  6758. };
  6759. auto res = cli_.Post("/multipart/multi_file_values", items);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6764. auto res = cli_.Get("/hi");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6768. EXPECT_EQ("Hello World!", res->body);
  6769. }
  6770. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6771. Request req;
  6772. req.method = "POST";
  6773. req.path = "/chunked";
  6774. std::string host_and_port;
  6775. host_and_port += HOST;
  6776. host_and_port += ":";
  6777. host_and_port += std::to_string(PORT);
  6778. req.headers.emplace("Host", host_and_port.c_str());
  6779. req.headers.emplace("Accept", "*/*");
  6780. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6781. req.headers.emplace("Content-Type", "text/plain");
  6782. req.headers.emplace("Content-Length", "0");
  6783. req.headers.emplace(
  6784. "Transfer-Encoding",
  6785. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6786. // Client does not chunk, so make a chunked body manually.
  6787. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6788. auto res = std::make_shared<Response>();
  6789. auto error = Error::Success;
  6790. auto ret = cli_.send(req, *res, error);
  6791. ASSERT_TRUE(ret);
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. }
  6794. template <typename ClientT>
  6795. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6796. int expected_status) {
  6797. Request req;
  6798. req.method = "POST";
  6799. req.path = "/chunked";
  6800. std::string host_and_port;
  6801. host_and_port += HOST;
  6802. host_and_port += ":";
  6803. host_and_port += std::to_string(PORT);
  6804. req.headers.emplace("Host", host_and_port.c_str());
  6805. req.headers.emplace("Content-Length", "0");
  6806. req.headers.emplace("Transfer-Encoding", "chunked");
  6807. req.body = body;
  6808. auto res = std::make_shared<Response>();
  6809. auto error = Error::Success;
  6810. ASSERT_TRUE(cli.send(req, *res, error));
  6811. EXPECT_EQ(expected_status, res->status);
  6812. }
  6813. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6814. // rather than treat them as valid lengths.
  6815. template <typename ClientT>
  6816. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6817. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6818. }
  6819. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6820. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6821. }
  6822. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6823. expect_chunked_body_rejected(
  6824. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6825. }
  6826. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6827. // chunk-size line carries no CR, LF or other control character ahead of its
  6828. // terminator. Such a line must be refused rather than read as extension text.
  6829. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6830. expect_chunked_body_rejected(
  6831. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6832. }
  6833. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6834. expect_chunked_body_rejected(
  6835. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6836. }
  6837. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6838. expect_chunked_body_rejected(
  6839. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6842. // The literal stays split: a hex escape consumes every hex digit that
  6843. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6844. expect_chunked_body_rejected(
  6845. cli_, "4;a\x01"
  6846. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6847. }
  6848. TEST_F(ServerTest, AcceptsChunkExtension) {
  6849. expect_chunked_body_status(cli_,
  6850. "4;name=value\r\ndech\r\n"
  6851. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6852. "0;last\r\n\r\n",
  6853. StatusCode::OK_200);
  6854. }
  6855. TEST_F(ServerTest, GetStreamed2) {
  6856. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6859. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6860. EXPECT_EQ(true, res->has_header("Content-Range"));
  6861. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6862. EXPECT_EQ(std::string("ab"), res->body);
  6863. }
  6864. TEST_F(ServerTest, GetStreamed) {
  6865. auto res = cli_.Get("/streamed");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6869. EXPECT_EQ(std::string("aaabbb"), res->body);
  6870. }
  6871. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6872. auto res = cli_.Get("/streamed-without-length",
  6873. Headers{make_range_header({{0, -1}})});
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ(false, res->has_header("Content-Length"));
  6877. EXPECT_EQ(false, res->has_header("Content-Range"));
  6878. EXPECT_EQ(std::string("abcdefg"), res->body);
  6879. }
  6880. TEST_F(ServerTest, GetStreamedWithRange1) {
  6881. auto res =
  6882. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6885. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6886. EXPECT_EQ(true, res->has_header("Content-Range"));
  6887. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6888. EXPECT_EQ(std::string("def"), res->body);
  6889. }
  6890. TEST_F(ServerTest, GetStreamedWithRange2) {
  6891. auto res =
  6892. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6895. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6896. EXPECT_EQ(true, res->has_header("Content-Range"));
  6897. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6898. EXPECT_EQ(std::string("bcdefg"), res->body);
  6899. }
  6900. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6901. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6904. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6905. EXPECT_EQ(true, res->has_header("Content-Range"));
  6906. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6907. EXPECT_EQ(std::string("efg"), res->body);
  6908. }
  6909. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6910. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6911. // the entire representation.
  6912. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6913. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6916. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6917. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6918. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6919. }
  6920. }
  6921. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6922. auto res =
  6923. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6926. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6927. EXPECT_EQ(false, res->has_header("Content-Range"));
  6928. EXPECT_EQ(0U, res->body.size());
  6929. }
  6930. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6931. // Only a 206 is served as a partial representation. Under any other status
  6932. // `apply_ranges()` reported the full content length, so the body must match
  6933. // that header, and the content provider must never be asked for an offset
  6934. // outside the representation.
  6935. auto check = [&](int status, const char *range) {
  6936. auto path =
  6937. std::string("/streamed-with-range?status=") + std::to_string(status);
  6938. auto ctx = path + " Range: " + range;
  6939. auto res = cli_.Get(path, Headers{{"Range", range}});
  6940. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6941. EXPECT_EQ(status, res->status) << ctx;
  6942. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6944. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6945. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6946. };
  6947. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6948. check(403, "bytes=3-5");
  6949. // The offset is far past the representation.
  6950. check(403, "bytes=100000-100200");
  6951. // `first_pos` is still -1 here, and the bounds asserts in
  6952. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6953. check(403, "bytes=-3");
  6954. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6955. // multipart branch would have written one that is empty.
  6956. check(403, "bytes=1-2, 4-5");
  6957. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6958. // covers the whole representation.
  6959. check(200, "bytes=3-5");
  6960. check(200, "bytes=1-2, 4-5");
  6961. }
  6962. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6963. auto res =
  6964. cli_.Get("/streamed-with-range",
  6965. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6966. "92233720368547758079223372036854775807"}});
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6969. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6970. EXPECT_EQ(false, res->has_header("Content-Range"));
  6971. EXPECT_EQ(0U, res->body.size());
  6972. }
  6973. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6974. auto res = cli_.Get(
  6975. "/with-range",
  6976. Headers{{"Range",
  6977. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6978. {"Accept-Encoding", ""}});
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6981. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6982. EXPECT_EQ(true, res->has_header("Content-Range"));
  6983. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6984. EXPECT_EQ(std::string("abcdefg"), res->body);
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6987. auto res = cli_.Get("/with-range", Headers{
  6988. {"Range", "bytes=0-"},
  6989. {"Accept-Encoding", ""},
  6990. });
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6993. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6994. EXPECT_EQ(true, res->has_header("Content-Range"));
  6995. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6996. EXPECT_EQ(std::string("abcdefg"), res->body);
  6997. }
  6998. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6999. auto res = cli_.Get("/streamed-with-range",
  7000. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7003. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7004. EXPECT_EQ(false, res->has_header("Content-Range"));
  7005. EXPECT_EQ(267U, res->body.size());
  7006. // Check that both range contents are present
  7007. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7008. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7009. // Check that Content-Range headers are present for both ranges
  7010. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7011. std::string::npos);
  7012. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7013. std::string::npos);
  7014. }
  7015. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7016. Ranges ranges;
  7017. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7018. ranges.emplace_back(0, -1);
  7019. }
  7020. auto res = cli_.Get("/streamed-with-range?error",
  7021. Headers{{make_range_header(ranges)}});
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7024. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7025. EXPECT_EQ(false, res->has_header("Content-Range"));
  7026. EXPECT_EQ(0U, res->body.size());
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7029. auto res = cli_.Get("/streamed-with-range",
  7030. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7033. EXPECT_EQ(5U, res->body.size());
  7034. // Check that overlapping ranges are coalesced into a single range
  7035. EXPECT_EQ("bcdef", res->body);
  7036. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7037. // Should be single range, not multipart
  7038. EXPECT_TRUE(res->has_header("Content-Range"));
  7039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(268U, res->body.size());
  7047. // Check that both range contents are present
  7048. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7049. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7050. // Check that Content-Range headers are present for both ranges
  7051. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7052. std::string::npos);
  7053. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7054. std::string::npos);
  7055. }
  7056. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7057. auto res = cli_.Get("/streamed-with-range",
  7058. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7061. EXPECT_EQ(269U, res->body.size());
  7062. // Check that both duplicate range contents are present
  7063. size_t first_abc = res->body.find("abc\r\n");
  7064. EXPECT_TRUE(first_abc != std::string::npos);
  7065. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7066. EXPECT_TRUE(second_abc != std::string::npos);
  7067. // Check that Content-Range headers are present for both ranges
  7068. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7069. EXPECT_TRUE(first_range != std::string::npos);
  7070. size_t second_range =
  7071. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7072. EXPECT_TRUE(second_range != std::string::npos);
  7073. }
  7074. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7075. auto res =
  7076. cli_.Get("/streamed-with-range?error",
  7077. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7079. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7081. EXPECT_EQ(false, res->has_header("Content-Range"));
  7082. EXPECT_EQ(0U, res->body.size());
  7083. }
  7084. TEST_F(ServerTest, GetStreamedEndless) {
  7085. uint64_t offset = 0;
  7086. auto res = cli_.Get("/streamed-cancel",
  7087. [&](const char * /*data*/, uint64_t data_length) {
  7088. if (offset < 100) {
  7089. offset += data_length;
  7090. return true;
  7091. }
  7092. return false;
  7093. });
  7094. ASSERT_TRUE(!res);
  7095. EXPECT_EQ(Error::Canceled, res.error());
  7096. }
  7097. TEST_F(ServerTest, ClientStop) {
  7098. std::atomic_size_t count{4};
  7099. std::vector<std::thread> threads;
  7100. for (auto i = count.load(); i != 0; --i) {
  7101. threads.emplace_back([&]() {
  7102. auto res = cli_.Get("/streamed-cancel",
  7103. [&](const char *, uint64_t) { return true; });
  7104. --count;
  7105. ASSERT_TRUE(!res);
  7106. EXPECT_TRUE(res.error() == Error::Canceled ||
  7107. res.error() == Error::Read || res.error() == Error::Write);
  7108. });
  7109. }
  7110. std::this_thread::sleep_for(std::chrono::seconds(2));
  7111. while (count != 0) {
  7112. cli_.stop();
  7113. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7114. }
  7115. for (auto &t : threads) {
  7116. t.join();
  7117. }
  7118. }
  7119. TEST_F(ServerTest, GetWithRange1) {
  7120. auto res = cli_.Get("/with-range", Headers{
  7121. make_range_header({{3, 5}}),
  7122. {"Accept-Encoding", ""},
  7123. });
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7126. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7127. EXPECT_EQ(true, res->has_header("Content-Range"));
  7128. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7129. EXPECT_EQ(std::string("def"), res->body);
  7130. }
  7131. TEST_F(ServerTest, GetWithRange2) {
  7132. auto res = cli_.Get("/with-range", Headers{
  7133. make_range_header({{1, -1}}),
  7134. {"Accept-Encoding", ""},
  7135. });
  7136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7138. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7139. EXPECT_EQ(true, res->has_header("Content-Range"));
  7140. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7141. EXPECT_EQ(std::string("bcdefg"), res->body);
  7142. }
  7143. TEST_F(ServerTest, GetWithRange3) {
  7144. auto res = cli_.Get("/with-range", Headers{
  7145. make_range_header({{0, 0}}),
  7146. {"Accept-Encoding", ""},
  7147. });
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7150. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7151. EXPECT_EQ(true, res->has_header("Content-Range"));
  7152. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7153. EXPECT_EQ(std::string("a"), res->body);
  7154. }
  7155. TEST_F(ServerTest, GetWithRange4) {
  7156. auto res = cli_.Get("/with-range", Headers{
  7157. make_range_header({{-1, 2}}),
  7158. {"Accept-Encoding", ""},
  7159. });
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ(true, res->has_header("Content-Range"));
  7164. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7165. EXPECT_EQ(std::string("fg"), res->body);
  7166. }
  7167. TEST_F(ServerTest, GetWithRange5) {
  7168. auto res = cli_.Get("/with-range", Headers{
  7169. make_range_header({{0, 5}}),
  7170. {"Accept-Encoding", ""},
  7171. });
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7174. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7177. EXPECT_EQ(std::string("abcdef"), res->body);
  7178. }
  7179. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7180. auto res =
  7181. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7184. }
  7185. TEST_F(ServerTest, GetWithRangeMultipart) {
  7186. auto res =
  7187. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7190. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(false, res->has_header("Content-Range"));
  7192. EXPECT_EQ(267U, res->body.size());
  7193. }
  7194. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7195. auto res = cli_.Get("/with-range",
  7196. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7199. }
  7200. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7201. auto res = cli_.Get("/with-range-customized-response",
  7202. Headers{{make_range_header({{1, 2}})}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7205. EXPECT_EQ(true, res->has_header("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(JSON_DATA, res->body);
  7208. }
  7209. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7210. auto res = cli_.Get("/with-range-customized-response",
  7211. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. EXPECT_EQ(true, res->has_header("Content-Length"));
  7215. EXPECT_EQ(false, res->has_header("Content-Range"));
  7216. EXPECT_EQ(JSON_DATA, res->body);
  7217. }
  7218. TEST_F(ServerTest, Issue1772) {
  7219. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7222. }
  7223. TEST_F(ServerTest, Issue609) {
  7224. auto res = cli_.Delete("/issue609");
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::OK_200, res->status);
  7227. EXPECT_EQ(std::string("ok"), res->body);
  7228. }
  7229. TEST_F(ServerTest, GetStreamedChunked) {
  7230. auto res = cli_.Get("/streamed-chunked");
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::OK_200, res->status);
  7233. EXPECT_EQ(std::string("123456789"), res->body);
  7234. }
  7235. TEST_F(ServerTest, GetStreamedChunked2) {
  7236. auto res = cli_.Get("/streamed-chunked2");
  7237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7238. EXPECT_EQ(StatusCode::OK_200, res->status);
  7239. EXPECT_EQ(std::string("123456789"), res->body);
  7240. }
  7241. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7242. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ(std::string("123456789"), res->body);
  7246. EXPECT_TRUE(res->has_header("Trailer"));
  7247. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7248. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7249. // Trailers are now stored separately from headers (security fix)
  7250. EXPECT_EQ(2U, res->trailers.size());
  7251. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7252. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7253. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7254. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7255. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7256. // Verify trailers are NOT in headers (security verification)
  7257. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7258. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7259. }
  7260. TEST_F(ServerTest, LargeChunkedPost) {
  7261. Request req;
  7262. req.method = "POST";
  7263. req.path = "/large-chunked";
  7264. std::string host_and_port;
  7265. host_and_port += HOST;
  7266. host_and_port += ":";
  7267. host_and_port += std::to_string(PORT);
  7268. req.headers.emplace("Host", host_and_port.c_str());
  7269. req.headers.emplace("Accept", "*/*");
  7270. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7271. req.headers.emplace("Content-Type", "text/plain");
  7272. req.headers.emplace("Content-Length", "0");
  7273. req.headers.emplace("Transfer-Encoding", "chunked");
  7274. std::string long_string(30 * 1024u, 'a');
  7275. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7276. // Attempt to make a large enough post to exceed OS buffers, to test that
  7277. // the server handles short reads if the full chunk data isn't available.
  7278. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7279. auto res = std::make_shared<Response>();
  7280. auto error = Error::Success;
  7281. auto ret = cli_.send(req, *res, error);
  7282. ASSERT_TRUE(ret);
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. }
  7285. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7286. auto res = cli_.Get("/remote_addr");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7290. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7291. }
  7292. TEST_F(ServerTest, GetMethodLocalAddr) {
  7293. auto res = cli_.Get("/local_addr");
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7297. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7298. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7299. }
  7300. TEST_F(ServerTest, HTTPResponseSplitting) {
  7301. auto res = cli_.Get("/http_response_splitting");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. }
  7305. TEST_F(ServerTest, SlowRequest) {
  7306. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7307. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7308. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7309. }
  7310. #if 0
  7311. TEST_F(ServerTest, SlowPost) {
  7312. char buffer[64 * 1024];
  7313. memset(buffer, 0x42, sizeof(buffer));
  7314. auto res = cli_.Post(
  7315. "/slowpost", 64 * 1024 * 1024,
  7316. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7317. auto ret = sink.write(buffer, sizeof(buffer));
  7318. EXPECT_TRUE(ret);
  7319. return true;
  7320. },
  7321. "text/plain");
  7322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7323. EXPECT_EQ(StatusCode::OK_200, res->status);
  7324. }
  7325. TEST_F(ServerTest, SlowPostFail) {
  7326. char buffer[64 * 1024];
  7327. memset(buffer, 0x42, sizeof(buffer));
  7328. cli_.set_write_timeout(std::chrono::seconds(0));
  7329. auto res = cli_.Post(
  7330. "/slowpost", 64 * 1024 * 1024,
  7331. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7332. sink.write(buffer, sizeof(buffer));
  7333. return true;
  7334. },
  7335. "text/plain");
  7336. ASSERT_TRUE(!res);
  7337. EXPECT_EQ(Error::Write, res.error());
  7338. }
  7339. #endif
  7340. TEST_F(ServerTest, Put) {
  7341. auto res = cli_.Put("/put", "PUT", "text/plain");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. EXPECT_EQ("PUT", res->body);
  7345. }
  7346. TEST_F(ServerTest, PutWithContentProvider) {
  7347. auto res = cli_.Put(
  7348. "/put", 3,
  7349. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7350. sink.os << "PUT";
  7351. return true;
  7352. },
  7353. "text/plain");
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("PUT", res->body);
  7357. }
  7358. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7359. auto res = cli_.Post(
  7360. "/post", 42,
  7361. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7362. return false;
  7363. },
  7364. "text/plain");
  7365. ASSERT_TRUE(!res);
  7366. EXPECT_EQ(Error::Canceled, res.error());
  7367. }
  7368. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7369. auto res = cli_.Put(
  7370. "/put",
  7371. [](size_t /*offset*/, DataSink &sink) {
  7372. sink.os << "PUT";
  7373. sink.done();
  7374. return true;
  7375. },
  7376. "text/plain");
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::OK_200, res->status);
  7379. EXPECT_EQ("PUT", res->body);
  7380. }
  7381. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7382. auto res = cli_.Post(
  7383. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7384. "text/plain");
  7385. ASSERT_TRUE(!res);
  7386. EXPECT_EQ(Error::Canceled, res.error());
  7387. }
  7388. TEST_F(ServerTest, PostLoopBack) {
  7389. std::string body;
  7390. auto res = cli_.Post(
  7391. "/post-loopback", 9,
  7392. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7393. EXPECT_EQ(9u, length);
  7394. sink.write("123", 3);
  7395. sink.write("456", 3);
  7396. sink.write("789", 3);
  7397. return true;
  7398. },
  7399. "text/plain",
  7400. [&body](const char *data, size_t data_length) {
  7401. body.append(data, data_length);
  7402. return true;
  7403. });
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ("123456789", body);
  7407. }
  7408. TEST_F(ServerTest, PutLoopBack) {
  7409. std::string body;
  7410. auto res = cli_.Put(
  7411. "/put-loopback", 9,
  7412. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7413. EXPECT_EQ(9u, length);
  7414. sink.write("123", 3);
  7415. sink.write("456", 3);
  7416. sink.write("789", 3);
  7417. return true;
  7418. },
  7419. "text/plain",
  7420. [&body](const char *data, size_t data_length) {
  7421. body.append(data, data_length);
  7422. return true;
  7423. });
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("123456789", body);
  7427. }
  7428. TEST_F(ServerTest, PatchLoopBack) {
  7429. std::string body;
  7430. auto res = cli_.Patch(
  7431. "/patch-loopback", 9,
  7432. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7433. EXPECT_EQ(9u, length);
  7434. sink.write("123", 3);
  7435. sink.write("456", 3);
  7436. sink.write("789", 3);
  7437. return true;
  7438. },
  7439. "text/plain",
  7440. [&body](const char *data, size_t data_length) {
  7441. body.append(data, data_length);
  7442. return true;
  7443. });
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. EXPECT_EQ("123456789", body);
  7447. }
  7448. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7449. std::string body;
  7450. auto res = cli_.Post(
  7451. "/post-loopback",
  7452. [](size_t /*offset*/, DataSink &sink) {
  7453. sink.write("123", 3);
  7454. sink.write("456", 3);
  7455. sink.write("789", 3);
  7456. sink.done();
  7457. return true;
  7458. },
  7459. "text/plain",
  7460. [&body](const char *data, size_t data_length) {
  7461. body.append(data, data_length);
  7462. return true;
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("123456789", body);
  7467. }
  7468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7469. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7470. cli_.set_compress(true);
  7471. auto res = cli_.Put(
  7472. "/put", 3,
  7473. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7474. sink.os << "PUT";
  7475. return true;
  7476. },
  7477. "text/plain");
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::OK_200, res->status);
  7480. EXPECT_EQ("PUT", res->body);
  7481. }
  7482. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Post(
  7485. "/post", 42,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7487. return false;
  7488. },
  7489. "text/plain");
  7490. ASSERT_TRUE(!res);
  7491. EXPECT_EQ(Error::Canceled, res.error());
  7492. }
  7493. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7494. cli_.set_compress(true);
  7495. auto res = cli_.Put(
  7496. "/put",
  7497. [](size_t /*offset*/, DataSink &sink) {
  7498. sink.os << "PUT";
  7499. sink.done();
  7500. return true;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("PUT", res->body);
  7506. }
  7507. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7508. cli_.set_compress(true);
  7509. auto res = cli_.Post(
  7510. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7511. "text/plain");
  7512. ASSERT_TRUE(!res);
  7513. EXPECT_EQ(Error::Canceled, res.error());
  7514. }
  7515. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7516. cli_.set_compress(true);
  7517. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ(LARGE_DATA, res->body);
  7521. }
  7522. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7525. Client cli(s.c_str());
  7526. cli.enable_server_certificate_verification(false);
  7527. #else
  7528. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7529. Client cli(s.c_str());
  7530. #endif
  7531. cli.set_compress(true);
  7532. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(LARGE_DATA, res->body);
  7536. // The compressed size should be less than a 10th of the original. May vary
  7537. // depending on the zlib library.
  7538. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7539. static_cast<uint64_t>(10 * 1024 * 1024));
  7540. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7541. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7542. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7544. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7545. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7546. #endif
  7547. }
  7548. TEST_F(ServerTest, PutContentWithDeflate) {
  7549. cli_.set_compress(false);
  7550. Headers headers;
  7551. headers.emplace("Content-Encoding", "deflate");
  7552. // PUT in deflate format:
  7553. auto res = cli_.Put("/put", headers,
  7554. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("PUT", res->body);
  7558. }
  7559. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7560. Headers headers;
  7561. headers.emplace("Accept-Encoding", "gzip, deflate");
  7562. auto res = cli_.Get("/streamed-chunked", headers);
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::OK_200, res->status);
  7565. EXPECT_EQ(std::string("123456789"), res->body);
  7566. }
  7567. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7568. Headers headers;
  7569. headers.emplace("Accept-Encoding", "gzip, deflate");
  7570. auto res = cli_.Get("/streamed-chunked2", headers);
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ(std::string("123456789"), res->body);
  7574. }
  7575. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7576. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. TEST(GzipDecompressor, ChunkedDecompression) {
  7581. std::string data;
  7582. for (size_t i = 0; i < 32 * 1024; ++i) {
  7583. data.push_back(static_cast<char>('a' + i % 26));
  7584. }
  7585. std::string compressed_data;
  7586. {
  7587. httplib::detail::gzip_compressor compressor;
  7588. bool result = compressor.compress(
  7589. data.data(), data.size(),
  7590. /*last=*/true,
  7591. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7592. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7593. compressed_data_size);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(result);
  7597. }
  7598. std::string decompressed_data;
  7599. {
  7600. httplib::detail::gzip_decompressor decompressor;
  7601. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7602. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7603. size_t chunk_size = 130;
  7604. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7605. chunk_begin += chunk_size) {
  7606. size_t current_chunk_size =
  7607. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7608. bool result = decompressor.decompress(
  7609. compressed_data.data() + chunk_begin, current_chunk_size,
  7610. [&](const char *decompressed_data_chunk,
  7611. size_t decompressed_data_chunk_size) {
  7612. decompressed_data.insert(decompressed_data.size(),
  7613. decompressed_data_chunk,
  7614. decompressed_data_chunk_size);
  7615. return true;
  7616. });
  7617. ASSERT_TRUE(result);
  7618. }
  7619. }
  7620. ASSERT_EQ(data, decompressed_data);
  7621. }
  7622. TEST(GzipDecompressor, DeflateDecompression) {
  7623. std::string original_text = "Raw deflate without gzip";
  7624. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7625. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7626. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7627. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7628. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7629. std::string decompressed_data;
  7630. {
  7631. httplib::detail::gzip_decompressor decompressor;
  7632. bool result = decompressor.decompress(
  7633. compressed_data.data(), compressed_data.size(),
  7634. [&](const char *decompressed_data_chunk,
  7635. size_t decompressed_data_chunk_size) {
  7636. decompressed_data.insert(decompressed_data.size(),
  7637. decompressed_data_chunk,
  7638. decompressed_data_chunk_size);
  7639. return true;
  7640. });
  7641. ASSERT_TRUE(result);
  7642. }
  7643. ASSERT_EQ(original_text, decompressed_data);
  7644. }
  7645. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7646. std::string original_text = "Raw deflate without gzip";
  7647. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7648. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7649. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7650. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7651. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7652. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7653. std::string decompressed_data;
  7654. {
  7655. httplib::detail::gzip_decompressor decompressor;
  7656. bool result = decompressor.decompress(
  7657. compressed_data.data(), compressed_data.size(),
  7658. [&](const char *decompressed_data_chunk,
  7659. size_t decompressed_data_chunk_size) {
  7660. decompressed_data.insert(decompressed_data.size(),
  7661. decompressed_data_chunk,
  7662. decompressed_data_chunk_size);
  7663. return true;
  7664. });
  7665. ASSERT_TRUE(result);
  7666. }
  7667. ASSERT_EQ(original_text, decompressed_data);
  7668. }
  7669. #endif
  7670. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7671. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "br");
  7674. auto res = cli_.Get("/streamed-chunked", headers);
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. EXPECT_EQ(std::string("123456789"), res->body);
  7678. }
  7679. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7680. Headers headers;
  7681. headers.emplace("Accept-Encoding", "br");
  7682. auto res = cli_.Get("/streamed-chunked2", headers);
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::OK_200, res->status);
  7685. EXPECT_EQ(std::string("123456789"), res->body);
  7686. }
  7687. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Put(
  7690. "/put", 3,
  7691. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7692. sink.os << "PUT";
  7693. return true;
  7694. },
  7695. "text/plain");
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("PUT", res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put",
  7704. [](size_t /*offset*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. sink.done();
  7707. return true;
  7708. },
  7709. "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_EQ("PUT", res->body);
  7713. }
  7714. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7715. cli_.set_compress(true);
  7716. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ(LARGE_DATA, res->body);
  7720. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7721. }
  7722. #endif
  7723. TEST_F(ServerTest, Patch) {
  7724. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PATCH", res->body);
  7728. }
  7729. TEST_F(ServerTest, Delete) {
  7730. auto res = cli_.Delete("/delete");
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. EXPECT_EQ("DELETE", res->body);
  7734. }
  7735. TEST_F(ServerTest, DeleteContentReceiver) {
  7736. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("content", res->body);
  7740. }
  7741. TEST_F(ServerTest, Options) {
  7742. auto res = cli_.Options("*");
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7746. EXPECT_TRUE(res->body.empty());
  7747. }
  7748. TEST_F(ServerTest, URL) {
  7749. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, ArrayParam) {
  7754. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. }
  7758. TEST_F(ServerTest, ArrayParamValues) {
  7759. auto res =
  7760. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. TEST_F(ServerTest, NoMultipleHeaders) {
  7765. Headers headers = {{"Content-Length", "5"}};
  7766. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7767. "text/plain");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, PostContentReceiver) {
  7772. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. ASSERT_EQ(StatusCode::OK_200, res->status);
  7775. ASSERT_EQ("content", res->body);
  7776. }
  7777. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7778. UploadFormDataItems items = {
  7779. {"text1", "text default", "", ""},
  7780. {"text2", "aωb", "", ""},
  7781. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7782. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7783. {"file3", "", "", "application/octet-stream"},
  7784. };
  7785. auto res = cli_.Post("/content_receiver", items);
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. }
  7789. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7790. UploadFormDataItems items = {
  7791. {"text1", "text default", "", ""},
  7792. {"text2", "aωb", "", ""},
  7793. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7794. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7795. {"file3", "", "", "application/octet-stream"},
  7796. };
  7797. auto boundary = std::string("+++++");
  7798. std::string body;
  7799. for (const auto &item : items) {
  7800. body += "--" + boundary + "\r\n";
  7801. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7802. if (!item.filename.empty()) {
  7803. body += "; filename=\"" + item.filename + "\"";
  7804. }
  7805. body += "\r\n";
  7806. if (!item.content_type.empty()) {
  7807. body += "Content-Type: " + item.content_type + "\r\n";
  7808. }
  7809. body += "\r\n";
  7810. body += item.content + "\r\n";
  7811. }
  7812. body += "--" + boundary + "--\r\n";
  7813. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7814. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST(MultipartFormDataTest, FieldEscaping) {
  7819. Server svr;
  7820. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7821. const ContentReader &content_reader) {
  7822. ASSERT_TRUE(req.is_multipart_form_data());
  7823. std::vector<FormData> received;
  7824. content_reader(
  7825. [&](const FormData &file) {
  7826. received.push_back(file);
  7827. return true;
  7828. },
  7829. [&](const char *data, size_t data_length) {
  7830. received.back().content.append(data, data_length);
  7831. return true;
  7832. });
  7833. // '"', CR and LF in names and filenames are escaped following the
  7834. // WHATWG HTML standard, so each part still parses as a single part
  7835. // with no injected headers. Content types get CR/LF escaped too,
  7836. // while '"' (legal there, e.g. quoted charset) is preserved.
  7837. ASSERT_EQ(4U, received.size());
  7838. EXPECT_EQ("na%22me", received[0].name);
  7839. EXPECT_EQ("quoted name", received[0].content);
  7840. EXPECT_EQ("file", received[1].name);
  7841. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7842. received[1].filename);
  7843. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7844. EXPECT_EQ("injected", received[1].content);
  7845. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7846. EXPECT_EQ("my%22file.txt", received[2].filename);
  7847. EXPECT_EQ("cr lf name", received[2].content);
  7848. EXPECT_EQ("typed", received[3].name);
  7849. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7850. received[3].content_type);
  7851. EXPECT_EQ("typed content", received[3].content);
  7852. });
  7853. auto port = svr.bind_to_any_port("localhost");
  7854. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7855. auto se = detail::scope_exit([&] {
  7856. svr.stop();
  7857. t.join();
  7858. ASSERT_FALSE(svr.is_running());
  7859. });
  7860. svr.wait_until_ready();
  7861. Client cli("localhost", port);
  7862. UploadFormDataItems items = {
  7863. {"na\"me", "quoted name", "", ""},
  7864. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7865. "application/octet-stream"},
  7866. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7867. {"typed", "typed content", "",
  7868. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7869. };
  7870. auto res = cli.Post("/post", items);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. }
  7874. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7875. const UploadFormDataItems items = {
  7876. {"name1", "Content 1", "", ""},
  7877. {"name2", "Content 2", "file2.txt", "text/plain"},
  7878. };
  7879. Server svr;
  7880. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7881. const ContentReader &content_reader) {
  7882. ASSERT_TRUE(req.is_multipart_form_data());
  7883. std::vector<FormData> received;
  7884. content_reader(
  7885. [&](const FormData &file) {
  7886. received.push_back(file);
  7887. return true;
  7888. },
  7889. [&](const char *data, size_t data_length) {
  7890. received.back().content.append(data, data_length);
  7891. return true;
  7892. });
  7893. ASSERT_EQ(2U, received.size());
  7894. EXPECT_EQ("name1", received[0].name);
  7895. EXPECT_EQ("Content 1", received[0].content);
  7896. EXPECT_EQ("name2", received[1].name);
  7897. EXPECT_EQ("Content 2", received[1].content);
  7898. EXPECT_EQ("file2.txt", received[1].filename);
  7899. EXPECT_EQ("text/plain", received[1].content_type);
  7900. });
  7901. auto port = svr.bind_to_any_port("localhost");
  7902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7903. auto se = detail::scope_exit([&] {
  7904. svr.stop();
  7905. t.join();
  7906. ASSERT_FALSE(svr.is_running());
  7907. });
  7908. svr.wait_until_ready();
  7909. Client cli("localhost", port);
  7910. // Whole-body serialization with a generated boundary
  7911. {
  7912. MultipartFormDataWriter writer;
  7913. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7914. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7915. writer.content_type());
  7916. auto body = writer.serialize(items);
  7917. EXPECT_EQ(body.size(), writer.content_length(items));
  7918. auto res = cli.Post("/post", body, writer.content_type());
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. }
  7922. // Per-part framing with a custom boundary via a content provider
  7923. {
  7924. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7925. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7926. MultipartFormDataWriter writer("custom-boundary_123");
  7927. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7928. std::string body;
  7929. for (const auto &item : items) {
  7930. body += writer.item_begin(item);
  7931. body += item.content;
  7932. body += MultipartFormDataWriter::item_end();
  7933. }
  7934. body += writer.finish();
  7935. EXPECT_EQ(body.size(), writer.content_length(items));
  7936. auto res = cli.Post(
  7937. "/post", body.size(),
  7938. [&](size_t offset, size_t length, DataSink &sink) {
  7939. sink.write(body.data() + offset, length);
  7940. return true;
  7941. },
  7942. writer.content_type());
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(StatusCode::OK_200, res->status);
  7945. }
  7946. }
  7947. TEST_F(ServerTest, PostContentReceiverGzip) {
  7948. cli_.set_compress(true);
  7949. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. ASSERT_EQ(StatusCode::OK_200, res->status);
  7952. ASSERT_EQ("content", res->body);
  7953. }
  7954. TEST_F(ServerTest, PutContentReceiver) {
  7955. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. ASSERT_EQ(StatusCode::OK_200, res->status);
  7958. ASSERT_EQ("content", res->body);
  7959. }
  7960. TEST_F(ServerTest, PatchContentReceiver) {
  7961. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. ASSERT_EQ(StatusCode::OK_200, res->status);
  7964. ASSERT_EQ("content", res->body);
  7965. }
  7966. template <typename ClientType>
  7967. void TestWithHeadersAndContentReceiver(
  7968. ClientType &cli,
  7969. std::function<Result(ClientType &, const std::string &, const Headers &,
  7970. const std::string &, const std::string &,
  7971. ContentReceiver, DownloadProgress)>
  7972. request_func) {
  7973. Headers headers;
  7974. headers.emplace("X-Custom-Header", "test-value");
  7975. std::string received_body;
  7976. auto res = request_func(
  7977. cli, "/content_receiver", headers, "content", "application/json",
  7978. [&](const char *data, size_t data_length) {
  7979. received_body.append(data, data_length);
  7980. return true;
  7981. },
  7982. nullptr);
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("content", received_body);
  7986. }
  7987. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7988. #ifdef CPPHTTPLIB_SSL_ENABLED
  7989. using ClientT = SSLClient;
  7990. #else
  7991. using ClientT = Client;
  7992. #endif
  7993. TestWithHeadersAndContentReceiver<ClientT>(
  7994. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7995. const std::string &body, const std::string &content_type,
  7996. ContentReceiver receiver, DownloadProgress progress) {
  7997. return cli.Post(path, headers, body, content_type, receiver, progress);
  7998. });
  7999. }
  8000. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Put(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. template <typename ClientType>
  8027. void TestWithHeadersAndContentReceiverWithProgress(
  8028. ClientType &cli,
  8029. std::function<Result(ClientType &, const std::string &, const Headers &,
  8030. const std::string &, const std::string &,
  8031. ContentReceiver, DownloadProgress)>
  8032. request_func) {
  8033. Headers headers;
  8034. headers.emplace("X-Test-Header", "progress-test");
  8035. std::string received_body;
  8036. auto progress_called = false;
  8037. auto res = request_func(
  8038. cli, "/content_receiver", headers, "content", "text/plain",
  8039. [&](const char *data, size_t data_length) {
  8040. received_body.append(data, data_length);
  8041. return true;
  8042. },
  8043. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8044. progress_called = true;
  8045. return true;
  8046. });
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_EQ("content", received_body);
  8050. EXPECT_TRUE(progress_called);
  8051. }
  8052. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver, DownloadProgress progress) {
  8062. return cli.Post(path, headers, body, content_type, receiver, progress);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Put(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. template <typename ClientType>
  8092. void TestWithHeadersAndContentReceiverError(
  8093. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8094. const Headers &, const std::string &,
  8095. const std::string &, ContentReceiver)>
  8096. request_func) {
  8097. Headers headers;
  8098. headers.emplace("X-Error-Test", "true");
  8099. std::string received_body;
  8100. auto receiver_failed = false;
  8101. auto res =
  8102. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8103. [&](const char *data, size_t data_length) {
  8104. received_body.append(data, data_length);
  8105. receiver_failed = true;
  8106. return false;
  8107. });
  8108. ASSERT_FALSE(res);
  8109. EXPECT_TRUE(receiver_failed);
  8110. }
  8111. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. using ClientT = SSLClient;
  8114. #else
  8115. using ClientT = Client;
  8116. #endif
  8117. TestWithHeadersAndContentReceiverError<ClientT>(
  8118. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8119. const std::string &body, const std::string &content_type,
  8120. ContentReceiver receiver) {
  8121. return cli.Post(path, headers, body, content_type, receiver);
  8122. });
  8123. }
  8124. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Put(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Patch(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PostQueryStringAndBody) {
  8151. auto res =
  8152. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. ASSERT_EQ(StatusCode::OK_200, res->status);
  8155. }
  8156. TEST_F(ServerTest, HTTP2Magic) {
  8157. Request req;
  8158. req.method = "PRI";
  8159. req.path = "*";
  8160. req.body = "SM";
  8161. auto res = std::make_shared<Response>();
  8162. auto error = Error::Success;
  8163. auto ret = cli_.send(req, *res, error);
  8164. ASSERT_TRUE(ret);
  8165. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8166. }
  8167. TEST_F(ServerTest, KeepAlive) {
  8168. auto res = cli_.Get("/hi");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8172. EXPECT_EQ("Hello World!", res->body);
  8173. res = cli_.Get("/hi");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8177. EXPECT_EQ("Hello World!", res->body);
  8178. res = cli_.Get("/hi");
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8182. EXPECT_EQ("Hello World!", res->body);
  8183. res = cli_.Get("/not-exist");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8186. res = cli_.Post("/empty", "", "text/plain");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("empty", res->body);
  8191. EXPECT_EQ("close", res->get_header_value("Connection"));
  8192. res = cli_.Post(
  8193. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8194. "text/plain");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8198. EXPECT_EQ("empty", res->body);
  8199. cli_.set_keep_alive(false);
  8200. res = cli_.Get("/last-request");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::OK_200, res->status);
  8203. EXPECT_EQ("close", res->get_header_value("Connection"));
  8204. }
  8205. TEST_F(ServerTest, TooManyRedirect) {
  8206. cli_.set_follow_location(true);
  8207. auto res = cli_.Get("/redirect/0");
  8208. ASSERT_TRUE(!res);
  8209. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8210. }
  8211. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8212. Request req;
  8213. req.method = "FOOBAR";
  8214. req.path = "/hi";
  8215. cli_.set_keep_alive(true);
  8216. auto res = cli_.send(req);
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8219. EXPECT_EQ("close", res->get_header_value("Connection"));
  8220. EXPECT_FALSE(cli_.is_socket_open());
  8221. }
  8222. TEST_F(ServerTest, CustomRouteReadsBody) {
  8223. const std::string xml =
  8224. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8225. Request req;
  8226. req.method = "PROPFIND";
  8227. req.path = "/dav/dir";
  8228. req.set_header("Depth", "1");
  8229. req.body = xml;
  8230. auto res = cli_.send(req);
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8233. EXPECT_EQ(xml, res->body);
  8234. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8235. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8236. }
  8237. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/42";
  8241. auto res = cli_.send(req);
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8244. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8245. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8246. }
  8247. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8248. Request req;
  8249. req.method = "PROPFIND";
  8250. req.path = "/dav-re/123";
  8251. auto res = cli_.send(req);
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8254. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8255. }
  8256. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8257. Request req;
  8258. req.method = "MKCOL";
  8259. req.path = "/dav-mkcol";
  8260. auto res = cli_.send(req);
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_EQ(StatusCode::Created_201, res->status);
  8263. }
  8264. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8265. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8266. Request req;
  8267. req.method = "REPORT";
  8268. req.path = "/dav-report";
  8269. req.body = xml;
  8270. auto res = cli_.send(req);
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8273. EXPECT_EQ(xml, res->body);
  8274. }
  8275. // A content reader route must fire even when the request carries no body,
  8276. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8277. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8278. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. auto res = cli_.send(req);
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8285. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8286. }
  8287. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8288. Request req;
  8289. req.method = "PROPFIND";
  8290. req.path = "/not-dav";
  8291. auto res = cli_.send(req);
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8294. }
  8295. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8296. Request req;
  8297. req.method = "UNLOCK";
  8298. req.path = "/dav/dir";
  8299. cli_.set_keep_alive(true);
  8300. auto res = cli_.send(req);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8303. EXPECT_EQ("close", res->get_header_value("Connection"));
  8304. EXPECT_FALSE(cli_.is_socket_open());
  8305. }
  8306. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8307. // The mount point serves this path, but only for GET and HEAD.
  8308. auto get_res = cli_.Get("/dir/index.html");
  8309. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8310. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8311. Request req;
  8312. req.method = "PROPFIND";
  8313. req.path = "/dir/index.html";
  8314. auto res = cli_.send(req);
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8317. }
  8318. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8319. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8320. cli_.set_keep_alive(true);
  8321. for (auto i = 0; i < 2; i++) {
  8322. Request req;
  8323. req.method = "PROPFIND";
  8324. req.path = "/dav/dir";
  8325. req.body = xml;
  8326. auto res = cli_.send(req);
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8329. EXPECT_EQ(xml, res->body);
  8330. EXPECT_TRUE(cli_.is_socket_open());
  8331. }
  8332. // A built-in method must still be served on the same connection.
  8333. cli_.set_keep_alive(false);
  8334. auto res = cli_.Get("/hi");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ("close", res->get_header_value("Connection"));
  8338. }
  8339. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8340. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8341. Request req;
  8342. req.method = "PROPFIND";
  8343. req.path = "/dav/dir";
  8344. req.set_header("Expect", "100-continue");
  8345. req.body = xml;
  8346. auto res = cli_.send(req);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8349. EXPECT_EQ(xml, res->body);
  8350. }
  8351. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8352. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8353. TEST_F(ServerTest, Gzip) {
  8354. Headers headers;
  8355. headers.emplace("Accept-Encoding", "gzip, deflate");
  8356. auto res = cli_.Get("/compress", headers);
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. res->body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress-with-charset", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("application/json; charset=utf-8",
  8373. res->get_header_value("Content-Type"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "");
  8382. auto res = cli_.Get("/compress", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8386. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithContentReceiver) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "gzip, deflate");
  8395. std::string body;
  8396. auto res =
  8397. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8398. EXPECT_EQ(100U, data_length);
  8399. body.append(data, data_length);
  8400. return true;
  8401. });
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8404. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8405. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8406. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8407. "7890123456789012345678901234567890",
  8408. body);
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "gzip, deflate");
  8414. cli_.set_decompress(false);
  8415. auto res = cli_.Get("/compress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ(33U, res->body.size());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. }
  8423. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8424. Headers headers;
  8425. headers.emplace("Accept-Encoding", "");
  8426. std::string body;
  8427. auto res =
  8428. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8429. EXPECT_EQ(100U, data_length);
  8430. body.append(data, data_length);
  8431. return true;
  8432. });
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8436. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8437. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8438. "7890123456789012345678901234567890",
  8439. body);
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. }
  8442. TEST_F(ServerTest, NoGzip) {
  8443. Headers headers;
  8444. headers.emplace("Accept-Encoding", "gzip, deflate");
  8445. auto res = cli_.Get("/nocompress", headers);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8448. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. res->body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. std::string body;
  8459. auto res = cli_.Get("/nocompress", headers,
  8460. [&](const char *data, size_t data_length) {
  8461. EXPECT_EQ(100U, data_length);
  8462. body.append(data, data_length);
  8463. return true;
  8464. });
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8467. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8468. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8469. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8470. "7890123456789012345678901234567890",
  8471. body);
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. }
  8474. TEST_F(ServerTest, MultipartFormDataGzip) {
  8475. UploadFormDataItems items = {
  8476. {"key1", "test", "", ""},
  8477. {"key2", "--abcdefg123", "", ""},
  8478. };
  8479. cli_.set_compress(true);
  8480. auto res = cli_.Post("/compress-multipart", items);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. #endif
  8485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8486. // Static file compression is opt-in, so these run their own server rather than
  8487. // flipping it on for the shared ServerTest fixture, which would silently
  8488. // rewrite what every other static file test is asserting.
  8489. class StaticFileCompressionTest : public ::testing::Test {
  8490. protected:
  8491. void TearDown() override {
  8492. if (t_.joinable()) {
  8493. svr_.stop();
  8494. t_.join();
  8495. }
  8496. }
  8497. int start(const std::function<void(Server &)> &configure = nullptr) {
  8498. // Serves the same tree as a directory of build-time compressed assets
  8499. // would be served: the mount point names the coding the files are already
  8500. // stored in. Registered before "/" so it is the one that matches.
  8501. svr_.set_mount_point("/pre-encoded", "./www",
  8502. {{"Content-Encoding", "gzip"}});
  8503. svr_.set_mount_point("/", "./www");
  8504. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8505. res.set_file_content("./www/dir/index.html", "text/html");
  8506. });
  8507. svr_.Get("/pre-encoded-file-content",
  8508. [](const Request & /*req*/, Response &res) {
  8509. res.set_header("Content-Encoding", "gzip");
  8510. res.set_file_content("./www/dir/index.html", "text/html");
  8511. });
  8512. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8513. res.set_content_provider(
  8514. 6, "text/plain",
  8515. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8516. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8517. return true;
  8518. });
  8519. });
  8520. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8521. res.set_content_provider(
  8522. 1000, "text/plain",
  8523. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8524. if (offset < 100) {
  8525. std::string data(100, 'A');
  8526. sink.write(data.data(), data.size());
  8527. return true;
  8528. }
  8529. std::this_thread::sleep_for(std::chrono::seconds(2));
  8530. std::string data(900, 'B');
  8531. sink.write(data.data(), data.size());
  8532. return true;
  8533. });
  8534. });
  8535. if (configure) { configure(svr_); }
  8536. auto port = svr_.bind_to_any_port(HOST);
  8537. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8538. svr_.wait_until_ready();
  8539. return port;
  8540. }
  8541. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8542. // Every file under ./www except 1MB.txt is smaller than the default
  8543. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8544. // it out of the way.
  8545. static void enable_without_floor(Server &svr) {
  8546. svr.set_static_file_compression(true);
  8547. svr.set_static_file_compression_min_length(0);
  8548. }
  8549. Server svr_;
  8550. std::thread t_;
  8551. };
  8552. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8553. auto port = start();
  8554. Client cli(HOST, port);
  8555. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8557. EXPECT_EQ(StatusCode::OK_200, res->status);
  8558. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8559. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8560. EXPECT_EQ(1048576U, res->body.size());
  8561. }
  8562. TEST_F(StaticFileCompressionTest, MountPoint) {
  8563. auto port = start(enable);
  8564. Client cli(HOST, port);
  8565. cli.set_decompress(false);
  8566. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8570. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8571. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8572. // The response stays self-delimiting: a length, not a chunked body.
  8573. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8574. EXPECT_EQ(std::to_string(res->body.size()),
  8575. res->get_header_value("Content-Length"));
  8576. EXPECT_LT(res->body.size(), 1048576U);
  8577. EXPECT_FALSE(res->body.empty());
  8578. }
  8579. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8580. auto port = start(enable);
  8581. Client cli(HOST, port);
  8582. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8586. EXPECT_EQ(1048576U, res->body.size());
  8587. }
  8588. TEST_F(StaticFileCompressionTest, FileContent) {
  8589. auto port = start(enable_without_floor);
  8590. Client cli(HOST, port);
  8591. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8595. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8596. EXPECT_EQ(104U, res->body.size());
  8597. }
  8598. // A handler that serves an already-encoded file names the coding itself. The
  8599. // file-backed path decided its coding from Accept-Encoding and the content
  8600. // type alone, so it compressed the stored bytes a second time and appended a
  8601. // second Content-Encoding field line.
  8602. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8603. auto port = start(enable_without_floor);
  8604. Client cli(HOST, port);
  8605. cli.set_decompress(false);
  8606. auto res = cli.Get("/pre-encoded-file-content",
  8607. Headers{{"Accept-Encoding", "gzip"}});
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. // Vary belongs to a coding the server chose, and it chose none here.
  8613. EXPECT_FALSE(res->has_header("Vary"));
  8614. // The file travels exactly as it is stored on disk.
  8615. EXPECT_EQ(104U, res->body.size());
  8616. }
  8617. // The 1MB file clears the default floor, so this one runs the configuration a
  8618. // deployment would actually have.
  8619. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8620. auto port = start(enable);
  8621. Client cli(HOST, port);
  8622. cli.set_decompress(false);
  8623. auto res =
  8624. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8628. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8629. EXPECT_FALSE(res->has_header("Vary"));
  8630. EXPECT_EQ(1048576U, res->body.size());
  8631. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8632. }
  8633. TEST_F(StaticFileCompressionTest, Head) {
  8634. auto port = start(enable);
  8635. Client cli(HOST, port);
  8636. cli.set_decompress(false);
  8637. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8639. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8643. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8644. // HEAD still reports the size a GET would return.
  8645. EXPECT_EQ(get->get_header_value("Content-Length"),
  8646. res->get_header_value("Content-Length"));
  8647. EXPECT_TRUE(res->body.empty());
  8648. }
  8649. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8650. auto port = start(enable);
  8651. Client cli(HOST, port);
  8652. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8653. {"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8656. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8657. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8658. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8659. EXPECT_EQ("cd", res->body);
  8660. }
  8661. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8662. auto port = start(enable);
  8663. Client cli(HOST, port);
  8664. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8668. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8669. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8670. }
  8671. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8672. auto port = start(enable);
  8673. Client cli(HOST, port);
  8674. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_EQ(StatusCode::OK_200, res->status);
  8677. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8678. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8679. EXPECT_TRUE(res->body.empty());
  8680. }
  8681. TEST_F(StaticFileCompressionTest, MinLength) {
  8682. auto port = start(enable);
  8683. Client cli(HOST, port);
  8684. // 104 bytes, well under the default floor. Compressing it would add the
  8685. // gzip header and trailer to a body that already fits in one packet.
  8686. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8688. EXPECT_EQ(StatusCode::OK_200, res->status);
  8689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8690. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8691. }
  8692. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8693. auto port = start([](Server &svr) {
  8694. svr.set_static_file_compression(true);
  8695. svr.set_static_file_compression_min_length(1);
  8696. });
  8697. Client cli(HOST, port);
  8698. cli.set_decompress(false);
  8699. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8702. // A 9-byte file comes back larger than it went in, because gzip's header and
  8703. // trailer outweigh anything deflate can save. That is the end of the range
  8704. // the floor exists to keep out.
  8705. EXPECT_GT(res->body.size(), 9U);
  8706. }
  8707. TEST_F(StaticFileCompressionTest, MaxLength) {
  8708. auto port = start([](Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(0);
  8711. svr.set_static_file_compression_max_length(1024);
  8712. });
  8713. Client cli(HOST, port);
  8714. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8715. // defines `small` as a macro on Windows.
  8716. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8717. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8718. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8719. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8720. // Under it: compressed.
  8721. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8722. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8723. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8724. }
  8725. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8726. auto port = start(enable_without_floor);
  8727. Client cli(HOST, port);
  8728. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8729. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8730. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8731. auto identity_etag = identity->get_header_value("ETag");
  8732. ASSERT_FALSE(identity_etag.empty());
  8733. auto gzipped =
  8734. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8736. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8737. auto gzip_etag = gzipped->get_header_value("ETag");
  8738. ASSERT_FALSE(gzip_etag.empty());
  8739. // Two representations, two validators.
  8740. EXPECT_NE(identity_etag, gzip_etag);
  8741. // Each one revalidates against the request that would produce it...
  8742. auto fresh =
  8743. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8744. {"If-None-Match", gzip_etag}});
  8745. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8746. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8747. auto fresh_identity =
  8748. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8749. {"If-None-Match", identity_etag}});
  8750. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8751. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8752. // ...and not against the other representation.
  8753. auto crossed =
  8754. cli.Get("/dir/index.html",
  8755. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8756. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8757. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8758. }
  8759. // The opt-in covers responses the server reads off disk itself. A caller's own
  8760. // known-length provider keeps its Content-Length and, more importantly, keeps
  8761. // delivering incrementally: routing it through a compressor would hold every
  8762. // write back until zlib's window filled.
  8763. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8764. auto port = start(enable);
  8765. Client cli(HOST, port);
  8766. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8768. EXPECT_EQ(StatusCode::OK_200, res->status);
  8769. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8770. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8771. EXPECT_EQ("aaabbb", res->body);
  8772. }
  8773. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8774. auto port = start(enable);
  8775. Client cli(HOST, port);
  8776. cli.set_read_timeout(1, 0);
  8777. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8778. Headers{{"Accept-Encoding", "gzip"}});
  8779. ASSERT_TRUE(handle.is_valid());
  8780. // The provider writes 100 bytes and then stalls for longer than the read
  8781. // timeout. Those first bytes have to arrive anyway: run the response through
  8782. // a compressor and zlib holds them until its window fills, so the read would
  8783. // come back empty instead.
  8784. char buf[256];
  8785. auto n = handle.read(buf, sizeof(buf));
  8786. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8787. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8788. }
  8789. #endif
  8790. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8791. TEST_F(ServerTest, Brotli) {
  8792. Headers headers;
  8793. headers.emplace("Accept-Encoding", "br");
  8794. auto res = cli_.Get("/compress", headers);
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8798. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8799. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8800. "7890123456789012345678901234567890",
  8801. res->body);
  8802. EXPECT_EQ(StatusCode::OK_200, res->status);
  8803. }
  8804. #endif
  8805. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8806. TEST_F(ServerTest, Zstd) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "zstd");
  8809. auto res = cli_.Get("/compress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8814. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8815. "7890123456789012345678901234567890",
  8816. res->body);
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "zstd");
  8835. std::string body;
  8836. auto res =
  8837. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8838. EXPECT_EQ(100U, data_length);
  8839. body.append(data, data_length);
  8840. return true;
  8841. });
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8845. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8846. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8847. "7890123456789012345678901234567890",
  8848. body);
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8852. Headers headers;
  8853. headers.emplace("Accept-Encoding", "zstd");
  8854. cli_.set_decompress(false);
  8855. auto res = cli_.Get("/compress", headers);
  8856. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8857. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8858. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8859. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ(StatusCode::OK_200, res->status);
  8865. ASSERT_EQ(26U, res->body.size());
  8866. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8867. 0);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, NoZstd) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. auto res = cli_.Get("/nocompress", headers);
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8894. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. res->body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. std::string body;
  8905. auto res = cli_.Get("/nocompress", headers,
  8906. [&](const char *data, size_t data_length) {
  8907. EXPECT_EQ(100U, data_length);
  8908. body.append(data, data_length);
  8909. return true;
  8910. });
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8913. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8916. "7890123456789012345678901234567890",
  8917. body);
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. }
  8920. // TODO: How to enable zstd ??
  8921. TEST_F(ServerTest, MultipartFormDataZstd) {
  8922. UploadFormDataItems items = {
  8923. {"key1", "test", "", ""},
  8924. {"key2", "--abcdefg123", "", ""},
  8925. };
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. cli_.set_compress(true);
  8929. auto res = cli_.Post("/compress-multipart", headers, items);
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8934. Headers headers;
  8935. headers.emplace("Accept-Encoding", "zstd");
  8936. cli_.set_compress(true);
  8937. auto res = cli_.Put(
  8938. "/put", headers, 3,
  8939. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8940. sink.os << "PUT";
  8941. return true;
  8942. },
  8943. "text/plain");
  8944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8945. EXPECT_EQ(StatusCode::OK_200, res->status);
  8946. EXPECT_EQ("PUT", res->body);
  8947. }
  8948. // Pre-compression logging tests
  8949. TEST_F(ServerTest, PreCompressionLogging) {
  8950. // Test data for compression (matches the actual /compress endpoint content)
  8951. const std::string test_content =
  8952. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8953. "3456789012345678901234567890";
  8954. // Variables to capture logging data
  8955. std::string pre_compression_body;
  8956. std::string pre_compression_content_type;
  8957. std::string pre_compression_content_encoding;
  8958. std::string post_compression_body;
  8959. std::string post_compression_content_type;
  8960. std::string post_compression_content_encoding;
  8961. // Set up pre-compression logger
  8962. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8963. const Response &res) {
  8964. pre_compression_body = res.body;
  8965. pre_compression_content_type = res.get_header_value("Content-Type");
  8966. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8967. });
  8968. // Set up post-compression logger
  8969. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8970. post_compression_body = res.body;
  8971. post_compression_content_type = res.get_header_value("Content-Type");
  8972. post_compression_content_encoding =
  8973. res.get_header_value("Content-Encoding");
  8974. });
  8975. // Test with gzip compression
  8976. Headers headers;
  8977. headers.emplace("Accept-Encoding", "gzip");
  8978. auto res = cli_.Get("/compress", headers);
  8979. // Verify response was compressed
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8983. // Verify pre-compression logger captured uncompressed content
  8984. EXPECT_EQ(test_content, pre_compression_body);
  8985. EXPECT_EQ("text/plain", pre_compression_content_type);
  8986. EXPECT_TRUE(pre_compression_content_encoding
  8987. .empty()); // No encoding header before compression
  8988. // Verify post-compression logger captured compressed content
  8989. EXPECT_NE(test_content,
  8990. post_compression_body); // Should be different after compression
  8991. EXPECT_EQ("text/plain", post_compression_content_type);
  8992. EXPECT_EQ("gzip", post_compression_content_encoding);
  8993. // Verify compressed content is smaller
  8994. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8995. }
  8996. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8997. const std::string test_content =
  8998. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8999. "3456789012345678901234567890";
  9000. std::string pre_compression_body;
  9001. std::string post_compression_body;
  9002. svr_.set_pre_compression_logger(
  9003. [&](const Request & /*req*/, const Response &res) {
  9004. pre_compression_body = res.body;
  9005. });
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. });
  9009. Headers headers;
  9010. headers.emplace("Accept-Encoding", "br");
  9011. auto res = cli_.Get("/compress", headers);
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ(StatusCode::OK_200, res->status);
  9014. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9015. // Verify pre-compression content is uncompressed
  9016. EXPECT_EQ(test_content, pre_compression_body);
  9017. // Verify post-compression content is compressed
  9018. EXPECT_NE(test_content, post_compression_body);
  9019. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9020. }
  9021. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9022. const std::string test_content =
  9023. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9024. "3456789012345678901234567890";
  9025. std::string pre_compression_body;
  9026. std::string post_compression_body;
  9027. svr_.set_pre_compression_logger(
  9028. [&](const Request & /*req*/, const Response &res) {
  9029. pre_compression_body = res.body;
  9030. });
  9031. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9032. post_compression_body = res.body;
  9033. });
  9034. // Request without compression (use /nocompress endpoint)
  9035. Headers headers;
  9036. auto res = cli_.Get("/nocompress", headers);
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::OK_200, res->status);
  9039. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9040. // Pre-compression logger should not be called when no compression is applied
  9041. EXPECT_TRUE(
  9042. pre_compression_body.empty()); // Pre-compression logger not called
  9043. EXPECT_EQ(
  9044. test_content,
  9045. post_compression_body); // Post-compression logger captures final content
  9046. }
  9047. TEST_F(ServerTest, LoggerSeesContentLength) {
  9048. size_t logged_content_length = 0;
  9049. std::string logged_content_length_header;
  9050. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9051. logged_content_length = res.content_length_;
  9052. logged_content_length_header = res.get_header_value("Content-Length");
  9053. });
  9054. auto res = cli_.Get("/nocompress");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. EXPECT_EQ(res->body.size(), logged_content_length);
  9058. EXPECT_EQ(std::to_string(logged_content_length),
  9059. logged_content_length_header);
  9060. }
  9061. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9062. const std::string test_content =
  9063. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9064. "3456789012345678901234567890";
  9065. std::string pre_compression_body;
  9066. bool pre_logger_called = false;
  9067. // Set only pre-compression logger
  9068. svr_.set_pre_compression_logger(
  9069. [&](const Request & /*req*/, const Response &res) {
  9070. pre_compression_body = res.body;
  9071. pre_logger_called = true;
  9072. });
  9073. Headers headers;
  9074. headers.emplace("Accept-Encoding", "gzip");
  9075. auto res = cli_.Get("/compress", headers);
  9076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9077. EXPECT_EQ(StatusCode::OK_200, res->status);
  9078. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9079. // Verify pre-compression logger was called
  9080. EXPECT_TRUE(pre_logger_called);
  9081. EXPECT_EQ(test_content, pre_compression_body);
  9082. }
  9083. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9084. {
  9085. // Test with Expect: 100-continue header - success case
  9086. // Server returns 100 Continue, client sends body, server returns 200 OK
  9087. Request req;
  9088. req.method = "POST";
  9089. req.path = "/post-large";
  9090. req.set_header("Expect", "100-continue");
  9091. req.body = LARGE_DATA;
  9092. Response res;
  9093. auto error = Error::Success;
  9094. cli_.set_keep_alive(true);
  9095. auto ret = cli_.send(req, res, error);
  9096. EXPECT_TRUE(ret);
  9097. EXPECT_EQ(StatusCode::OK_200, res.status);
  9098. EXPECT_EQ(LARGE_DATA, res.body);
  9099. }
  9100. {
  9101. // Test with Expect: 100-continue header - error case
  9102. // Client should not send the body when server returns an error
  9103. Request req;
  9104. req.method = "POST";
  9105. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9106. req.set_header("Expect", "100-continue");
  9107. req.body = LARGE_DATA;
  9108. Response res;
  9109. auto error = Error::Success;
  9110. auto start = std::chrono::high_resolution_clock::now();
  9111. cli_.set_keep_alive(true);
  9112. auto ret = cli_.send(req, res, error);
  9113. auto end = std::chrono::high_resolution_clock::now();
  9114. auto elapsed =
  9115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9116. .count();
  9117. // With Expect: 100-continue, request completes successfully but with error
  9118. EXPECT_TRUE(ret);
  9119. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9120. EXPECT_EQ("close", res.get_header_value("Connection"));
  9121. EXPECT_FALSE(cli_.is_socket_open());
  9122. EXPECT_LE(elapsed, 2000);
  9123. }
  9124. {
  9125. // Send an extra GET request to ensure error recovery without hanging
  9126. Request req;
  9127. req.method = "GET";
  9128. req.path = "/hi";
  9129. auto start = std::chrono::high_resolution_clock::now();
  9130. auto res = cli_.send(req);
  9131. auto end = std::chrono::high_resolution_clock::now();
  9132. auto elapsed =
  9133. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9134. .count();
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. EXPECT_EQ("Hello World!", res->body);
  9138. EXPECT_LE(elapsed, 500);
  9139. }
  9140. }
  9141. TEST(ZstdDecompressor, ChunkedDecompression) {
  9142. std::string data;
  9143. for (size_t i = 0; i < 32 * 1024; ++i) {
  9144. data.push_back(static_cast<char>('a' + i % 26));
  9145. }
  9146. std::string compressed_data;
  9147. {
  9148. httplib::detail::zstd_compressor compressor;
  9149. bool result = compressor.compress(
  9150. data.data(), data.size(),
  9151. /*last=*/true,
  9152. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9153. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9154. compressed_data_size);
  9155. return true;
  9156. });
  9157. ASSERT_TRUE(result);
  9158. }
  9159. std::string decompressed_data;
  9160. {
  9161. httplib::detail::zstd_decompressor decompressor;
  9162. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9163. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9164. size_t chunk_size = 130;
  9165. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9166. chunk_begin += chunk_size) {
  9167. size_t current_chunk_size =
  9168. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9169. bool result = decompressor.decompress(
  9170. compressed_data.data() + chunk_begin, current_chunk_size,
  9171. [&](const char *decompressed_data_chunk,
  9172. size_t decompressed_data_chunk_size) {
  9173. decompressed_data.insert(decompressed_data.size(),
  9174. decompressed_data_chunk,
  9175. decompressed_data_chunk_size);
  9176. return true;
  9177. });
  9178. ASSERT_TRUE(result);
  9179. }
  9180. }
  9181. ASSERT_EQ(data, decompressed_data);
  9182. }
  9183. TEST(ZstdDecompressor, Decompress) {
  9184. std::string original_text = "Compressed with ZSTD";
  9185. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9186. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9187. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9188. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9189. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9190. std::string decompressed_data;
  9191. {
  9192. httplib::detail::zstd_decompressor decompressor;
  9193. bool result = decompressor.decompress(
  9194. compressed_data.data(), compressed_data.size(),
  9195. [&](const char *decompressed_data_chunk,
  9196. size_t decompressed_data_chunk_size) {
  9197. decompressed_data.insert(decompressed_data.size(),
  9198. decompressed_data_chunk,
  9199. decompressed_data_chunk_size);
  9200. return true;
  9201. });
  9202. ASSERT_TRUE(result);
  9203. }
  9204. ASSERT_EQ(original_text, decompressed_data);
  9205. }
  9206. #endif
  9207. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9208. // separate chunks so that the server sees each part in its own read(). Used to
  9209. // place a read boundary at a specific offset of a request body.
  9210. static bool send_request_in_parts(time_t read_timeout_sec,
  9211. const std::vector<std::string> &parts,
  9212. std::string *resp = nullptr,
  9213. int port = PORT) {
  9214. auto error = Error::Success;
  9215. auto client_sock = detail::create_client_socket(
  9216. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9217. /*connection_timeout_sec=*/5, 0,
  9218. /*read_timeout_sec=*/5, 0,
  9219. /*write_timeout_sec=*/5, 0, std::string(), error);
  9220. if (client_sock == INVALID_SOCKET) { return false; }
  9221. auto ret = detail::process_client_socket(
  9222. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9223. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9224. for (size_t i = 0; i < parts.size(); i++) {
  9225. const auto &part = parts[i];
  9226. if (part.size() !=
  9227. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9228. return false;
  9229. }
  9230. if (i + 1 < parts.size()) {
  9231. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9232. }
  9233. }
  9234. char buf[512];
  9235. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9236. while (line_reader.getline()) {
  9237. if (resp) { *resp += line_reader.ptr(); }
  9238. }
  9239. return true;
  9240. });
  9241. detail::close_socket(client_sock);
  9242. return ret;
  9243. }
  9244. // Sends a raw request to a server listening at HOST:PORT.
  9245. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9246. std::string *resp = nullptr, int port = PORT) {
  9247. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9248. }
  9249. #ifdef CPPHTTPLIB_SSL_ENABLED
  9250. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9252. ASSERT_TRUE(svr.is_valid());
  9253. svr.set_read_timeout(1, 0);
  9254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9262. // keeps each wait well within the read timeout. The server gives up a
  9263. // second in, so the bytes sent after that fail.
  9264. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9265. parts.resize(26, std::string(1, '\0'));
  9266. EXPECT_FALSE(send_request_in_parts(5, parts));
  9267. }
  9268. #endif
  9269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9270. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9271. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9272. const std::vector<std::string> &parts,
  9273. std::string *resp = nullptr,
  9274. int port = PORT) {
  9275. auto error = Error::Success;
  9276. auto sock = detail::create_client_socket(
  9277. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9278. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9279. /*write_timeout_sec=*/5, 0, std::string(), error);
  9280. if (sock == INVALID_SOCKET) { return false; }
  9281. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9282. auto ctx = SSL_CTX_new(TLS_client_method());
  9283. auto ssl = SSL_new(ctx);
  9284. auto ssl_se = detail::scope_exit([&] {
  9285. SSL_free(ssl);
  9286. SSL_CTX_free(ctx);
  9287. });
  9288. SSL_set_fd(ssl, static_cast<int>(sock));
  9289. if (SSL_connect(ssl) != 1) { return false; }
  9290. for (size_t i = 0; i < parts.size(); i++) {
  9291. const auto &part = parts[i];
  9292. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9293. static_cast<int>(part.size())) {
  9294. return false;
  9295. }
  9296. if (i + 1 < parts.size()) {
  9297. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9298. }
  9299. }
  9300. char buf[512];
  9301. int n;
  9302. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9303. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9304. }
  9305. return true;
  9306. }
  9307. #endif
  9308. // The request line, then a header value a byte at a time.
  9309. static std::vector<std::string> slow_request_head_parts() {
  9310. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9311. parts.resize(26, "a");
  9312. parts.emplace_back("\r\n\r\n");
  9313. return parts;
  9314. }
  9315. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9316. // within the one-second read timeout. The server gives up a second in, before
  9317. // the head is complete.
  9318. static void
  9319. expect_slow_request_head_dropped(Server &svr,
  9320. const std::function<std::string()> &send) {
  9321. std::atomic<bool> handled(false);
  9322. svr.Get("/", [&](const Request &, Response &res) {
  9323. handled = true;
  9324. res.set_content("ok", "text/plain");
  9325. });
  9326. svr.set_read_timeout(1, 0);
  9327. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9328. auto se = detail::scope_exit([&] {
  9329. svr.stop();
  9330. t.join();
  9331. ASSERT_FALSE(svr.is_running());
  9332. });
  9333. svr.wait_until_ready();
  9334. auto resp = send();
  9335. EXPECT_FALSE(handled);
  9336. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9337. }
  9338. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9339. Server svr;
  9340. expect_slow_request_head_dropped(svr, [] {
  9341. std::string resp;
  9342. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9343. return resp;
  9344. });
  9345. }
  9346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9347. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9349. ASSERT_TRUE(svr.is_valid());
  9350. expect_slow_request_head_dropped(svr, [] {
  9351. std::string resp;
  9352. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9353. return resp;
  9354. });
  9355. }
  9356. #endif
  9357. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9358. Server svr;
  9359. std::string header_value;
  9360. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9361. header_value = req.get_header_value("foo");
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. thread t = thread([&] { svr.listen(HOST, PORT); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9372. // like characters are not treated the same - use vertical tab and escape.
  9373. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9374. "foo: \t \v bar \x1B\t \r\n"
  9375. "Connection: close\r\n"
  9376. "\r\n";
  9377. std::string res;
  9378. ASSERT_TRUE(send_request(5, req, &res));
  9379. EXPECT_EQ(header_value, "");
  9380. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9381. }
  9382. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9383. Server svr;
  9384. std::string received;
  9385. svr.Get("/order", [&](const Request &req, Response &res) {
  9386. received = entries_to_string(req.headers);
  9387. res.set_content("ok", "text/plain");
  9388. });
  9389. auto port = svr.bind_to_any_port(HOST);
  9390. thread t = thread([&] { svr.listen_after_bind(); });
  9391. auto se = detail::scope_exit([&] {
  9392. svr.stop();
  9393. t.join();
  9394. ASSERT_FALSE(svr.is_running());
  9395. });
  9396. svr.wait_until_ready();
  9397. const std::string req = "GET /order HTTP/1.1\r\n"
  9398. "Host: localhost\r\n"
  9399. "X-First: 1\r\n"
  9400. "X-Dup: a\r\n"
  9401. "X-Second: 2\r\n"
  9402. "X-Dup: b\r\n"
  9403. "Connection: close\r\n"
  9404. "\r\n";
  9405. std::string res;
  9406. ASSERT_TRUE(send_request(5, req, &res, port));
  9407. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9408. EXPECT_EQ(
  9409. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9410. received);
  9411. }
  9412. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9413. Server svr;
  9414. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9415. res.set_header("Set-Cookie", "first=1");
  9416. res.set_header("X-Between", "y");
  9417. res.set_header("Set-Cookie", "second=2");
  9418. res.set_content("ok", "text/plain");
  9419. });
  9420. auto port = svr.bind_to_any_port(HOST);
  9421. thread t = thread([&] { svr.listen_after_bind(); });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. t.join();
  9425. ASSERT_FALSE(svr.is_running());
  9426. });
  9427. svr.wait_until_ready();
  9428. Client cli(HOST, port);
  9429. auto res = cli.Get("/cookies");
  9430. ASSERT_TRUE(res);
  9431. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9432. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9433. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9434. }
  9435. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9436. Server svr;
  9437. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9438. auto i = new int(0);
  9439. res.set_header("Trailer", "X-Safe, X-Reflected");
  9440. res.set_chunked_content_provider(
  9441. "text/plain",
  9442. [i](size_t /*offset*/, DataSink &sink) {
  9443. if (*i == 0) {
  9444. sink.os << "body";
  9445. } else {
  9446. Headers trailer;
  9447. // A valid trailer that must survive.
  9448. trailer.emplace("X-Safe", "safe");
  9449. // Attacker-controlled value carrying CR/LF (response splitting).
  9450. trailer.emplace("X-Reflected",
  9451. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9452. // Attacker-controlled name carrying CR/LF.
  9453. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9454. sink.done_with_trailer(trailer);
  9455. }
  9456. (*i)++;
  9457. return true;
  9458. },
  9459. [i](bool /*success*/) { delete i; });
  9460. });
  9461. thread t = thread([&] { svr.listen(HOST, PORT); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9469. "Host: " + HOST +
  9470. "\r\n"
  9471. "Connection: close\r\n"
  9472. "\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res));
  9475. // The injected fields must not appear anywhere in the raw response.
  9476. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9477. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9478. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9479. // Invalid trailers are dropped entirely, matching set_header().
  9480. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9481. // The valid trailer still passes through.
  9482. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9483. }
  9484. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9485. Server svr;
  9486. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9487. // res.headers is a public field an application can populate directly,
  9488. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9489. // A valid header that must survive.
  9490. res.headers.emplace("X-Safe", "safe");
  9491. // Attacker-controlled value carrying CR/LF (response splitting).
  9492. res.headers.emplace("X-Reflected",
  9493. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9494. // Attacker-controlled name carrying CR/LF.
  9495. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9496. res.set_content("body", "text/plain");
  9497. });
  9498. thread t = thread([&] { svr.listen(HOST, PORT); });
  9499. auto se = detail::scope_exit([&] {
  9500. svr.stop();
  9501. t.join();
  9502. ASSERT_FALSE(svr.is_running());
  9503. });
  9504. svr.wait_until_ready();
  9505. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9506. "Host: " + HOST +
  9507. "\r\n"
  9508. "Connection: close\r\n"
  9509. "\r\n";
  9510. std::string res;
  9511. ASSERT_TRUE(send_request(5, req, &res));
  9512. // The injected fields must not appear anywhere in the raw response.
  9513. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9514. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9515. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9516. // Invalid headers are dropped entirely, matching set_header().
  9517. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9518. // The valid header still passes through.
  9519. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9520. }
  9521. // Forward declaration: in split builds split.py strips `inline` and moves the
  9522. // definition into httplib.cc, so detail::write_request_line is not visible from
  9523. // the public httplib.h. Re-declaring it here lets the tests link against the
  9524. // symbol in both header-only and split builds.
  9525. namespace httplib {
  9526. namespace detail {
  9527. ssize_t write_request_line(Stream &strm, const std::string &method,
  9528. const std::string &path);
  9529. } // namespace detail
  9530. } // namespace httplib
  9531. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9532. // A well-formed target is written verbatim.
  9533. {
  9534. detail::BufferStream strm;
  9535. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9536. EXPECT_GT(n, 0);
  9537. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9538. }
  9539. // A target carrying CR/LF, SP or other control octets must be rejected
  9540. // before anything reaches the wire, otherwise it splits the request line and
  9541. // injects a header or a whole request.
  9542. const std::string evil_targets[] = {
  9543. "/a\r\nInjected: pwned",
  9544. "/a\rInjected",
  9545. "/a\nInjected",
  9546. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9547. "/a b",
  9548. "/a\tb",
  9549. "/a\x7f",
  9550. };
  9551. for (const auto &evil : evil_targets) {
  9552. detail::BufferStream strm;
  9553. auto n = detail::write_request_line(strm, "GET", evil);
  9554. EXPECT_LT(n, 0);
  9555. EXPECT_TRUE(strm.get_buffer().empty());
  9556. }
  9557. }
  9558. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9559. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9560. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9561. // target reaches write_request. The client must fail cleanly with
  9562. // Error::Write instead of putting a request-line-less, header-injecting
  9563. // request on the wire.
  9564. Server svr;
  9565. svr.Get("/a", [](const Request &, Response &res) {
  9566. res.set_content("ok", "text/plain");
  9567. });
  9568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9569. auto se = detail::scope_exit([&] {
  9570. svr.stop();
  9571. thread.join();
  9572. ASSERT_FALSE(svr.is_running());
  9573. });
  9574. svr.wait_until_ready();
  9575. {
  9576. Client cli(HOST, PORT);
  9577. cli.set_path_encode(false);
  9578. // The request is rejected before anything is written, so the connection
  9579. // stays silent and the subsequent response read would otherwise block for
  9580. // the full default read timeout. Shorten it -- the assertion is on the
  9581. // error, not the timeout.
  9582. cli.set_read_timeout(1, 0);
  9583. auto res = cli.Get("/a\r\nInjected: pwned");
  9584. EXPECT_FALSE(res);
  9585. EXPECT_EQ(Error::Write, res.error());
  9586. }
  9587. }
  9588. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9589. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9590. // including extension methods.
  9591. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9592. for (const auto &method : good_methods) {
  9593. detail::BufferStream strm;
  9594. auto n = detail::write_request_line(strm, method, "/");
  9595. EXPECT_GT(n, 0);
  9596. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9597. }
  9598. // A method carrying CR/LF would split the request line and smuggle a whole
  9599. // request ahead of the real one. A space or an empty method corrupts the
  9600. // request line. All must be rejected before anything reaches the wire.
  9601. const std::string evil_methods[] = {
  9602. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9603. "GET\r\nInjected: pwned",
  9604. "GET\r",
  9605. "GET\n",
  9606. "GE T",
  9607. "",
  9608. };
  9609. for (const auto &evil : evil_methods) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, evil, "/");
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9617. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9618. // through Client::send must fail with Error::Write and no request, neither
  9619. // the smuggled one nor the real one, may reach the server.
  9620. Server svr;
  9621. std::atomic<int> request_count(0);
  9622. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9623. request_count++;
  9624. res.status = StatusCode::OK_200;
  9625. return Server::HandlerResponse::Handled;
  9626. });
  9627. auto port = svr.bind_to_any_port(HOST);
  9628. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9629. auto se = detail::scope_exit([&] {
  9630. svr.stop();
  9631. thread.join();
  9632. ASSERT_FALSE(svr.is_running());
  9633. });
  9634. svr.wait_until_ready();
  9635. {
  9636. Client cli(HOST, port);
  9637. const std::string evil_methods[] = {
  9638. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9639. "GE T",
  9640. "",
  9641. };
  9642. for (const auto &evil : evil_methods) {
  9643. Request req;
  9644. req.method = evil;
  9645. req.path = "/";
  9646. auto res = cli.send(req);
  9647. EXPECT_FALSE(res);
  9648. EXPECT_EQ(Error::Write, res.error());
  9649. }
  9650. auto handle =
  9651. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9652. EXPECT_FALSE(handle.is_valid());
  9653. EXPECT_EQ(Error::Write, handle.error);
  9654. // A valid request on the same client still goes through.
  9655. auto res = cli.Get("/");
  9656. ASSERT_TRUE(res);
  9657. EXPECT_EQ(StatusCode::OK_200, res->status);
  9658. }
  9659. EXPECT_EQ(1, request_count.load());
  9660. }
  9661. // Sends a raw request and verifies that there isn't a crash or exception.
  9662. static void test_raw_request(const std::string &req,
  9663. std::string *out = nullptr) {
  9664. Server svr;
  9665. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9669. res.set_content("ok", "text/plain");
  9670. });
  9671. svr.Get("/header_field_value_check",
  9672. [&](const Request & /*req*/, Response &res) {
  9673. res.set_content("ok", "text/plain");
  9674. });
  9675. svr.CustomRoute("PROPFIND", "/dav",
  9676. [&](const Request & /*req*/, Response &res) {
  9677. res.status = StatusCode::MultiStatus_207;
  9678. });
  9679. // Server read timeout must be longer than the client read timeout for the
  9680. // bug to reproduce, probably to force the server to process a request
  9681. // without a trailing blank line.
  9682. const time_t client_read_timeout_sec = 1;
  9683. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9684. bool listen_thread_ok = false;
  9685. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. EXPECT_TRUE(listen_thread_ok);
  9691. });
  9692. svr.wait_until_ready();
  9693. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9694. }
  9695. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9696. // A certain header line causes an exception if the header property is parsed
  9697. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9698. test_raw_request(
  9699. "GET /hi HTTP/1.1\r\n"
  9700. " : "
  9701. " "
  9702. " ");
  9703. }
  9704. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9705. // A certain header line causes an exception if the header property *name* is
  9706. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9707. // greedy matcher and requires backtracking when there are a lot of ":"
  9708. // characters.
  9709. // This occurs with libc++ but not libstdc++.
  9710. test_raw_request(
  9711. "GET /hi HTTP/1.1\r\n"
  9712. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9713. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9714. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9715. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9716. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9717. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9718. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9719. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9720. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9721. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9722. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9723. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9724. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9725. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9726. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9727. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9728. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9729. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9730. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9731. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9732. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9733. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9734. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9735. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9736. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9737. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9738. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9739. "&&&%%%");
  9740. }
  9741. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9742. // Make sure this doesn't crash the server.
  9743. // In a previous version of the header line regex, the "\r" rendered the line
  9744. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9745. // a new position where the leading white space ended and the field value
  9746. // began.
  9747. // The crash occurs with libc++ but not libstdc++.
  9748. test_raw_request("GET /hi HTTP/1.1\r\n"
  9749. "a:" +
  9750. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9751. "\r\n"
  9752. "\r\n");
  9753. }
  9754. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9755. const char *rejected[] = {
  9756. // RFC 9112 §3: one SP between the parts, and nothing else
  9757. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9758. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9759. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9760. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9761. // A request-target has no fragment
  9762. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9763. // An HTTP/1.1 request needs a Host
  9764. "GET /hi HTTP/1.1\r\n\r\n",
  9765. };
  9766. for (auto request : rejected) {
  9767. std::string out;
  9768. test_raw_request(request, &out);
  9769. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9770. }
  9771. std::string out;
  9772. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9773. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9774. }
  9775. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9776. // RFC 9112 §6.1
  9777. const char *requests[] = {
  9778. "PUT /put_hi HTTP/1.1\r\n"
  9779. "Host: localhost\r\n"
  9780. "Content-Length: 0\r\n"
  9781. "Transfer-Encoding: chunked\r\n"
  9782. "\r\n"
  9783. "0\r\n\r\n",
  9784. "PUT /put_hi HTTP/1.0\r\n"
  9785. "Connection: keep-alive\r\n"
  9786. "Transfer-Encoding: chunked\r\n"
  9787. "\r\n"
  9788. "0\r\n\r\n",
  9789. };
  9790. for (auto request : requests) {
  9791. std::string out;
  9792. test_raw_request(request, &out);
  9793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9794. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9795. }
  9796. }
  9797. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9798. std::string out;
  9799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9800. "Content-Type: text/plain\r\n"
  9801. "Transfer-Encoding: chunked\r\n"
  9802. "\r\n"
  9803. "nothex\r\n",
  9804. &out);
  9805. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9806. }
  9807. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9808. std::string out;
  9809. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9810. "Content-Type: text/plain\r\n"
  9811. "Transfer-Encoding: chunked\r\n"
  9812. "\r\n"
  9813. "3\r\n"
  9814. "xyz\r\n"
  9815. "NaN\r\n",
  9816. &out);
  9817. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9818. }
  9819. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9820. std::string out;
  9821. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9822. "Content-Type: text/plain\r\n"
  9823. "Transfer-Encoding: chunked\r\n"
  9824. "\r\n"
  9825. // Length is too large for 64 bits.
  9826. "1ffffffffffffffff\r\n"
  9827. "xyz\r\n",
  9828. &out);
  9829. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9830. }
  9831. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9832. test_raw_request("GET /hi HTTP/1.1\r\n"
  9833. "Content-Type: text/plain\r\n\r");
  9834. }
  9835. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9836. std::string out;
  9837. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9838. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9839. }
  9840. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9841. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9842. std::string out;
  9843. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9845. }
  9846. }
  9847. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9848. std::string out;
  9849. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9850. "Host: localhost\r\n"
  9851. "Connection: close\r\n\r\n",
  9852. &out);
  9853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9854. }
  9855. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9856. Server svr;
  9857. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9858. EXPECT_TRUE(!req.remote_addr.empty());
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. });
  9866. svr.wait_until_ready();
  9867. // Send an invalid request line to trigger Bad Request
  9868. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9869. std::string out;
  9870. ASSERT_TRUE(send_request(5, bad_req, &out));
  9871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9872. }
  9873. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9874. // answered right away rather than blocking on a read that waits for EOF.
  9875. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9876. std::string out;
  9877. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9878. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9879. }
  9880. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9881. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9882. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9883. for (const auto *method : methods) {
  9884. Server svr;
  9885. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9886. EXPECT_FALSE(svr.is_valid()) << method;
  9887. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9888. }
  9889. }
  9890. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9891. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9892. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9893. for (const auto *method : methods) {
  9894. Server svr;
  9895. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9896. EXPECT_FALSE(svr.is_valid()) << method;
  9897. }
  9898. }
  9899. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9900. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9901. "COPY", "MOVE", "LOCK",
  9902. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9903. Server svr;
  9904. for (const auto *method : methods) {
  9905. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9906. }
  9907. EXPECT_TRUE(svr.is_valid());
  9908. }
  9909. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9910. Server svr;
  9911. svr.CustomRoute("POST", "/x",
  9912. [](const Request &, Response &, const ContentReader &) {});
  9913. EXPECT_FALSE(svr.is_valid());
  9914. }
  9915. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9916. Server svr;
  9917. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9918. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9919. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9920. EXPECT_FALSE(svr.is_valid());
  9921. }
  9922. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9923. Server svr;
  9924. auto captured = Error::Success;
  9925. svr.set_error_logger(
  9926. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9927. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9928. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9929. }
  9930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9931. std::string out;
  9932. std::string request(
  9933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9934. test_raw_request(request, &out);
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9936. }
  9937. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9938. std::string out;
  9939. std::string request(
  9940. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9941. test_raw_request(request, &out);
  9942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9943. }
  9944. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9945. std::string out;
  9946. std::string request(
  9947. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9948. test_raw_request(request, &out);
  9949. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9950. }
  9951. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9952. std::string out;
  9953. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9954. "Host: localhost\r\n"
  9955. "Test: \r\n\r\n",
  9956. &out);
  9957. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9958. }
  9959. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9960. Server svr;
  9961. std::string x_custom;
  9962. std::string cookie;
  9963. std::string xff;
  9964. std::string x_unicode;
  9965. std::string x_iis;
  9966. svr.Get("/check", [&](const Request &req, Response &res) {
  9967. x_custom = req.get_header_value("X-Custom");
  9968. cookie = req.get_header_value("Cookie");
  9969. xff = req.get_header_value("X-Forwarded-For");
  9970. x_unicode = req.get_header_value("X-Unicode");
  9971. x_iis = req.get_header_value("X-IIS");
  9972. res.set_content("ok", "text/plain");
  9973. });
  9974. thread t = thread([&] { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. t.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. const std::string req = "GET /check HTTP/1.1\r\n"
  9982. "Host: localhost\r\n"
  9983. "X-Custom: a%0D%0AInjected: b\r\n"
  9984. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9985. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9986. "X-Unicode: %E3%81%82\r\n"
  9987. "X-IIS: %u00E9\r\n"
  9988. "Connection: close\r\n"
  9989. "\r\n";
  9990. std::string res;
  9991. ASSERT_TRUE(send_request(5, req, &res));
  9992. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9993. // Every value must be returned verbatim (wire form), with no decoding.
  9994. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9995. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9996. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9997. EXPECT_EQ("%E3%81%82", x_unicode);
  9998. EXPECT_EQ("%u00E9", x_iis);
  9999. }
  10000. // Applications that previously relied on automatic percent-decoding can
  10001. // reproduce the old behavior by explicitly calling decode_path_component()
  10002. // or, for RFC 3986 conformance, decode_uri_component().
  10003. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10004. Server svr;
  10005. std::string decoded;
  10006. svr.Get("/check", [&](const Request &req, Response &res) {
  10007. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. thread t = thread([&] { svr.listen(HOST, PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. const std::string req = "GET /check HTTP/1.1\r\n"
  10018. "Host: localhost\r\n"
  10019. "X-Custom: hello%20world\r\n"
  10020. "Connection: close\r\n"
  10021. "\r\n";
  10022. std::string res;
  10023. ASSERT_TRUE(send_request(5, req, &res));
  10024. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10025. EXPECT_EQ("hello world", decoded);
  10026. }
  10027. // Regression test for #2033. Browsers send Referer values that include
  10028. // percent-encoded characters such as %0A inside the URL. Decoding the
  10029. // header value would either trip the post-decode CR/LF/NUL guard (the
  10030. // original bug, returning 400) or, after that guard was relaxed, silently
  10031. // store a literal LF — both unacceptable. The wire form must round-trip.
  10032. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10033. Server svr;
  10034. std::string referer;
  10035. svr.Get("/check", [&](const Request &req, Response &res) {
  10036. referer = req.get_header_value("Referer");
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. thread t = thread([&] { svr.listen(HOST, PORT); });
  10040. auto se = detail::scope_exit([&] {
  10041. svr.stop();
  10042. t.join();
  10043. ASSERT_FALSE(svr.is_running());
  10044. });
  10045. svr.wait_until_ready();
  10046. const std::string req = "GET /check HTTP/1.1\r\n"
  10047. "Host: localhost\r\n"
  10048. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10049. "Connection: close\r\n"
  10050. "\r\n";
  10051. std::string res;
  10052. ASSERT_TRUE(send_request(5, req, &res));
  10053. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10054. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10055. }
  10056. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10057. Server svr;
  10058. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10059. res.set_header("Cache-Control", "no-cache");
  10060. res.set_chunked_content_provider(
  10061. "text/event-stream", [](size_t offset, DataSink &sink) {
  10062. std::string s = "data:";
  10063. s += std::to_string(offset);
  10064. s += "\n\n";
  10065. auto ret = sink.write(s.data(), s.size());
  10066. EXPECT_TRUE(ret);
  10067. std::this_thread::sleep_for(std::chrono::seconds(1));
  10068. return true;
  10069. });
  10070. });
  10071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10072. svr.wait_until_ready();
  10073. Client client(HOST, PORT);
  10074. const Headers headers = {{"Accept", "text/event-stream"}};
  10075. auto get_thread = std::thread([&client, &headers]() {
  10076. auto res = client.Get(
  10077. "/events", headers,
  10078. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10079. });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. get_thread.join();
  10083. listen_thread.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. // Give GET time to get a few messages.
  10087. std::this_thread::sleep_for(std::chrono::seconds(2));
  10088. }
  10089. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10090. httplib::Server svr;
  10091. svr.Post("/hi",
  10092. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10093. res.status = StatusCode::OK_200;
  10094. });
  10095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10096. svr.wait_until_ready();
  10097. Client cli(HOST, PORT);
  10098. auto res = cli.Post("/hi", "data", "text/plain");
  10099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10100. EXPECT_EQ(StatusCode::OK_200, res->status);
  10101. svr.stop();
  10102. thread.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. res = cli.Post("/hi", "data", "text/plain");
  10105. ASSERT_FALSE(res);
  10106. }
  10107. TEST(ServerStopTest, ListenFailure) {
  10108. Server svr;
  10109. auto t = thread([&]() {
  10110. auto ret = svr.listen("????", PORT);
  10111. EXPECT_FALSE(ret);
  10112. });
  10113. svr.wait_until_ready();
  10114. svr.stop();
  10115. t.join();
  10116. }
  10117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10118. TEST(ServerStopTest, Decommision) {
  10119. Server svr;
  10120. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10121. for (int i = 0; i < 4; i++) {
  10122. auto is_even = !(i % 2);
  10123. std::thread t{[&] {
  10124. try {
  10125. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10126. if (is_even) {
  10127. throw std::runtime_error("Some thing that happens to go wrong.");
  10128. }
  10129. svr.listen(HOST, PORT);
  10130. } catch (...) { svr.decommission(); }
  10131. }};
  10132. svr.wait_until_ready();
  10133. // Server is up
  10134. {
  10135. Client cli(HOST, PORT);
  10136. auto res = cli.Get("/hi");
  10137. if (is_even) {
  10138. EXPECT_FALSE(res);
  10139. } else {
  10140. EXPECT_TRUE(res);
  10141. EXPECT_EQ("hi...", res->body);
  10142. }
  10143. }
  10144. svr.stop();
  10145. t.join();
  10146. // Server is down...
  10147. {
  10148. Client cli(HOST, PORT);
  10149. auto res = cli.Get("/hi");
  10150. EXPECT_FALSE(res);
  10151. }
  10152. }
  10153. }
  10154. #endif
  10155. // Helper function for string body upload progress tests
  10156. template <typename SetupHandler, typename ClientCall>
  10157. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10158. ClientCall &&client_call,
  10159. const string &body) {
  10160. Server svr;
  10161. setup_handler(svr);
  10162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10163. auto se = detail::scope_exit([&] {
  10164. svr.stop();
  10165. t.join();
  10166. });
  10167. svr.wait_until_ready();
  10168. Client cli(HOST, PORT);
  10169. vector<uint64_t> progress_values;
  10170. bool progress_called = false;
  10171. auto res =
  10172. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10173. progress_values.push_back(current);
  10174. progress_called = true;
  10175. return true;
  10176. });
  10177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10178. EXPECT_EQ(200, res->status);
  10179. EXPECT_TRUE(progress_called);
  10180. }
  10181. TEST(UploadProgressTest, PostStringBodyBasic) {
  10182. TestStringBodyUploadProgress(
  10183. [](Server &svr) {
  10184. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10185. res.set_content("received", "text/plain");
  10186. });
  10187. },
  10188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10189. return cli.Post("/test", body, "text/plain", progress_callback);
  10190. },
  10191. "test data for upload progress");
  10192. }
  10193. TEST(UploadProgressTest, PutStringBodyBasic) {
  10194. TestStringBodyUploadProgress(
  10195. [](Server &svr) {
  10196. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10197. res.set_content("put received", "text/plain");
  10198. });
  10199. },
  10200. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10201. return cli.Put("/test", body, "text/plain", progress_callback);
  10202. },
  10203. "put test data for upload progress");
  10204. }
  10205. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10206. TestStringBodyUploadProgress(
  10207. [](Server &svr) {
  10208. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10209. res.set_content("patch received", "text/plain");
  10210. });
  10211. },
  10212. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10213. return cli.Patch("/test", body, "text/plain", progress_callback);
  10214. },
  10215. "patch test data for upload progress");
  10216. }
  10217. // Helper function for content provider upload progress tests
  10218. template <typename SetupHandler, typename ClientCall>
  10219. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10220. ClientCall &&client_call) {
  10221. Server svr;
  10222. setup_handler(svr);
  10223. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. });
  10228. svr.wait_until_ready();
  10229. Client cli(HOST, PORT);
  10230. vector<uint64_t> progress_values;
  10231. auto res =
  10232. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10233. progress_values.push_back(current);
  10234. return true;
  10235. });
  10236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10237. EXPECT_EQ(200, res->status);
  10238. EXPECT_FALSE(progress_values.empty());
  10239. }
  10240. TEST(UploadProgressTest, PostContentProviderProgress) {
  10241. TestContentProviderUploadProgress(
  10242. [](Server &svr) {
  10243. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10244. res.set_content("provider received", "text/plain");
  10245. });
  10246. },
  10247. [](Client &cli, UploadProgress progress_callback) {
  10248. return cli.Post(
  10249. "/test", 9,
  10250. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10251. sink.os << "test data";
  10252. return true;
  10253. },
  10254. "text/plain", progress_callback);
  10255. });
  10256. }
  10257. // Helper function for multipart upload progress tests
  10258. template <typename SetupHandler, typename ClientCall>
  10259. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10260. ClientCall &&client_call,
  10261. const string &endpoint) {
  10262. Server svr;
  10263. setup_handler(svr);
  10264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. });
  10269. svr.wait_until_ready();
  10270. Client cli(HOST, PORT);
  10271. vector<uint64_t> progress_values;
  10272. UploadFormDataItems items = {
  10273. {"field1", "value1", "", ""},
  10274. {"field2", "longer value for progress tracking test", "", ""},
  10275. {"file1", "file content data for upload progress", "test.txt",
  10276. "text/plain"}};
  10277. auto res = client_call(cli, endpoint, items,
  10278. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10279. progress_values.push_back(current);
  10280. return true;
  10281. });
  10282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10283. EXPECT_EQ(200, res->status);
  10284. EXPECT_FALSE(progress_values.empty());
  10285. }
  10286. TEST(UploadProgressTest, PostMultipartProgress) {
  10287. TestMultipartUploadProgress(
  10288. [](Server &svr) {
  10289. svr.Post("/multipart", [](const Request &req, Response &res) {
  10290. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10291. res.set_content("multipart received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10295. UploadProgress progress_callback) {
  10296. return cli.Post(endpoint, items, progress_callback);
  10297. },
  10298. "/multipart");
  10299. }
  10300. // Helper function for basic download progress tests
  10301. template <typename SetupHandler, typename ClientCall>
  10302. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10303. ClientCall &&client_call, const string &endpoint,
  10304. size_t expected_content_size) {
  10305. Server svr;
  10306. setup_handler(svr);
  10307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. t.join();
  10311. });
  10312. svr.wait_until_ready();
  10313. Client cli(HOST, PORT);
  10314. vector<uint64_t> progress_values;
  10315. auto res = client_call(cli, endpoint,
  10316. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10317. progress_values.push_back(current);
  10318. return true;
  10319. });
  10320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10321. EXPECT_EQ(200, res->status);
  10322. EXPECT_FALSE(progress_values.empty());
  10323. EXPECT_EQ(expected_content_size, res->body.size());
  10324. }
  10325. TEST(DownloadProgressTest, GetBasic) {
  10326. TestBasicDownloadProgress(
  10327. [](Server &svr) {
  10328. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10329. string content(1000, 'D');
  10330. res.set_content(content, "text/plain");
  10331. });
  10332. },
  10333. [](Client &cli, const string &endpoint,
  10334. DownloadProgress progress_callback) {
  10335. return cli.Get(endpoint, progress_callback);
  10336. },
  10337. "/download", 1000u);
  10338. }
  10339. // Helper function for content receiver download progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint,
  10344. size_t expected_content_size) {
  10345. Server svr;
  10346. setup_handler(svr);
  10347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. });
  10352. svr.wait_until_ready();
  10353. Client cli(HOST, PORT);
  10354. vector<uint64_t> progress_values;
  10355. string received_body;
  10356. auto res = client_call(
  10357. cli, endpoint,
  10358. [&](const char *data, size_t data_length) -> bool {
  10359. received_body.append(data, data_length);
  10360. return true;
  10361. },
  10362. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10363. progress_values.push_back(current);
  10364. return true;
  10365. });
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(200, res->status);
  10368. EXPECT_FALSE(progress_values.empty());
  10369. EXPECT_EQ(expected_content_size, received_body.size());
  10370. EXPECT_TRUE(res->body.empty());
  10371. }
  10372. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10373. TestContentReceiverDownloadProgress(
  10374. [](Server &svr) {
  10375. svr.Get("/download-receiver",
  10376. [](const Request & /*req*/, Response &res) {
  10377. string content(2000, 'R');
  10378. res.set_content(content, "text/plain");
  10379. });
  10380. },
  10381. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10382. DownloadProgress progress_callback) {
  10383. return cli.Get(endpoint, content_receiver, progress_callback);
  10384. },
  10385. "/download-receiver", 2000u);
  10386. }
  10387. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10388. // A provider reaching a pass with nothing to hand over - an empty buffer
  10389. // popped off a queue, say - must not be taken to mean the body is finished.
  10390. // It used to end the loop with the terminating chunk unwritten while the
  10391. // server still considered the response complete, so the peer waited for an
  10392. // end that never arrived.
  10393. Server svr;
  10394. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10395. auto step = std::make_shared<int>(0);
  10396. res.set_chunked_content_provider("text/plain",
  10397. [step](size_t /*offset*/, DataSink &sink) {
  10398. switch ((*step)++) {
  10399. case 0: sink.write("", 0); break;
  10400. case 1: sink.write("hello", 5); break;
  10401. default: sink.done(); break;
  10402. }
  10403. return true;
  10404. });
  10405. });
  10406. auto port = svr.bind_to_any_port(HOST);
  10407. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10408. auto listen_se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. listen_thread.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. Client cli(HOST, port);
  10415. // Without the fix the body is never terminated, so bound the wait rather
  10416. // than letting the test hang on the default read timeout.
  10417. cli.set_read_timeout(5, 0);
  10418. auto res = cli.Get("/stream");
  10419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10420. EXPECT_EQ(StatusCode::OK_200, res->status);
  10421. EXPECT_EQ("hello", res->body);
  10422. }
  10423. TEST(StreamingTest, NoContentLengthStreaming) {
  10424. Server svr;
  10425. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10426. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10427. if (offset < 6) {
  10428. sink.os << (offset < 3 ? "a" : "b");
  10429. } else {
  10430. sink.done();
  10431. }
  10432. return true;
  10433. });
  10434. });
  10435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10436. auto listen_se = detail::scope_exit([&] {
  10437. svr.stop();
  10438. listen_thread.join();
  10439. ASSERT_FALSE(svr.is_running());
  10440. });
  10441. svr.wait_until_ready();
  10442. Client client(HOST, PORT);
  10443. auto get_thread = std::thread([&client]() {
  10444. std::string s;
  10445. auto res =
  10446. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10447. s += std::string(data, len);
  10448. return true;
  10449. });
  10450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10451. EXPECT_EQ(StatusCode::OK_200, res->status);
  10452. EXPECT_EQ("aaabbb", s);
  10453. });
  10454. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10455. // Give GET time to get a few messages.
  10456. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10457. }
  10458. TEST(MountTest, Unmount) {
  10459. Server svr;
  10460. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10461. auto se = detail::scope_exit([&] {
  10462. svr.stop();
  10463. listen_thread.join();
  10464. ASSERT_FALSE(svr.is_running());
  10465. });
  10466. svr.wait_until_ready();
  10467. Client cli("localhost", PORT);
  10468. svr.set_mount_point("/mount2", "./www2");
  10469. auto res = cli.Get("/");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10472. res = cli.Get("/mount2/dir/test.html");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_EQ(StatusCode::OK_200, res->status);
  10475. svr.set_mount_point("/", "./www");
  10476. res = cli.Get("/dir/");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. svr.remove_mount_point("/");
  10480. res = cli.Get("/dir/");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10483. svr.remove_mount_point("/mount2");
  10484. res = cli.Get("/mount2/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10487. }
  10488. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10489. Server svr;
  10490. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10491. svr.Get("/api/hello", [](const Request &, Response &res) {
  10492. res.set_content("api", "text/plain");
  10493. });
  10494. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10495. auto se = detail::scope_exit([&] {
  10496. svr.stop();
  10497. listen_thread.join();
  10498. ASSERT_FALSE(svr.is_running());
  10499. });
  10500. svr.wait_until_ready();
  10501. Client cli(HOST, PORT);
  10502. auto res = cli.Get("/dir/test.html");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. res = cli.Get("/api/hello");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. EXPECT_EQ("api", res->body);
  10509. }
  10510. TEST(MountTest, PathSegmentBoundary) {
  10511. Server svr;
  10512. svr.set_mount_point("/mount2", "./www2");
  10513. svr.set_mount_point("/", "./www");
  10514. auto port = svr.bind_to_any_port(HOST);
  10515. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. listen_thread.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, port);
  10523. auto res = cli.Get("/mount2/dir/test.html");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. EXPECT_EQ(StatusCode::OK_200, res->status);
  10526. // "/mount2" must not match part-way through a path segment.
  10527. res = cli.Get("/mount2dir/test.html");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. // A mount point ending in '/' keeps matching every path below it.
  10531. res = cli.Get("/dir/test.html");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. }
  10535. TEST(MountTest, Redicect) {
  10536. Server svr;
  10537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10538. auto se = detail::scope_exit([&] {
  10539. svr.stop();
  10540. listen_thread.join();
  10541. ASSERT_FALSE(svr.is_running());
  10542. });
  10543. svr.set_mount_point("/", "./www");
  10544. svr.wait_until_ready();
  10545. Client cli("localhost", PORT);
  10546. auto res = cli.Get("/dir/");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. res = cli.Get("/dir");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10552. res = cli.Get("/file");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. res = cli.Get("/file/");
  10556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10557. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10558. cli.set_follow_location(true);
  10559. res = cli.Get("/dir");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. }
  10563. TEST(MountTest, MultibytesPathName) {
  10564. Server svr;
  10565. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10566. auto se = detail::scope_exit([&] {
  10567. svr.stop();
  10568. listen_thread.join();
  10569. ASSERT_FALSE(svr.is_running());
  10570. });
  10571. svr.set_mount_point("/", "./www");
  10572. svr.wait_until_ready();
  10573. Client cli("localhost", PORT);
  10574. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::OK_200, res->status);
  10577. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10578. }
  10579. #ifdef _WIN32
  10580. // Issue #2435: mmap::open() must succeed even when another handle holds
  10581. // the file open for writing (e.g. an active log file).
  10582. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10583. const char *path = "mmap_concurrent_writer_test.txt";
  10584. const char *content = "hello";
  10585. {
  10586. std::ofstream f(path, std::ios::binary);
  10587. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10588. }
  10589. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10590. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10591. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10592. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10593. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10594. detail::mmap m(path);
  10595. ASSERT_TRUE(m.is_open());
  10596. EXPECT_EQ(strlen(content), m.size());
  10597. char buf[8];
  10598. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10599. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10600. }
  10601. #endif
  10602. #ifndef _WIN32
  10603. // A directory or a device has no size to serve.
  10604. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10605. const char *path = "./mmap_not_regular_test_dir";
  10606. ASSERT_EQ(0, ::mkdir(path, 0755));
  10607. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10608. for (auto p : {path, "/dev/null"}) {
  10609. detail::mmap m(p);
  10610. EXPECT_FALSE(m.is_open()) << p;
  10611. EXPECT_EQ(0U, m.size()) << p;
  10612. }
  10613. Server svr;
  10614. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10615. res.set_file_content("/dev/null");
  10616. });
  10617. auto port = svr.bind_to_any_port(HOST);
  10618. thread t = thread([&] { svr.listen_after_bind(); });
  10619. auto se = detail::scope_exit([&] {
  10620. svr.stop();
  10621. t.join();
  10622. });
  10623. svr.wait_until_ready();
  10624. auto res = Client(HOST, port).Get("/null");
  10625. ASSERT_TRUE(res);
  10626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10627. }
  10628. #endif
  10629. #ifdef __linux__
  10630. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10631. TEST(MmapTest, FileIsNotMapped) {
  10632. const char *path = "mmap_not_mapped_test.txt";
  10633. {
  10634. std::ofstream f(path, std::ios::binary);
  10635. f << "hello";
  10636. }
  10637. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10638. detail::mmap m(path);
  10639. ASSERT_TRUE(m.is_open());
  10640. std::ifstream maps("/proc/self/maps");
  10641. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10642. std::istreambuf_iterator<char>());
  10643. EXPECT_EQ(std::string::npos, mappings.find(path));
  10644. }
  10645. #endif
  10646. TEST(KeepAliveTest, ReadTimeout) {
  10647. Server svr;
  10648. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10649. std::this_thread::sleep_for(std::chrono::seconds(2));
  10650. res.set_content("a", "text/plain");
  10651. });
  10652. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10653. res.set_content("b", "text/plain");
  10654. });
  10655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10656. auto se = detail::scope_exit([&] {
  10657. svr.stop();
  10658. listen_thread.join();
  10659. ASSERT_FALSE(svr.is_running());
  10660. });
  10661. svr.wait_until_ready();
  10662. Client cli("localhost", PORT);
  10663. cli.set_keep_alive(true);
  10664. cli.set_read_timeout(std::chrono::seconds(1));
  10665. auto resa = cli.Get("/a");
  10666. ASSERT_FALSE(resa);
  10667. EXPECT_EQ(Error::Read, resa.error());
  10668. auto resb = cli.Get("/b");
  10669. ASSERT_TRUE(resb);
  10670. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10671. EXPECT_EQ("b", resb->body);
  10672. }
  10673. TEST(KeepAliveTest, MaxCount) {
  10674. size_t keep_alive_max_count = 3;
  10675. Server svr;
  10676. svr.set_keep_alive_max_count(keep_alive_max_count);
  10677. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10678. res.set_content("Hello World!", "text/plain");
  10679. });
  10680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. listen_thread.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. });
  10686. svr.wait_until_ready();
  10687. Client cli(HOST, PORT);
  10688. cli.set_keep_alive(true);
  10689. for (size_t i = 0; i < 5; i++) {
  10690. auto result = cli.Get("/hi");
  10691. ASSERT_TRUE(result);
  10692. EXPECT_EQ(StatusCode::OK_200, result->status);
  10693. if (i == keep_alive_max_count - 1) {
  10694. EXPECT_EQ("close", result->get_header_value("Connection"));
  10695. } else {
  10696. EXPECT_FALSE(result->has_header("Connection"));
  10697. }
  10698. }
  10699. }
  10700. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10701. // can pull the next one into the server's buffer. The server must serve it
  10702. // without waiting for the socket to become readable again. The keep-alive
  10703. // timeout outlasts the client's read timeout, so a request left waiting for it
  10704. // shows up as a missing response.
  10705. static void serve_pipelining_routes(Server &svr,
  10706. const std::function<void(int)> &client) {
  10707. svr.set_keep_alive_timeout(5);
  10708. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10709. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10710. });
  10711. svr.Post("/echo", [](const Request &req, Response &res) {
  10712. res.set_content("echo " + req.body, "text/plain");
  10713. });
  10714. auto port = svr.bind_to_any_port(HOST);
  10715. thread t = thread([&] { svr.listen_after_bind(); });
  10716. auto se = detail::scope_exit([&] {
  10717. svr.stop();
  10718. t.join();
  10719. });
  10720. svr.wait_until_ready();
  10721. client(port);
  10722. }
  10723. static std::string
  10724. send_pipelined_requests(const std::vector<std::string> &parts) {
  10725. Server svr;
  10726. std::string res;
  10727. serve_pipelining_routes(svr, [&](int port) {
  10728. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10729. });
  10730. return res;
  10731. }
  10732. static void expect_in_order(const std::string &res,
  10733. const std::vector<std::string> &bodies) {
  10734. size_t pos = 0;
  10735. for (const auto &body : bodies) {
  10736. pos = res.find(body, pos);
  10737. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10738. pos += body.size();
  10739. }
  10740. }
  10741. TEST(KeepAliveTest, PipelinedRequests) {
  10742. auto res = send_pipelined_requests(
  10743. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10744. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10745. "Content-Length: 4\r\n\r\nbody"
  10746. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10747. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10748. }
  10749. // The second request starts in the server's buffer and ends on the socket.
  10750. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10751. auto res =
  10752. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10753. "GET /hi/2 HTTP/1.1\r\nHo",
  10754. "st: localhost\r\nConnection: close\r\n\r\n"});
  10755. expect_in_order(res, {"hi 1", "hi 2"});
  10756. }
  10757. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10758. // CRLF after a body does not turn into a 400 for the next request.
  10759. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10760. auto res = send_pipelined_requests(
  10761. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10762. "Content-Length: 4\r\n\r\nbody\r\n"
  10763. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10764. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10765. expect_in_order(res, {"echo body", "hi 2"});
  10766. }
  10767. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10768. // must not be served as the next request.
  10769. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10770. auto res = send_pipelined_requests(
  10771. {"INVALID REQUEST LINE\r\n\r\n"
  10772. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10773. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10774. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10775. }
  10776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10777. // Over TLS, the next request is held by the TLS library as already decrypted
  10778. // data rather than on the socket.
  10779. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10781. std::string res;
  10782. serve_pipelining_routes(svr, [&](int port) {
  10783. // One part, so all three requests arrive in one TLS record
  10784. EXPECT_TRUE(send_ssl_request_in_parts(
  10785. 2,
  10786. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10787. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10788. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10789. &res, port));
  10790. });
  10791. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10792. }
  10793. #endif
  10794. TEST(KeepAliveTest, Issue1041) {
  10795. Server svr;
  10796. svr.set_keep_alive_timeout(3);
  10797. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10798. res.set_content("Hello World!", "text/plain");
  10799. });
  10800. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. listen_thread.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. Client cli(HOST, PORT);
  10808. cli.set_keep_alive(true);
  10809. auto result = cli.Get("/hi");
  10810. ASSERT_TRUE(result);
  10811. EXPECT_EQ(StatusCode::OK_200, result->status);
  10812. std::this_thread::sleep_for(std::chrono::seconds(5));
  10813. result = cli.Get("/hi");
  10814. ASSERT_TRUE(result);
  10815. EXPECT_EQ(StatusCode::OK_200, result->status);
  10816. }
  10817. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10818. Server svr;
  10819. svr.set_keep_alive_max_count(0);
  10820. std::set<int> remote_ports;
  10821. svr.Get("/hi", [&](const Request &req, Response &res) {
  10822. remote_ports.insert(req.remote_port);
  10823. res.set_content("hi", "text/plain");
  10824. });
  10825. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. listen_thread.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. Client cli(HOST, PORT);
  10833. cli.set_keep_alive(true);
  10834. for (int i = 0; i < 3; i++) {
  10835. auto res = cli.Get("/hi");
  10836. ASSERT_TRUE(res);
  10837. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10838. }
  10839. // All three over one connection
  10840. EXPECT_EQ(1u, remote_ports.size());
  10841. }
  10842. TEST(KeepAliveTest, Issue1959) {
  10843. Server svr;
  10844. svr.set_keep_alive_timeout(5);
  10845. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10846. res.set_content("a", "text/plain");
  10847. });
  10848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10849. auto se = detail::scope_exit([&] {
  10850. if (!svr.is_running()) return;
  10851. svr.stop();
  10852. listen_thread.join();
  10853. ASSERT_FALSE(svr.is_running());
  10854. });
  10855. svr.wait_until_ready();
  10856. Client cli("localhost", PORT);
  10857. cli.set_keep_alive(true);
  10858. using namespace std::chrono;
  10859. auto start = steady_clock::now();
  10860. cli.Get("/a");
  10861. svr.stop();
  10862. listen_thread.join();
  10863. auto end = steady_clock::now();
  10864. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10865. EXPECT_LT(elapsed, 5000);
  10866. }
  10867. #ifdef CPPHTTPLIB_SSL_ENABLED
  10868. TEST(KeepAliveTest, SSLClientReconnection) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. ASSERT_TRUE(svr.is_valid());
  10871. svr.set_keep_alive_timeout(1);
  10872. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10873. res.set_content("Hello World!", "text/plain");
  10874. });
  10875. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10876. auto se = detail::scope_exit([&] {
  10877. svr.stop();
  10878. listen_thread.join();
  10879. ASSERT_FALSE(svr.is_running());
  10880. });
  10881. svr.wait_until_ready();
  10882. SSLClient cli(HOST, PORT);
  10883. cli.enable_server_certificate_verification(false);
  10884. cli.set_keep_alive(true);
  10885. auto result = cli.Get("/hi");
  10886. ASSERT_TRUE(result);
  10887. EXPECT_EQ(StatusCode::OK_200, result->status);
  10888. result = cli.Get("/hi");
  10889. ASSERT_TRUE(result);
  10890. EXPECT_EQ(StatusCode::OK_200, result->status);
  10891. std::this_thread::sleep_for(std::chrono::seconds(2));
  10892. // Recoonect
  10893. result = cli.Get("/hi");
  10894. ASSERT_TRUE(result);
  10895. EXPECT_EQ(StatusCode::OK_200, result->status);
  10896. result = cli.Get("/hi");
  10897. ASSERT_TRUE(result);
  10898. EXPECT_EQ(StatusCode::OK_200, result->status);
  10899. }
  10900. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10902. ASSERT_TRUE(svr.is_valid());
  10903. svr.set_keep_alive_timeout(1);
  10904. std::string content = "reconnect";
  10905. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10906. res.set_content("Hello World!", "text/plain");
  10907. });
  10908. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. listen_thread.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. SSLClient cli(HOST, PORT);
  10916. cli.enable_server_certificate_verification(false);
  10917. cli.set_keep_alive(true);
  10918. auto result = cli.Post(
  10919. "/hi", content.size(),
  10920. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10921. sink.write(content.c_str(), content.size());
  10922. return true;
  10923. },
  10924. "text/plain");
  10925. ASSERT_TRUE(result);
  10926. EXPECT_EQ(200, result->status);
  10927. std::this_thread::sleep_for(std::chrono::seconds(2));
  10928. // Recoonect
  10929. result = cli.Post(
  10930. "/hi", content.size(),
  10931. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10932. sink.write(content.c_str(), content.size());
  10933. return true;
  10934. },
  10935. "text/plain");
  10936. ASSERT_TRUE(result);
  10937. EXPECT_EQ(200, result->status);
  10938. result = cli.Post(
  10939. "/hi", content.size(),
  10940. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10941. sink.write(content.c_str(), content.size());
  10942. return true;
  10943. },
  10944. "text/plain");
  10945. ASSERT_TRUE(result);
  10946. EXPECT_EQ(200, result->status);
  10947. }
  10948. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10949. using namespace httplib::tls;
  10950. {
  10951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. ASSERT_TRUE(svr.is_valid());
  10953. svr.Get("/sni", [&](const Request &req, Response &res) {
  10954. std::string expected = req.sni();
  10955. EXPECT_EQ(expected, req.get_param_value("expected"));
  10956. res.set_content("ok", "text/plain");
  10957. });
  10958. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10959. auto se = detail::scope_exit([&] {
  10960. svr.stop();
  10961. listen_thread.join();
  10962. ASSERT_FALSE(svr.is_running());
  10963. });
  10964. svr.wait_until_ready();
  10965. {
  10966. SSLClient cli("localhost", PORT);
  10967. cli.enable_server_certificate_verification(false);
  10968. auto res = cli.Get("/sni?expected=localhost");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. }
  10971. {
  10972. SSLClient cli("::1", PORT);
  10973. cli.enable_server_certificate_verification(false);
  10974. auto res = cli.Get("/sni?expected=");
  10975. // NOTE: This may fail if the server is listening on IPv4 only
  10976. // (e.g., when localhost resolves to 127.0.0.1 only)
  10977. if (res) {
  10978. EXPECT_EQ(StatusCode::OK_200, res->status);
  10979. } else {
  10980. EXPECT_EQ(Error::Connection, res.error());
  10981. }
  10982. }
  10983. }
  10984. }
  10985. #endif
  10986. TEST(ClientProblemDetectionTest, ContentProvider) {
  10987. Server svr;
  10988. size_t content_length = 1024 * 1024;
  10989. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10990. res.set_content_provider(
  10991. content_length, "text/plain",
  10992. [&](size_t offset, size_t length, DataSink &sink) {
  10993. auto out_len = std::min(length, static_cast<size_t>(1024));
  10994. std::string out(out_len, '@');
  10995. sink.write(out.data(), out_len);
  10996. return offset < 4096;
  10997. },
  10998. [](bool success) { ASSERT_FALSE(success); });
  10999. });
  11000. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11001. res.set_content_provider(
  11002. 0, "text/plain",
  11003. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11004. EXPECT_TRUE(false);
  11005. return true;
  11006. },
  11007. [](bool success) { ASSERT_FALSE(success); });
  11008. });
  11009. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. listen_thread.join();
  11013. ASSERT_FALSE(svr.is_running());
  11014. });
  11015. svr.wait_until_ready();
  11016. Client cli("localhost", PORT);
  11017. {
  11018. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11019. size_t /*data_length*/) { return false; });
  11020. ASSERT_FALSE(res);
  11021. }
  11022. {
  11023. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11024. size_t /*data_length*/) { return false; });
  11025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11026. }
  11027. }
  11028. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11029. // A provider that reports success without writing anything and without
  11030. // calling done() used to be handed the same offset and length again on every
  11031. // pass, so it spun for as long as the peer stayed connected.
  11032. Server svr;
  11033. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("ok", "text/plain");
  11035. });
  11036. auto port = svr.bind_to_any_port(HOST);
  11037. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11038. auto se = detail::scope_exit([&] {
  11039. svr.stop();
  11040. listen_thread.join();
  11041. ASSERT_FALSE(svr.is_running());
  11042. });
  11043. svr.wait_until_ready();
  11044. std::atomic<int> call_count{0};
  11045. Client cli(HOST, port);
  11046. auto res = cli.Post(
  11047. "/", 1024,
  11048. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11049. // Give up after enough passes to show the spin, so that losing the
  11050. // check below fails this test instead of hanging it.
  11051. return ++call_count < 100;
  11052. },
  11053. "text/plain");
  11054. ASSERT_FALSE(res);
  11055. EXPECT_EQ(Error::Write, res.error());
  11056. EXPECT_EQ(1, call_count.load());
  11057. }
  11058. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11059. // A writer only has to assign `write`. The other three used to be left as
  11060. // empty std::functions, so a provider calling one threw
  11061. // std::bad_function_call out of the thread running it and took the whole
  11062. // process down.
  11063. DataSink sink;
  11064. std::string written;
  11065. sink.write = [&](const char *data, size_t data_len) {
  11066. written.append(data, data_len);
  11067. return true;
  11068. };
  11069. EXPECT_TRUE(sink.is_writable());
  11070. sink.done();
  11071. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11072. EXPECT_TRUE(written.empty());
  11073. }
  11074. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11075. // A sink that cannot carry trailers still has to finish.
  11076. DataSink sink;
  11077. auto done_count = 0;
  11078. sink.done = [&]() { done_count++; };
  11079. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11080. EXPECT_EQ(1, done_count);
  11081. }
  11082. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11083. Server svr;
  11084. const std::string body(4096, 'x');
  11085. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11086. res.set_content_provider(body.size(), "text/plain",
  11087. [&](size_t offset, size_t length, DataSink &sink) {
  11088. sink.write(body.data() + offset, length);
  11089. sink.done();
  11090. return true;
  11091. });
  11092. });
  11093. auto port = svr.bind_to_any_port(HOST);
  11094. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11095. auto se = detail::scope_exit([&] {
  11096. svr.stop();
  11097. listen_thread.join();
  11098. ASSERT_FALSE(svr.is_running());
  11099. });
  11100. svr.wait_until_ready();
  11101. Client cli(HOST, port);
  11102. auto res = cli.Get("/");
  11103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11104. EXPECT_EQ(StatusCode::OK_200, res->status);
  11105. EXPECT_EQ(body, res->body);
  11106. }
  11107. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11108. Server svr;
  11109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11110. res.set_content_provider(
  11111. 1024, "text/plain",
  11112. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11113. sink.write("hello", 5);
  11114. sink.done(); // short of the 1024 bytes the response promised
  11115. return true;
  11116. });
  11117. });
  11118. auto port = svr.bind_to_any_port(HOST);
  11119. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11120. auto se = detail::scope_exit([&] {
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli(HOST, port);
  11127. cli.set_read_timeout(5, 0);
  11128. // The response is short of its Content-Length, so the client cannot read a
  11129. // complete body. What matters is that this returns at all: a no-op done()
  11130. // would leave the writer looping over a provider that never makes progress.
  11131. auto res = cli.Get("/");
  11132. EXPECT_FALSE(res);
  11133. }
  11134. // Read as the next response by a peer that sees it after a framed body.
  11135. static const std::string smuggled_response =
  11136. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11137. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11138. Server svr;
  11139. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11140. res.set_content_provider(
  11141. 5, "text/plain",
  11142. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11143. auto data = "AAAAA" + smuggled_response;
  11144. sink.write(data.data(), data.size());
  11145. return true;
  11146. });
  11147. });
  11148. thread t = thread([&] { svr.listen(HOST, PORT); });
  11149. auto se = detail::scope_exit([&] {
  11150. svr.stop();
  11151. t.join();
  11152. ASSERT_FALSE(svr.is_running());
  11153. });
  11154. svr.wait_until_ready();
  11155. std::string resp;
  11156. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11157. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11158. resp.clear();
  11159. ASSERT_TRUE(send_request(
  11160. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11161. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11162. }
  11163. TEST(NoContentTest, BodyIsNotSent) {
  11164. Server svr;
  11165. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11166. res.status = StatusCode::NoContent_204;
  11167. res.set_content(smuggled_response, "text/plain");
  11168. });
  11169. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11170. res.status = StatusCode::NotModified_304;
  11171. res.set_chunked_content_provider(
  11172. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11173. sink.write(smuggled_response.data(), smuggled_response.size());
  11174. sink.done();
  11175. return true;
  11176. });
  11177. });
  11178. thread t = thread([&] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. t.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. for (auto path : {"/204", "/304"}) {
  11186. std::string resp;
  11187. ASSERT_TRUE(send_request(
  11188. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11189. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11190. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11191. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11192. }
  11193. }
  11194. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11195. Server svr;
  11196. std::atomic<bool> smuggled(false);
  11197. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11198. res.set_content("ok", "text/plain");
  11199. });
  11200. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11201. smuggled = true;
  11202. });
  11203. auto port = svr.bind_to_any_port(HOST);
  11204. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11205. auto se = detail::scope_exit([&] {
  11206. svr.stop();
  11207. listen_thread.join();
  11208. ASSERT_FALSE(svr.is_running());
  11209. });
  11210. svr.wait_until_ready();
  11211. // What follows the body would be read as the next request.
  11212. Client cli(HOST, port);
  11213. auto res = cli.Post(
  11214. "/", 5,
  11215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11216. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11217. sink.write(data.data(), data.size());
  11218. return true;
  11219. },
  11220. "text/plain");
  11221. ASSERT_FALSE(res);
  11222. EXPECT_EQ(Error::Write, res.error());
  11223. EXPECT_FALSE(smuggled);
  11224. }
  11225. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11226. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11227. // The compressed path builds the whole body before connecting, so this
  11228. // fails client-side and never reaches a server.
  11229. Client cli(HOST, PORT);
  11230. cli.set_compress(true);
  11231. auto res = cli.Post(
  11232. "/", 1024,
  11233. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11234. sink.write("hello", 5);
  11235. sink.done(); // short of the 1024 bytes the request announced
  11236. return true;
  11237. },
  11238. "text/plain");
  11239. ASSERT_FALSE(res);
  11240. EXPECT_EQ(Error::Write, res.error());
  11241. }
  11242. #endif
  11243. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11244. Server svr;
  11245. svr.set_error_handler([](Request const &, Response &res) -> void {
  11246. res.set_chunked_content_provider(
  11247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11248. sink.os << "hello";
  11249. sink.os << "world";
  11250. sink.done();
  11251. return true;
  11252. });
  11253. });
  11254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. Client cli("localhost", PORT);
  11262. auto res = cli.Get("/");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11265. EXPECT_EQ("helloworld", res->body);
  11266. }
  11267. // A body set after a content provider must replace it, not be sent through it.
  11268. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11269. Server svr;
  11270. svr.set_mount_point("/", "./www");
  11271. svr.set_file_request_handler([](const Request &req, Response &res) {
  11272. if (req.path == "/dir/test.html") {
  11273. res.status = StatusCode::Forbidden_403;
  11274. res.set_content(std::string(5000, 'D'), "text/plain");
  11275. } else if (req.path == "/file") {
  11276. res.status = StatusCode::Forbidden_403;
  11277. res.body = "Denied";
  11278. }
  11279. });
  11280. auto port = svr.bind_to_any_port(HOST);
  11281. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. });
  11287. svr.wait_until_ready();
  11288. Client cli(HOST, port);
  11289. {
  11290. auto res = cli.Get("/dir/test.html");
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11293. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11294. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11295. }
  11296. {
  11297. auto res = cli.Get("/file");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11300. EXPECT_EQ("Denied", res->body);
  11301. }
  11302. {
  11303. auto res = cli.Get("/dir/index.html");
  11304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11305. EXPECT_EQ(StatusCode::OK_200, res->status);
  11306. EXPECT_EQ(0U, res->body.find("<html>"));
  11307. }
  11308. }
  11309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11310. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11311. Server svr;
  11312. std::vector<bool> released;
  11313. std::mutex released_mutex;
  11314. auto releaser = [&](bool success) {
  11315. std::lock_guard<std::mutex> guard(released_mutex);
  11316. released.push_back(success);
  11317. };
  11318. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11319. return sink.write(&"hello"[offset], length);
  11320. };
  11321. svr.Get("/sized", [&](const Request &, Response &res) {
  11322. res.status = StatusCode::NotFound_404;
  11323. res.set_content_provider(5, "text/plain", provider, releaser);
  11324. });
  11325. svr.Get("/chunked", [&](const Request &, Response &res) {
  11326. res.status = StatusCode::ServiceUnavailable_503;
  11327. res.set_chunked_content_provider(
  11328. "text/plain",
  11329. [](size_t, DataSink &sink) {
  11330. sink.os << "chunk";
  11331. sink.done();
  11332. return true;
  11333. },
  11334. releaser);
  11335. });
  11336. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11337. res.set_content_provider(5, "text/plain", provider, releaser);
  11338. throw std::runtime_error("after the provider");
  11339. });
  11340. svr.set_error_handler([](const Request &req, Response &res) {
  11341. // Leave the exception handler's content to it.
  11342. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11343. res.set_content(std::string(1000, 'E'), "text/html");
  11344. return Server::HandlerResponse::Handled;
  11345. });
  11346. svr.set_exception_handler(
  11347. [](const Request &, Response &res, std::exception_ptr) {
  11348. res.status = StatusCode::InternalServerError_500;
  11349. res.set_content(std::string(1000, 'X'), "text/html");
  11350. });
  11351. auto port = svr.bind_to_any_port(HOST);
  11352. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. t.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, port);
  11360. {
  11361. auto res = cli.Get("/sized");
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11364. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11365. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11366. }
  11367. {
  11368. auto res = cli.Get("/chunked");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11371. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11373. }
  11374. {
  11375. auto res = cli.Get("/throw");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11378. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11379. }
  11380. std::lock_guard<std::mutex> guard(released_mutex);
  11381. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11382. }
  11383. #endif
  11384. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11385. Server svr;
  11386. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11387. return sink.write(&"abc"[offset], length);
  11388. };
  11389. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11390. res.set_file_content("./www/dir/test.html");
  11391. res.set_content("body", "text/plain");
  11392. });
  11393. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11394. res.set_content(std::string(100, 'B'), "text/plain");
  11395. res.set_file_content("./www/dir/test.html");
  11396. });
  11397. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11398. res.set_content(std::string(100, 'B'), "text/plain");
  11399. res.set_content_provider(3, "text/x-provider", abc);
  11400. });
  11401. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11402. res.set_content_provider(3, "text/x-provider", abc);
  11403. res.set_content(std::string(100, 'B'), "text/plain");
  11404. });
  11405. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11406. res.set_content_provider(3, "text/x-provider", abc);
  11407. res.set_file_content("./www/dir/test.html", "text/x-file");
  11408. });
  11409. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11410. res.set_file_content("./www/dir/test.html");
  11411. res.set_header("Content-Type", "text/x-handler");
  11412. });
  11413. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11414. res.set_content_provider(3, "text/plain", abc);
  11415. res.body = "direct";
  11416. });
  11417. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11418. res.set_file_content("./www/dir/test.html");
  11419. res.body = "direct";
  11420. });
  11421. auto port = svr.bind_to_any_port(HOST);
  11422. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11423. auto se = detail::scope_exit([&] {
  11424. svr.stop();
  11425. t.join();
  11426. ASSERT_FALSE(svr.is_running());
  11427. });
  11428. svr.wait_until_ready();
  11429. Client cli(HOST, port);
  11430. auto expect_body = [&](const char *path, const std::string &body,
  11431. const std::string &type) {
  11432. // Uncompressed, so Content-Length can be compared with the body.
  11433. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11434. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11435. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11436. EXPECT_EQ(body, res->body) << path;
  11437. EXPECT_EQ(std::to_string(body.size()),
  11438. res->get_header_value("Content-Length"))
  11439. << path;
  11440. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11441. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11442. };
  11443. expect_body("/file-then-body", "body", "text/plain");
  11444. expect_body("/body-then-file", "test.html", "text/html");
  11445. expect_body("/body-then-provider", "abc", "text/x-provider");
  11446. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11447. expect_body("/provider-then-file", "test.html", "text/x-file");
  11448. expect_body("/file-then-header", "test.html", "text/x-handler");
  11449. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11450. expect_body("/file-then-direct-body", "direct", "text/plain");
  11451. // Ranges are checked against the body, not the dropped provider.
  11452. {
  11453. auto res = cli.Get("/provider-then-direct-body",
  11454. Headers{{make_range_header({{1, 2}})}});
  11455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11457. EXPECT_EQ("ir", res->body);
  11458. }
  11459. {
  11460. auto res = cli.Get("/file-then-direct-body",
  11461. Headers{{make_range_header({{7, 8}})}});
  11462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11463. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11464. }
  11465. }
  11466. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11467. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11468. const char *path = "./truncated_while_served.txt";
  11469. const size_t size = 32 * 1024 * 1024;
  11470. {
  11471. std::ofstream f(path, std::ios::binary);
  11472. f << std::string(size, 'x');
  11473. }
  11474. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11475. // Over TLS, where the bytes are encrypted in this process rather than
  11476. // copied by send().
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. svr.Get("/file", [&](const Request &, Response &res) {
  11479. res.set_file_content(path, "text/plain");
  11480. });
  11481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. thread.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. // The file shrinks once the first bytes are in, as a rewrite in place
  11489. // would, and reading the mapping past its new end used to raise SIGBUS.
  11490. SSLClient cli(HOST, PORT);
  11491. cli.enable_server_certificate_verification(false);
  11492. size_t received = 0;
  11493. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11494. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11495. received += len;
  11496. return true;
  11497. });
  11498. EXPECT_FALSE(res);
  11499. EXPECT_LT(received, size);
  11500. }
  11501. #endif
  11502. // Forward declaration (see the base64_encode note).
  11503. namespace httplib {
  11504. namespace detail {
  11505. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11506. const std::string &content_type,
  11507. EncodingType encoding);
  11508. } // namespace detail
  11509. } // namespace httplib
  11510. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11511. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11512. ASSERT_TRUE(mm->is_open());
  11513. Response res;
  11514. detail::set_file_content_provider(res, mm, "text/html",
  11515. detail::EncodingType::None);
  11516. std::string out;
  11517. DataSink sink;
  11518. sink.write = [&](const char *d, size_t l) {
  11519. out.append(d, l);
  11520. return true;
  11521. };
  11522. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11523. EXPECT_EQ("test.html", out);
  11524. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11525. EXPECT_EQ("test.html", out);
  11526. }
  11527. TEST(LongPollingTest, ClientCloseDetection) {
  11528. Server svr;
  11529. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11530. res.set_chunked_content_provider(
  11531. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11532. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11533. sink.os << "hello";
  11534. auto count = 10;
  11535. while (count > 0 && sink.is_writable()) {
  11536. this_thread::sleep_for(chrono::milliseconds(10));
  11537. count--;
  11538. }
  11539. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11540. return true;
  11541. });
  11542. });
  11543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. listen_thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. Client cli("localhost", PORT);
  11551. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11552. EXPECT_EQ("hello", string(data, data_length));
  11553. return false; // close the socket immediately.
  11554. });
  11555. ASSERT_FALSE(res);
  11556. }
  11557. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11558. Server svr;
  11559. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11560. res.set_chunked_content_provider(
  11561. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11562. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11563. sink.os << "hello";
  11564. EXPECT_TRUE(sink.os.good());
  11565. // Wait for the client to close the connection
  11566. auto count = 10;
  11567. while (count > 0 && sink.is_writable()) {
  11568. this_thread::sleep_for(chrono::milliseconds(10));
  11569. count--;
  11570. }
  11571. // After client disconnect, write repeatedly until the socket
  11572. // write actually fails (small writes may be absorbed by the
  11573. // kernel buffer)
  11574. std::string chunk(1024, 'x');
  11575. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11576. sink.os << chunk;
  11577. }
  11578. EXPECT_TRUE(sink.os.fail());
  11579. return true;
  11580. });
  11581. });
  11582. auto port = svr.bind_to_any_port("localhost");
  11583. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. listen_thread.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. });
  11589. svr.wait_until_ready();
  11590. Client cli("localhost", port);
  11591. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11592. EXPECT_EQ("hello", string(data, data_length));
  11593. return false; // close the socket immediately.
  11594. });
  11595. ASSERT_FALSE(res);
  11596. }
  11597. TEST(GetWithParametersTest, GetWithParameters) {
  11598. Server svr;
  11599. svr.Get("/", [&](const Request &req, Response &) {
  11600. EXPECT_EQ("world", req.get_param_value("hello"));
  11601. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11602. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11603. });
  11604. svr.Get("/params", [&](const Request &req, Response &) {
  11605. EXPECT_EQ("world", req.get_param_value("hello"));
  11606. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11607. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11608. });
  11609. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11610. EXPECT_EQ("resource-id", req.matches[1]);
  11611. EXPECT_EQ("foo", req.get_param_value("param1"));
  11612. EXPECT_EQ("bar", req.get_param_value("param2"));
  11613. });
  11614. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11615. EXPECT_EQ("user-id", req.path_params.at("id"));
  11616. EXPECT_EQ("foo", req.get_param_value("param1"));
  11617. EXPECT_EQ("bar", req.get_param_value("param2"));
  11618. });
  11619. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. listen_thread.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. });
  11625. svr.wait_until_ready();
  11626. {
  11627. Client cli(HOST, PORT);
  11628. Params params;
  11629. params.emplace("hello", "world");
  11630. params.emplace("hello2", "world2");
  11631. params.emplace("hello3", "world3");
  11632. auto res = cli.Get("/", params, Headers{});
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ(StatusCode::OK_200, res->status);
  11635. }
  11636. {
  11637. Client cli(HOST, PORT);
  11638. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11640. EXPECT_EQ(StatusCode::OK_200, res->status);
  11641. }
  11642. {
  11643. Client cli(HOST, PORT);
  11644. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. EXPECT_EQ(StatusCode::OK_200, res->status);
  11647. }
  11648. {
  11649. Client cli(HOST, PORT);
  11650. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. EXPECT_EQ(StatusCode::OK_200, res->status);
  11653. }
  11654. }
  11655. TEST(GetWithParametersTest, GetWithParameters2) {
  11656. Server svr;
  11657. svr.Get("/", [&](const Request &req, Response &res) {
  11658. auto text = req.get_param_value("hello");
  11659. res.set_content(text, "text/plain");
  11660. });
  11661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11662. auto se = detail::scope_exit([&] {
  11663. svr.stop();
  11664. listen_thread.join();
  11665. ASSERT_FALSE(svr.is_running());
  11666. });
  11667. svr.wait_until_ready();
  11668. Client cli("localhost", PORT);
  11669. Params params;
  11670. params.emplace("hello", "world");
  11671. std::string body;
  11672. auto res = cli.Get("/", params, Headers{},
  11673. [&](const char *data, size_t data_length) {
  11674. body.append(data, data_length);
  11675. return true;
  11676. });
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. EXPECT_EQ(StatusCode::OK_200, res->status);
  11679. EXPECT_EQ("world", body);
  11680. }
  11681. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11682. Server svr;
  11683. svr.Get("/search", [&](const Request &req, Response &res) {
  11684. auto q = req.get_param_value("q");
  11685. res.set_content(q, "text/plain");
  11686. });
  11687. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. listen_thread.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. Client cli("localhost", PORT);
  11695. // Verify that Get(path, params) works without requiring Headers argument
  11696. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ(StatusCode::OK_200, res->status);
  11699. EXPECT_EQ("cpp-httplib", res->body);
  11700. }
  11701. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11702. auto host = "httpbingo.org";
  11703. auto path = std::string{"/range/32"};
  11704. #ifdef CPPHTTPLIB_SSL_ENABLED
  11705. SSLClient cli(host);
  11706. #else
  11707. Client cli(host);
  11708. #endif
  11709. cli.set_default_headers({make_range_header({{1, 10}})});
  11710. cli.set_connection_timeout(5);
  11711. {
  11712. auto res = cli.Get(path);
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ("bcdefghijk", res->body);
  11715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11716. }
  11717. {
  11718. auto res = cli.Get(path);
  11719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11720. EXPECT_EQ("bcdefghijk", res->body);
  11721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11722. }
  11723. }
  11724. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11725. Server svr;
  11726. svr.set_default_headers({{"Hello", "World"}});
  11727. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11728. res.set_content("ok", "text/plain");
  11729. });
  11730. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", PORT);
  11738. auto res = cli.Get("/");
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. EXPECT_EQ("ok", res->body);
  11742. EXPECT_EQ("World", res->get_header_value("Hello"));
  11743. }
  11744. #ifdef CPPHTTPLIB_SSL_ENABLED
  11745. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11747. ASSERT_TRUE(svr.is_valid());
  11748. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11749. std::this_thread::sleep_for(std::chrono::seconds(2));
  11750. res.set_content("a", "text/plain");
  11751. });
  11752. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11753. res.set_content("b", "text/plain");
  11754. });
  11755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11756. auto se = detail::scope_exit([&] {
  11757. svr.stop();
  11758. listen_thread.join();
  11759. ASSERT_FALSE(svr.is_running());
  11760. });
  11761. svr.wait_until_ready();
  11762. SSLClient cli("localhost", PORT);
  11763. cli.enable_server_certificate_verification(false);
  11764. cli.set_keep_alive(true);
  11765. cli.set_read_timeout(std::chrono::seconds(1));
  11766. auto resa = cli.Get("/a");
  11767. ASSERT_TRUE(!resa);
  11768. EXPECT_EQ(Error::Read, resa.error());
  11769. auto resb = cli.Get("/b");
  11770. ASSERT_TRUE(resb);
  11771. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11772. EXPECT_EQ("b", resb->body);
  11773. }
  11774. // Closing an idle keep-alive connection sends close_notify and returns. The
  11775. // server must not wait for the client's close_notify: an idle client never
  11776. // sends one, so the worker would be held until the read timeout expires, and
  11777. // stop() would wait for it.
  11778. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11780. ASSERT_TRUE(svr.is_valid());
  11781. svr.set_keep_alive_timeout(1);
  11782. svr.set_read_timeout(10, 0);
  11783. svr.Get("/", [](const Request &, Response &res) {
  11784. res.set_content("ok", "text/plain");
  11785. });
  11786. auto port = svr.bind_to_any_port(HOST);
  11787. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11788. auto se = detail::scope_exit([&] {
  11789. if (listen_thread.joinable()) {
  11790. svr.stop();
  11791. listen_thread.join();
  11792. }
  11793. });
  11794. svr.wait_until_ready();
  11795. SSLClient cli(HOST, port);
  11796. cli.enable_server_certificate_verification(false);
  11797. cli.set_keep_alive(true);
  11798. auto res = cli.Get("/");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. EXPECT_EQ(StatusCode::OK_200, res->status);
  11801. // Stay idle past the keep-alive timeout so the server closes the connection.
  11802. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11803. auto start = std::chrono::steady_clock::now();
  11804. svr.stop();
  11805. listen_thread.join();
  11806. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11807. std::chrono::steady_clock::now() - start)
  11808. .count();
  11809. EXPECT_LT(elapsed, 3000);
  11810. }
  11811. #endif
  11812. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11813. protected:
  11814. ServerTestWithAI_PASSIVE()
  11815. : cli_(HOST, PORT)
  11816. #ifdef CPPHTTPLIB_SSL_ENABLED
  11817. ,
  11818. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11819. #endif
  11820. {
  11821. #ifdef CPPHTTPLIB_SSL_ENABLED
  11822. cli_.enable_server_certificate_verification(false);
  11823. #endif
  11824. }
  11825. virtual void SetUp() {
  11826. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11827. res.set_content("Hello World!", "text/plain");
  11828. });
  11829. t_ = thread(
  11830. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11831. svr_.wait_until_ready();
  11832. }
  11833. virtual void TearDown() {
  11834. svr_.stop();
  11835. t_.join();
  11836. }
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. SSLClient cli_;
  11839. SSLServer svr_;
  11840. #else
  11841. Client cli_;
  11842. Server svr_;
  11843. #endif
  11844. thread t_;
  11845. };
  11846. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11847. auto res = cli_.Get("/hi");
  11848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11849. EXPECT_EQ(StatusCode::OK_200, res->status);
  11850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11851. EXPECT_EQ("Hello World!", res->body);
  11852. }
  11853. class ServerUpDownTest : public ::testing::Test {
  11854. protected:
  11855. ServerUpDownTest() : cli_(HOST, PORT) {}
  11856. virtual void SetUp() {
  11857. t_ = thread([&]() {
  11858. svr_.bind_to_any_port(HOST);
  11859. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11860. ASSERT_TRUE(svr_.listen_after_bind());
  11861. });
  11862. svr_.wait_until_ready();
  11863. }
  11864. virtual void TearDown() {
  11865. svr_.stop();
  11866. t_.join();
  11867. }
  11868. Client cli_;
  11869. Server svr_;
  11870. thread t_;
  11871. };
  11872. TEST_F(ServerUpDownTest, QuickStartStop) {
  11873. // Should not crash, especially when run with
  11874. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11875. }
  11876. class PayloadMaxLengthTest : public ::testing::Test {
  11877. protected:
  11878. PayloadMaxLengthTest()
  11879. : cli_(HOST, PORT)
  11880. #ifdef CPPHTTPLIB_SSL_ENABLED
  11881. ,
  11882. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11883. #endif
  11884. {
  11885. #ifdef CPPHTTPLIB_SSL_ENABLED
  11886. cli_.enable_server_certificate_verification(false);
  11887. #endif
  11888. }
  11889. virtual void SetUp() {
  11890. svr_.set_payload_max_length(8);
  11891. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11892. res.set_content("test", "text/plain");
  11893. });
  11894. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11895. svr_.wait_until_ready();
  11896. }
  11897. virtual void TearDown() {
  11898. svr_.stop();
  11899. t_.join();
  11900. }
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. SSLClient cli_;
  11903. SSLServer svr_;
  11904. #else
  11905. Client cli_;
  11906. Server svr_;
  11907. #endif
  11908. thread t_;
  11909. };
  11910. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11911. auto res = cli_.Post("/test", "123456789", "text/plain");
  11912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11913. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11914. res = cli_.Post("/test", "12345678", "text/plain");
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. }
  11918. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11919. // Test chunked encoding with payload exceeding the 8-byte limit
  11920. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11921. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11924. }
  11925. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11926. // Test chunked encoding with payload within the 8-byte limit
  11927. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11928. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11930. EXPECT_EQ(StatusCode::OK_200, res->status);
  11931. }
  11932. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11933. // Test using send_request to send chunked data exceeding payload limit
  11934. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11935. "Host: " +
  11936. std::string(HOST) + ":" + std::to_string(PORT) +
  11937. "\r\n"
  11938. "Transfer-Encoding: chunked\r\n"
  11939. "Connection: close\r\n"
  11940. "\r\n"
  11941. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11942. "0123456789\r\n"
  11943. "0\r\n" // End chunk
  11944. "\r\n";
  11945. std::string response;
  11946. bool result = send_request(1, chunked_request, &response);
  11947. if (!result) {
  11948. // If send_request fails, it might be because the server closed the
  11949. // connection due to payload limit enforcement, which is acceptable
  11950. SUCCEED()
  11951. << "Server rejected oversized chunked request (connection closed)";
  11952. } else {
  11953. // If we got a response, check if it's an error response or connection was
  11954. // closed early Short response length indicates connection was closed due to
  11955. // payload limit
  11956. if (response.length() <= 10) {
  11957. SUCCEED() << "Server closed connection for oversized chunked request";
  11958. } else {
  11959. // Check for error status codes
  11960. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11961. response.find("Payload Too Large") != std::string::npos ||
  11962. response.find("400") != std::string::npos);
  11963. }
  11964. }
  11965. }
  11966. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11967. // Test request without Content-Length header exceeding payload limit
  11968. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11969. "Host: " +
  11970. std::string(HOST) + ":" +
  11971. std::to_string(PORT) +
  11972. "\r\n"
  11973. "Connection: close\r\n"
  11974. "\r\n";
  11975. // Add payload exceeding the 8-byte limit
  11976. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11977. request_without_content_length += large_payload;
  11978. std::string response;
  11979. bool result = send_request(1, request_without_content_length, &response);
  11980. if (!result) {
  11981. // If send_request fails, server likely closed connection due to payload
  11982. // limit
  11983. SUCCEED() << "Server rejected oversized request without Content-Length "
  11984. "(connection closed)";
  11985. } else {
  11986. // Check if server responded with error or closed connection early
  11987. if (response.length() <= 10) {
  11988. SUCCEED() << "Server closed connection for oversized request without "
  11989. "Content-Length";
  11990. } else {
  11991. // Check for error status codes
  11992. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11993. response.find("Payload Too Large") != std::string::npos ||
  11994. response.find("400") != std::string::npos);
  11995. }
  11996. }
  11997. }
  11998. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11999. // Test request without Content-Length header within payload limit
  12000. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12001. "Host: " +
  12002. std::string(HOST) + ":" +
  12003. std::to_string(PORT) +
  12004. "\r\n"
  12005. "Connection: close\r\n"
  12006. "\r\n";
  12007. // Add payload within the 8-byte limit
  12008. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12009. request_without_content_length += small_payload;
  12010. std::string response;
  12011. bool result = send_request(1, request_without_content_length, &response);
  12012. // For requests without Content-Length, the server may have different behavior
  12013. // The key is that it should not reject due to payload limit for small
  12014. // payloads
  12015. if (result) {
  12016. // Check for any HTTP response (success or error, but not connection closed)
  12017. if (response.length() > 10) {
  12018. SUCCEED()
  12019. << "Server processed request without Content-Length within limit";
  12020. } else {
  12021. // Short response might indicate connection closed, which is acceptable
  12022. SUCCEED() << "Server closed connection for request without "
  12023. "Content-Length (acceptable behavior)";
  12024. }
  12025. } else {
  12026. // Connection failure might be due to protocol requirements
  12027. SUCCEED() << "Connection issue with request without Content-Length "
  12028. "(environment-specific)";
  12029. }
  12030. }
  12031. class LargePayloadMaxLengthTest : public ::testing::Test {
  12032. protected:
  12033. LargePayloadMaxLengthTest()
  12034. : cli_(HOST, PORT)
  12035. #ifdef CPPHTTPLIB_SSL_ENABLED
  12036. ,
  12037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12038. #endif
  12039. {
  12040. #ifdef CPPHTTPLIB_SSL_ENABLED
  12041. cli_.enable_server_certificate_verification(false);
  12042. #endif
  12043. }
  12044. virtual void SetUp() {
  12045. // Set 10MB payload limit
  12046. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12047. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12048. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12049. res.set_content("Large payload test", "text/plain");
  12050. });
  12051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12052. svr_.wait_until_ready();
  12053. }
  12054. virtual void TearDown() {
  12055. svr_.stop();
  12056. t_.join();
  12057. }
  12058. #ifdef CPPHTTPLIB_SSL_ENABLED
  12059. SSLClient cli_;
  12060. SSLServer svr_;
  12061. #else
  12062. Client cli_;
  12063. Server svr_;
  12064. #endif
  12065. thread t_;
  12066. };
  12067. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12068. // Test chunked encoding with payload within 10MB limit
  12069. std::string medium_payload(5 * 1024 * 1024,
  12070. 'A'); // 5MB payload, within 10MB limit
  12071. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12076. // Test chunked encoding with payload exceeding 10MB limit
  12077. std::string large_payload(12 * 1024 * 1024,
  12078. 'B'); // 12MB payload, exceeds 10MB limit
  12079. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12080. // Server may either return 413 or close the connection
  12081. if (res) {
  12082. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12083. } else {
  12084. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12085. }
  12086. }
  12087. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12088. // Test request without Content-Length header within 10MB limit
  12089. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12090. "Host: " +
  12091. std::string(HOST) + ":" +
  12092. std::to_string(PORT) +
  12093. "\r\n"
  12094. "Connection: close\r\n"
  12095. "\r\n";
  12096. // Add 1MB payload (within 10MB limit)
  12097. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12098. request_without_content_length += medium_payload;
  12099. std::string response;
  12100. bool result = send_request(5, request_without_content_length, &response);
  12101. if (result) {
  12102. // Should get a proper HTTP response for payloads within limit
  12103. if (response.length() > 10) {
  12104. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12105. "10MB limit";
  12106. } else {
  12107. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12108. "Content-Length)";
  12109. }
  12110. } else {
  12111. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12112. }
  12113. }
  12114. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12115. // Test request without Content-Length header exceeding 10MB limit
  12116. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12117. "Host: " +
  12118. std::string(HOST) + ":" +
  12119. std::to_string(PORT) +
  12120. "\r\n"
  12121. "Connection: close\r\n"
  12122. "\r\n";
  12123. // Add 12MB payload (exceeds 10MB limit)
  12124. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12125. request_without_content_length += large_payload;
  12126. std::string response;
  12127. bool result = send_request(10, request_without_content_length, &response);
  12128. if (!result) {
  12129. // Server should close connection due to payload limit
  12130. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12131. "(connection closed)";
  12132. } else {
  12133. // Check for error response
  12134. if (response.length() <= 10) {
  12135. SUCCEED()
  12136. << "Server closed connection for 12MB request exceeding 10MB limit";
  12137. } else {
  12138. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12139. response.find("Payload Too Large") != std::string::npos ||
  12140. response.find("400") != std::string::npos);
  12141. }
  12142. }
  12143. }
  12144. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12145. Server svr;
  12146. svr.Get("/", [](const Request &, Response &res) {
  12147. // Claims the most the client accepts, far more than it sends, then drops
  12148. // the connection.
  12149. res.set_content_provider(std::string().max_size(), "text/plain",
  12150. [](size_t, size_t, DataSink &sink) {
  12151. sink.write("abc", 3);
  12152. return false;
  12153. });
  12154. });
  12155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12156. auto se = detail::scope_exit([&] {
  12157. svr.stop();
  12158. thread.join();
  12159. ASSERT_FALSE(svr.is_running());
  12160. });
  12161. svr.wait_until_ready();
  12162. Client cli(HOST, PORT);
  12163. cli.set_payload_max_length(0);
  12164. EXPECT_FALSE(cli.Get("/"));
  12165. }
  12166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12167. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12168. // path.
  12169. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12170. Server svr;
  12171. const size_t LIMIT = 64 * 1024; // 64KB
  12172. svr.set_payload_max_length(LIMIT);
  12173. size_t total = 0;
  12174. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12175. const ContentReader &content_reader) {
  12176. content_reader([&](const char * /*data*/, size_t len) {
  12177. total += len;
  12178. return true;
  12179. });
  12180. res.status = 200;
  12181. res.set_content("stream_ok", "text/plain");
  12182. });
  12183. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12184. auto se = detail::scope_exit([&] {
  12185. svr.stop();
  12186. thread.join();
  12187. ASSERT_FALSE(svr.is_running());
  12188. });
  12189. svr.wait_until_ready();
  12190. // Prepare 256KB raw data and gzip-compress it
  12191. std::string raw(256 * 1024, 'A');
  12192. std::string gz;
  12193. {
  12194. z_stream zs{};
  12195. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12196. Z_DEFAULT_STRATEGY);
  12197. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12198. zs.avail_in = static_cast<uInt>(raw.size());
  12199. char outbuf[4096];
  12200. int ret;
  12201. do {
  12202. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12203. zs.avail_out = sizeof(outbuf);
  12204. ret = deflate(&zs, Z_FINISH);
  12205. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12206. } while (ret != Z_STREAM_END);
  12207. deflateEnd(&zs);
  12208. }
  12209. Client cli(HOST, PORT);
  12210. cli.set_connection_timeout(std::chrono::seconds(5));
  12211. Headers headers = {{"Content-Encoding", "gzip"}};
  12212. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12213. "application/octet-stream");
  12214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12215. // Server must reject oversized decompressed payloads with 413.
  12216. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12217. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12218. EXPECT_LE(total, LIMIT);
  12219. }
  12220. #ifndef CPPHTTPLIB_SSL_ENABLED
  12221. // For a request with neither Content-Length nor Transfer-Encoding, the
  12222. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12223. // compressed wire bytes straight to the ContentReader without ever routing
  12224. // them through the decompressor, so payload_max_length_ only bounded the
  12225. // compressed size on the wire, not the decompressed size.
  12226. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12227. Server svr;
  12228. const size_t LIMIT = 64 * 1024; // 64KB
  12229. svr.set_payload_max_length(LIMIT);
  12230. size_t total = 0;
  12231. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12232. const ContentReader &content_reader) {
  12233. content_reader([&](const char * /*data*/, size_t len) {
  12234. total += len;
  12235. return true;
  12236. });
  12237. res.status = 200;
  12238. res.set_content("stream_ok", "text/plain");
  12239. });
  12240. auto port = svr.bind_to_any_port(HOST);
  12241. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12242. auto se = detail::scope_exit([&] {
  12243. svr.stop();
  12244. thread.join();
  12245. ASSERT_FALSE(svr.is_running());
  12246. });
  12247. svr.wait_until_ready();
  12248. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12249. // StreamingGzipDecompression test above.
  12250. std::string raw(256 * 1024, 'A');
  12251. std::string gz;
  12252. {
  12253. httplib::detail::gzip_compressor compressor;
  12254. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12255. [&](const char *chunk, size_t len) {
  12256. gz.append(chunk, len);
  12257. return true;
  12258. });
  12259. ASSERT_TRUE(result);
  12260. }
  12261. // Send the gzip body over raw TCP with neither Content-Length nor
  12262. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12263. // kicks in.
  12264. std::string req = "POST /stream HTTP/1.1\r\n"
  12265. "Host: " +
  12266. std::string(HOST) + ":" + std::to_string(port) +
  12267. "\r\n"
  12268. "Content-Encoding: gzip\r\n"
  12269. "Connection: close\r\n"
  12270. "\r\n" +
  12271. gz;
  12272. std::string response;
  12273. ASSERT_TRUE(send_request(5, req, &response, port));
  12274. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12275. EXPECT_LE(total, LIMIT);
  12276. }
  12277. #endif
  12278. #endif
  12279. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12280. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12281. // the payload must be passed through untouched instead of being rejected.
  12282. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12283. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12284. Server svr;
  12285. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12286. res.set_content(body, "image/jpeg");
  12287. res.set_header("Content-Encoding", "UTF-8");
  12288. });
  12289. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12290. res.set_content(body, "image/jpeg");
  12291. res.set_header("Content-Encoding", "identity");
  12292. });
  12293. svr.Post("/echo", [](const Request &req, Response &res) {
  12294. res.set_content(req.body, "image/jpeg");
  12295. });
  12296. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12297. auto se = detail::scope_exit([&] {
  12298. svr.stop();
  12299. t.join();
  12300. ASSERT_FALSE(svr.is_running());
  12301. });
  12302. svr.wait_until_ready();
  12303. Client cli(HOST, PORT);
  12304. {
  12305. auto res = cli.Get("/image");
  12306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12307. EXPECT_EQ(StatusCode::OK_200, res->status);
  12308. EXPECT_EQ(body, res->body);
  12309. }
  12310. {
  12311. auto res = cli.Get("/identity");
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. EXPECT_EQ(body, res->body);
  12315. }
  12316. {
  12317. // The same applies to a request body reaching the server.
  12318. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12319. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12321. EXPECT_EQ(StatusCode::OK_200, res->status);
  12322. EXPECT_EQ(body, res->body);
  12323. }
  12324. }
  12325. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12326. // gzip-encoded response even when the build has no zlib support.
  12327. static const char GZIPPED_HELLO_WORLD[] = {
  12328. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12329. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12330. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12331. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12332. // A content coding is a whole token, not something the field value merely
  12333. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12334. // as "fibre" look like Brotli, and turned a multi-coding value like
  12335. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12336. // it was never meant to see.
  12337. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12338. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12339. Server svr;
  12340. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12341. res.set_content(body, "image/jpeg");
  12342. res.set_header("Content-Encoding", "fibre");
  12343. });
  12344. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12345. res.set_content(body, "image/jpeg");
  12346. res.set_header("Content-Encoding", "gzip, br");
  12347. });
  12348. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12349. res.set_content(body, "image/jpeg");
  12350. res.set_header("Content-Encoding", "x-zstd-ish");
  12351. });
  12352. auto port = svr.bind_to_any_port(HOST);
  12353. thread t = thread([&]() { svr.listen_after_bind(); });
  12354. auto se = detail::scope_exit([&] {
  12355. svr.stop();
  12356. t.join();
  12357. ASSERT_FALSE(svr.is_running());
  12358. });
  12359. svr.wait_until_ready();
  12360. Client cli(HOST, port);
  12361. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12362. auto res = cli.Get(path);
  12363. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12364. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12365. // Not a coding we recognize, so the payload comes back untouched
  12366. EXPECT_EQ(body, res->body) << path;
  12367. }
  12368. }
  12369. // A content coding cpp-httplib recognizes but was not built with must be
  12370. // reported as such. Handing the still-compressed payload back to the caller
  12371. // would silently corrupt it.
  12372. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12373. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12374. Server svr;
  12375. // "image/jpeg" keeps the server from applying a content coding of its own,
  12376. // so the hand-crafted Content-Encoding below survives.
  12377. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12378. res.set_content(gzipped, "image/jpeg");
  12379. res.set_header("Content-Encoding", "gzip");
  12380. });
  12381. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12382. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12383. res.set_content(gzipped, "image/jpeg");
  12384. res.set_header("Content-Encoding", "GZIP");
  12385. });
  12386. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12387. auto se = detail::scope_exit([&] {
  12388. svr.stop();
  12389. t.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. Client cli(HOST, PORT);
  12394. {
  12395. auto res = cli.Get("/gzipped");
  12396. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12398. EXPECT_EQ("Hello World!", res->body);
  12399. #else
  12400. ASSERT_FALSE(res);
  12401. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12402. #endif
  12403. }
  12404. {
  12405. // open_stream() must behave the same way.
  12406. auto handle = cli.open_stream("GET", "/gzipped");
  12407. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12408. ASSERT_TRUE(handle.is_valid());
  12409. std::string received;
  12410. char buf[256];
  12411. ssize_t n;
  12412. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12413. received.append(buf, static_cast<size_t>(n));
  12414. }
  12415. EXPECT_EQ("Hello World!", received);
  12416. #else
  12417. EXPECT_FALSE(handle.is_valid());
  12418. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12419. #endif
  12420. }
  12421. {
  12422. // A differently-cased coding must not be mistaken for an unknown one, or
  12423. // the body would be handed back still compressed.
  12424. auto res = cli.Get("/gzipped-uppercase");
  12425. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12427. EXPECT_EQ("Hello World!", res->body);
  12428. #else
  12429. ASSERT_FALSE(res);
  12430. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12431. #endif
  12432. }
  12433. }
  12434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12435. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12436. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12437. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12438. // body a second time and appending a second Content-Encoding field line, so
  12439. // clients that decode one coding per listed value handed back raw gzip bytes.
  12440. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12441. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12442. Server svr;
  12443. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12444. // keeps the server from applying a coding of its own.
  12445. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12446. res.set_content(gzipped, "text/plain");
  12447. res.set_header("Content-Encoding", "gzip");
  12448. });
  12449. auto port = svr.bind_to_any_port(HOST);
  12450. thread t = thread([&]() { svr.listen_after_bind(); });
  12451. auto se = detail::scope_exit([&] {
  12452. svr.stop();
  12453. t.join();
  12454. ASSERT_FALSE(svr.is_running());
  12455. });
  12456. svr.wait_until_ready();
  12457. Client cli(HOST, port);
  12458. Headers headers = {{"Accept-Encoding", "gzip"}};
  12459. auto res = cli.Get("/pre-gzipped", headers);
  12460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12461. EXPECT_EQ(StatusCode::OK_200, res->status);
  12462. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12463. EXPECT_EQ("Hello World!", res->body);
  12464. }
  12465. // A chunked provider settles its coding where the headers are written and
  12466. // reuses it at write time. Both ends of that have to hold: a handler's own
  12467. // Content-Encoding suppresses the coding, and a response without one is still
  12468. // compressed as it always was.
  12469. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12470. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12471. const std::string plain = "Hello World! Hello World! Hello World!";
  12472. Server svr;
  12473. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12474. res.set_header("Content-Encoding", "gzip");
  12475. res.set_chunked_content_provider(
  12476. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12477. sink.write(gzipped.data(), gzipped.size());
  12478. sink.done();
  12479. return true;
  12480. });
  12481. });
  12482. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12483. res.set_chunked_content_provider(
  12484. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12485. sink.write(plain.data(), plain.size());
  12486. sink.done();
  12487. return true;
  12488. });
  12489. });
  12490. auto port = svr.bind_to_any_port(HOST);
  12491. thread t = thread([&]() { svr.listen_after_bind(); });
  12492. auto se = detail::scope_exit([&] {
  12493. svr.stop();
  12494. t.join();
  12495. ASSERT_FALSE(svr.is_running());
  12496. });
  12497. svr.wait_until_ready();
  12498. Client cli(HOST, port);
  12499. Headers headers = {{"Accept-Encoding", "gzip"}};
  12500. {
  12501. auto res = cli.Get("/pre-gzipped", headers);
  12502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12503. EXPECT_EQ(StatusCode::OK_200, res->status);
  12504. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12505. EXPECT_EQ("Hello World!", res->body);
  12506. }
  12507. {
  12508. auto res = cli.Get("/negotiated", headers);
  12509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12510. EXPECT_EQ(StatusCode::OK_200, res->status);
  12511. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12512. EXPECT_EQ(plain, res->body);
  12513. }
  12514. }
  12515. #endif
  12516. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12517. // the same message as the comma-joined one, so both have to be read the same
  12518. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12519. // single gzip coding, and a body the sender says was encoded twice was handed
  12520. // back after one pass, still compressed but presented as decoded.
  12521. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12522. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12523. Server svr;
  12524. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12525. res.set_content(body, "image/jpeg");
  12526. res.headers.emplace("Content-Encoding", "gzip");
  12527. res.headers.emplace("Content-Encoding", "gzip");
  12528. });
  12529. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12530. res.set_content(body, "image/jpeg");
  12531. res.set_header("Content-Encoding", "gzip, gzip");
  12532. });
  12533. auto port = svr.bind_to_any_port(HOST);
  12534. thread t = thread([&]() { svr.listen_after_bind(); });
  12535. auto se = detail::scope_exit([&] {
  12536. svr.stop();
  12537. t.join();
  12538. ASSERT_FALSE(svr.is_running());
  12539. });
  12540. svr.wait_until_ready();
  12541. Client cli(HOST, port);
  12542. // Two codings is not something cpp-httplib decodes, so both representations
  12543. // take the pass-through path rather than one of them being gunzipped once.
  12544. for (const char *path : {"/split", "/joined"}) {
  12545. auto res = cli.Get(path);
  12546. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12547. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12548. EXPECT_EQ(body, res->body) << path;
  12549. }
  12550. }
  12551. // Regression test for DoS vulnerability: a malicious server sending a response
  12552. // without Content-Length header must not cause unbounded memory consumption on
  12553. // the client side. The client should stop reading after a reasonable limit,
  12554. // similar to the server-side set_payload_max_length protection.
  12555. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12556. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12557. #ifndef _WIN32
  12558. signal(SIGPIPE, SIG_IGN);
  12559. #endif
  12560. auto server_thread = std::thread([] {
  12561. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12563. default_socket_options(srv);
  12564. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12565. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12566. sockaddr_in addr{};
  12567. addr.sin_family = AF_INET;
  12568. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12570. int opt = 1;
  12571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12572. #ifdef _WIN32
  12573. reinterpret_cast<const char *>(&opt),
  12574. #else
  12575. &opt,
  12576. #endif
  12577. sizeof(opt));
  12578. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12579. ::listen(srv, 1);
  12580. sockaddr_in cli_addr{};
  12581. socklen_t cli_len = sizeof(cli_addr);
  12582. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12583. if (cli != INVALID_SOCKET) {
  12584. char buf[4096];
  12585. ::recv(cli, buf, sizeof(buf), 0);
  12586. // Malicious response: no Content-Length, no chunked encoding
  12587. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12588. "Connection: close\r\n"
  12589. "\r\n";
  12590. ::send(cli,
  12591. #ifdef _WIN32
  12592. static_cast<const char *>(response_header.c_str()),
  12593. static_cast<int>(response_header.size()),
  12594. #else
  12595. response_header.c_str(), response_header.size(),
  12596. #endif
  12597. 0);
  12598. // Send 10MB of data
  12599. std::string chunk(64 * 1024, 'A');
  12600. size_t total_sent = 0;
  12601. while (total_sent < MALICIOUS_DATA_SIZE) {
  12602. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12603. auto sent = ::send(cli,
  12604. #ifdef _WIN32
  12605. static_cast<const char *>(chunk.c_str()),
  12606. static_cast<int>(to_send),
  12607. #else
  12608. chunk.c_str(), to_send,
  12609. #endif
  12610. 0);
  12611. if (sent <= 0) break;
  12612. total_sent += static_cast<size_t>(sent);
  12613. }
  12614. detail::close_socket(cli);
  12615. }
  12616. detail::close_socket(srv);
  12617. });
  12618. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12619. size_t total_read = 0;
  12620. {
  12621. Client cli("127.0.0.1", PORT + 2);
  12622. cli.set_read_timeout(5, 0);
  12623. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12624. auto stream = cli.open_stream("GET", "/malicious");
  12625. ASSERT_TRUE(stream.is_valid());
  12626. char buffer[64 * 1024];
  12627. ssize_t n;
  12628. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12629. total_read += static_cast<size_t>(n);
  12630. }
  12631. } // StreamHandle and Client destroyed here, closing the socket
  12632. server_thread.join();
  12633. // With set_payload_max_length, the client must stop reading before consuming
  12634. // all 10MB. The read loop should be cut off at or near the configured limit.
  12635. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12636. << "Client read " << total_read << " bytes, exceeding the configured "
  12637. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12638. }
  12639. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12640. // the entire response body without truncation.
  12641. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12642. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12643. #ifndef _WIN32
  12644. signal(SIGPIPE, SIG_IGN);
  12645. #endif
  12646. auto server_thread = std::thread([] {
  12647. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12648. default_socket_options(srv);
  12649. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12650. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12651. sockaddr_in addr{};
  12652. addr.sin_family = AF_INET;
  12653. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12654. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12655. int opt = 1;
  12656. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12657. #ifdef _WIN32
  12658. reinterpret_cast<const char *>(&opt),
  12659. #else
  12660. &opt,
  12661. #endif
  12662. sizeof(opt));
  12663. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12664. ::listen(srv, 1);
  12665. sockaddr_in cli_addr{};
  12666. socklen_t cli_len = sizeof(cli_addr);
  12667. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12668. if (cli != INVALID_SOCKET) {
  12669. char buf[4096];
  12670. ::recv(cli, buf, sizeof(buf), 0);
  12671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12672. "Connection: close\r\n"
  12673. "\r\n";
  12674. ::send(cli,
  12675. #ifdef _WIN32
  12676. static_cast<const char *>(response_header.c_str()),
  12677. static_cast<int>(response_header.size()),
  12678. #else
  12679. response_header.c_str(), response_header.size(),
  12680. #endif
  12681. 0);
  12682. std::string chunk(64 * 1024, 'A');
  12683. size_t total_sent = 0;
  12684. while (total_sent < DATA_SIZE) {
  12685. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12686. auto sent = ::send(cli,
  12687. #ifdef _WIN32
  12688. static_cast<const char *>(chunk.c_str()),
  12689. static_cast<int>(to_send),
  12690. #else
  12691. chunk.c_str(), to_send,
  12692. #endif
  12693. 0);
  12694. if (sent <= 0) break;
  12695. total_sent += static_cast<size_t>(sent);
  12696. }
  12697. #ifdef _WIN32
  12698. ::shutdown(cli, SD_SEND);
  12699. #else
  12700. ::shutdown(cli, SHUT_WR);
  12701. #endif
  12702. // Drain until the client closes its end, ensuring all data is delivered
  12703. char drain[1024];
  12704. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12705. detail::close_socket(cli);
  12706. }
  12707. detail::close_socket(srv);
  12708. });
  12709. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12710. size_t total_read = 0;
  12711. {
  12712. Client cli("127.0.0.1", PORT + 2);
  12713. cli.set_read_timeout(5, 0);
  12714. cli.set_payload_max_length(0); // 0 means no limit
  12715. auto stream = cli.open_stream("GET", "/data");
  12716. ASSERT_TRUE(stream.is_valid());
  12717. char buffer[64 * 1024];
  12718. ssize_t n;
  12719. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12720. total_read += static_cast<size_t>(n);
  12721. }
  12722. }
  12723. server_thread.join();
  12724. EXPECT_EQ(total_read, DATA_SIZE)
  12725. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12726. << " bytes without truncation, but only read " << total_read << " bytes.";
  12727. }
  12728. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12729. // enormous Content-Length must not cause the client to pre-allocate a huge
  12730. // response body buffer. The reservation is capped at payload_max_length_, and
  12731. // the read itself fails when the body exceeds the limit.
  12732. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12733. #ifndef _WIN32
  12734. signal(SIGPIPE, SIG_IGN);
  12735. #endif
  12736. auto server_thread = std::thread([] {
  12737. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12738. default_socket_options(srv);
  12739. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12740. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12741. sockaddr_in addr{};
  12742. addr.sin_family = AF_INET;
  12743. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12744. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12745. int opt = 1;
  12746. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12747. #ifdef _WIN32
  12748. reinterpret_cast<const char *>(&opt),
  12749. #else
  12750. &opt,
  12751. #endif
  12752. sizeof(opt));
  12753. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12754. ::listen(srv, 1);
  12755. sockaddr_in cli_addr{};
  12756. socklen_t cli_len = sizeof(cli_addr);
  12757. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12758. if (cli != INVALID_SOCKET) {
  12759. char buf[4096];
  12760. ::recv(cli, buf, sizeof(buf), 0);
  12761. // Malicious response: claim a 20GB body but send only a tiny payload.
  12762. std::string response = "HTTP/1.1 200 OK\r\n"
  12763. "Content-Length: 20000000000\r\n"
  12764. "\r\n"
  12765. "abc";
  12766. ::send(cli,
  12767. #ifdef _WIN32
  12768. static_cast<const char *>(response.c_str()),
  12769. static_cast<int>(response.size()),
  12770. #else
  12771. response.c_str(), response.size(),
  12772. #endif
  12773. 0);
  12774. detail::close_socket(cli);
  12775. }
  12776. detail::close_socket(srv);
  12777. });
  12778. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12779. {
  12780. Client cli("127.0.0.1", PORT + 2);
  12781. cli.set_read_timeout(5, 0);
  12782. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12783. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12784. // (server claims more bytes than payload_max_length permits), but it must
  12785. // not exhaust memory before getting there.
  12786. auto res = cli.Get("/malicious");
  12787. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12788. }
  12789. server_thread.join();
  12790. }
  12791. // Verify that content_receiver bypasses the default payload_max_length,
  12792. // allowing streaming downloads larger than 100MB without requiring an explicit
  12793. // set_payload_max_length call.
  12794. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12795. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12796. #ifndef _WIN32
  12797. signal(SIGPIPE, SIG_IGN);
  12798. #endif
  12799. auto server_thread = std::thread([] {
  12800. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12801. default_socket_options(srv);
  12802. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12803. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12804. sockaddr_in addr{};
  12805. addr.sin_family = AF_INET;
  12806. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12807. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12808. int opt = 1;
  12809. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12810. #ifdef _WIN32
  12811. reinterpret_cast<const char *>(&opt),
  12812. #else
  12813. &opt,
  12814. #endif
  12815. sizeof(opt));
  12816. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12817. ::listen(srv, 1);
  12818. sockaddr_in cli_addr{};
  12819. socklen_t cli_len = sizeof(cli_addr);
  12820. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12821. if (cli != INVALID_SOCKET) {
  12822. char buf[4096];
  12823. ::recv(cli, buf, sizeof(buf), 0);
  12824. // Response with Content-Length larger than default 100MB limit
  12825. auto content_length = std::to_string(DATA_SIZE);
  12826. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12827. "Content-Length: " +
  12828. content_length +
  12829. "\r\n"
  12830. "Connection: close\r\n"
  12831. "\r\n";
  12832. ::send(cli,
  12833. #ifdef _WIN32
  12834. static_cast<const char *>(response_header.c_str()),
  12835. static_cast<int>(response_header.size()),
  12836. #else
  12837. response_header.c_str(), response_header.size(),
  12838. #endif
  12839. 0);
  12840. std::string chunk(64 * 1024, 'A');
  12841. size_t total_sent = 0;
  12842. while (total_sent < DATA_SIZE) {
  12843. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12844. auto sent = ::send(cli,
  12845. #ifdef _WIN32
  12846. static_cast<const char *>(chunk.c_str()),
  12847. static_cast<int>(to_send),
  12848. #else
  12849. chunk.c_str(), to_send,
  12850. #endif
  12851. 0);
  12852. if (sent <= 0) break;
  12853. total_sent += static_cast<size_t>(sent);
  12854. }
  12855. detail::close_socket(cli);
  12856. }
  12857. detail::close_socket(srv);
  12858. });
  12859. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12860. size_t total_received = 0;
  12861. {
  12862. Client cli("127.0.0.1", PORT + 2);
  12863. cli.set_read_timeout(10, 0);
  12864. // Do NOT call set_payload_max_length — use the default 100MB limit
  12865. auto res =
  12866. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12867. total_received += data_length;
  12868. return true;
  12869. });
  12870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12871. EXPECT_EQ(StatusCode::OK_200, res->status);
  12872. }
  12873. server_thread.join();
  12874. EXPECT_EQ(total_received, DATA_SIZE)
  12875. << "With content_receiver, the client should read all " << DATA_SIZE
  12876. << " bytes despite the default 100MB payload_max_length, but only read "
  12877. << total_received << " bytes.";
  12878. }
  12879. // Verify that an explicit set_payload_max_length smaller than the response is
  12880. // enforced even when a content_receiver is used.
  12881. TEST(ClientVulnerabilityTest,
  12882. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12883. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12884. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12885. #ifndef _WIN32
  12886. signal(SIGPIPE, SIG_IGN);
  12887. #endif
  12888. auto server_thread = std::thread([] {
  12889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12890. default_socket_options(srv);
  12891. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12892. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12893. sockaddr_in addr{};
  12894. addr.sin_family = AF_INET;
  12895. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12896. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12897. int opt = 1;
  12898. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12899. #ifdef _WIN32
  12900. reinterpret_cast<const char *>(&opt),
  12901. #else
  12902. &opt,
  12903. #endif
  12904. sizeof(opt));
  12905. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12906. ::listen(srv, 1);
  12907. sockaddr_in cli_addr{};
  12908. socklen_t cli_len = sizeof(cli_addr);
  12909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12910. if (cli != INVALID_SOCKET) {
  12911. char buf[4096];
  12912. ::recv(cli, buf, sizeof(buf), 0);
  12913. auto content_length = std::to_string(DATA_SIZE);
  12914. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12915. "Content-Length: " +
  12916. content_length +
  12917. "\r\n"
  12918. "Connection: close\r\n"
  12919. "\r\n";
  12920. ::send(cli,
  12921. #ifdef _WIN32
  12922. static_cast<const char *>(response_header.c_str()),
  12923. static_cast<int>(response_header.size()),
  12924. #else
  12925. response_header.c_str(), response_header.size(),
  12926. #endif
  12927. 0);
  12928. std::string chunk(64 * 1024, 'A');
  12929. size_t total_sent = 0;
  12930. while (total_sent < DATA_SIZE) {
  12931. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12932. auto sent = ::send(cli,
  12933. #ifdef _WIN32
  12934. static_cast<const char *>(chunk.c_str()),
  12935. static_cast<int>(to_send),
  12936. #else
  12937. chunk.c_str(), to_send,
  12938. #endif
  12939. 0);
  12940. if (sent <= 0) break;
  12941. total_sent += static_cast<size_t>(sent);
  12942. }
  12943. detail::close_socket(cli);
  12944. }
  12945. detail::close_socket(srv);
  12946. });
  12947. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12948. size_t total_received = 0;
  12949. {
  12950. Client cli("127.0.0.1", PORT + 2);
  12951. cli.set_read_timeout(10, 0);
  12952. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12953. auto res =
  12954. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12955. total_received += data_length;
  12956. return true;
  12957. });
  12958. // Should fail because 200MB exceeds the explicit 150MB limit
  12959. EXPECT_FALSE(res);
  12960. }
  12961. server_thread.join();
  12962. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12963. << "Client with content_receiver should respect the explicit "
  12964. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12965. << total_received << " bytes.";
  12966. }
  12967. // Verify that an explicit set_payload_max_length larger than the response
  12968. // allows the content_receiver to read all data successfully.
  12969. TEST(ClientVulnerabilityTest,
  12970. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12971. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12972. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12973. #ifndef _WIN32
  12974. signal(SIGPIPE, SIG_IGN);
  12975. #endif
  12976. auto server_thread = std::thread([] {
  12977. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12978. default_socket_options(srv);
  12979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12980. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12981. sockaddr_in addr{};
  12982. addr.sin_family = AF_INET;
  12983. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12984. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12985. int opt = 1;
  12986. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12987. #ifdef _WIN32
  12988. reinterpret_cast<const char *>(&opt),
  12989. #else
  12990. &opt,
  12991. #endif
  12992. sizeof(opt));
  12993. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12994. ::listen(srv, 1);
  12995. sockaddr_in cli_addr{};
  12996. socklen_t cli_len = sizeof(cli_addr);
  12997. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12998. if (cli != INVALID_SOCKET) {
  12999. char buf[4096];
  13000. ::recv(cli, buf, sizeof(buf), 0);
  13001. auto content_length = std::to_string(DATA_SIZE);
  13002. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13003. "Content-Length: " +
  13004. content_length +
  13005. "\r\n"
  13006. "Connection: close\r\n"
  13007. "\r\n";
  13008. ::send(cli,
  13009. #ifdef _WIN32
  13010. static_cast<const char *>(response_header.c_str()),
  13011. static_cast<int>(response_header.size()),
  13012. #else
  13013. response_header.c_str(), response_header.size(),
  13014. #endif
  13015. 0);
  13016. std::string chunk(64 * 1024, 'A');
  13017. size_t total_sent = 0;
  13018. while (total_sent < DATA_SIZE) {
  13019. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13020. auto sent = ::send(cli,
  13021. #ifdef _WIN32
  13022. static_cast<const char *>(chunk.c_str()),
  13023. static_cast<int>(to_send),
  13024. #else
  13025. chunk.c_str(), to_send,
  13026. #endif
  13027. 0);
  13028. if (sent <= 0) break;
  13029. total_sent += static_cast<size_t>(sent);
  13030. }
  13031. #ifdef _WIN32
  13032. ::shutdown(cli, SD_SEND);
  13033. #else
  13034. ::shutdown(cli, SHUT_WR);
  13035. #endif
  13036. char drain[1024];
  13037. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13038. detail::close_socket(cli);
  13039. }
  13040. detail::close_socket(srv);
  13041. });
  13042. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13043. size_t total_received = 0;
  13044. {
  13045. Client cli("127.0.0.1", PORT + 2);
  13046. cli.set_read_timeout(10, 0);
  13047. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13048. auto res =
  13049. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13050. total_received += data_length;
  13051. return true;
  13052. });
  13053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13054. EXPECT_EQ(StatusCode::OK_200, res->status);
  13055. }
  13056. server_thread.join();
  13057. EXPECT_EQ(total_received, DATA_SIZE)
  13058. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13059. << " bytes (larger than " << DATA_SIZE
  13060. << " bytes response), content_receiver should read all data, but only "
  13061. "read "
  13062. << total_received << " bytes.";
  13063. }
  13064. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13065. // Regression test for "zip bomb" attack on the client side: a malicious server
  13066. // sends a small gzip-compressed response that decompresses to a huge payload.
  13067. // The client must enforce payload_max_length on the decompressed size.
  13068. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13069. constexpr size_t DECOMPRESSED_SIZE =
  13070. 10 * 1024 * 1024; // 10MB after decompression
  13071. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13072. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13073. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13074. std::string compressed;
  13075. {
  13076. httplib::detail::gzip_compressor compressor;
  13077. bool ok =
  13078. compressor.compress(uncompressed.data(), uncompressed.size(),
  13079. /*last=*/true, [&](const char *buf, size_t len) {
  13080. compressed.append(buf, len);
  13081. return true;
  13082. });
  13083. ASSERT_TRUE(ok);
  13084. }
  13085. // Sanity: compressed data should be much smaller than the decompressed size
  13086. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13087. #ifndef _WIN32
  13088. signal(SIGPIPE, SIG_IGN);
  13089. #endif
  13090. // Set up the listening socket in the main thread so the server is guaranteed
  13091. // to be ready before the client connects (eliminates race condition).
  13092. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13093. default_socket_options(srv);
  13094. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13095. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13096. sockaddr_in addr{};
  13097. addr.sin_family = AF_INET;
  13098. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13099. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13100. int opt = 1;
  13101. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13102. #ifdef _WIN32
  13103. reinterpret_cast<const char *>(&opt),
  13104. #else
  13105. &opt,
  13106. #endif
  13107. sizeof(opt));
  13108. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13109. ASSERT_EQ(0, ::listen(srv, 1));
  13110. auto server_thread = std::thread([&compressed, srv] {
  13111. sockaddr_in cli_addr{};
  13112. socklen_t cli_len = sizeof(cli_addr);
  13113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13114. if (cli != INVALID_SOCKET) {
  13115. // Read the full HTTP request (until \r\n\r\n)
  13116. char buf[4096];
  13117. size_t total = 0;
  13118. while (total < sizeof(buf)) {
  13119. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13120. if (n <= 0) break;
  13121. total += static_cast<size_t>(n);
  13122. // Check for end of headers
  13123. if (total >= 4) {
  13124. std::string req(buf, total);
  13125. if (req.find("\r\n\r\n") != std::string::npos) break;
  13126. }
  13127. }
  13128. // Malicious response: gzip-compressed body, no Content-Length
  13129. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13130. "Content-Encoding: gzip\r\n"
  13131. "Connection: close\r\n"
  13132. "\r\n";
  13133. ::send(cli,
  13134. #ifdef _WIN32
  13135. static_cast<const char *>(response_header.c_str()),
  13136. static_cast<int>(response_header.size()),
  13137. #else
  13138. response_header.c_str(), response_header.size(),
  13139. #endif
  13140. 0);
  13141. // Send the compressed payload (small on the wire, huge when decompressed)
  13142. size_t total_sent = 0;
  13143. while (total_sent < compressed.size()) {
  13144. auto to_send = std::min(compressed.size() - total_sent,
  13145. static_cast<size_t>(64 * 1024));
  13146. auto sent =
  13147. ::send(cli,
  13148. #ifdef _WIN32
  13149. static_cast<const char *>(compressed.c_str() + total_sent),
  13150. static_cast<int>(to_send),
  13151. #else
  13152. compressed.c_str() + total_sent, to_send,
  13153. #endif
  13154. 0);
  13155. if (sent <= 0) break;
  13156. total_sent += static_cast<size_t>(sent);
  13157. }
  13158. detail::close_socket(cli);
  13159. }
  13160. });
  13161. auto se = detail::scope_exit([&] {
  13162. detail::close_socket(srv);
  13163. server_thread.join();
  13164. });
  13165. size_t total_decompressed = 0;
  13166. {
  13167. Client cli("127.0.0.1", PORT + 3);
  13168. cli.set_read_timeout(5, 0);
  13169. cli.set_decompress(true);
  13170. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13171. auto stream = cli.open_stream("GET", "/zipbomb");
  13172. ASSERT_TRUE(stream.is_valid());
  13173. char buffer[64 * 1024];
  13174. ssize_t n;
  13175. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13176. total_decompressed += static_cast<size_t>(n);
  13177. }
  13178. }
  13179. // The decompressed size must be capped by payload_max_length. Without
  13180. // protection, the client would decompress the full 10MB from a tiny
  13181. // compressed payload, enabling a zip bomb DoS attack.
  13182. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13183. << "Client decompressed " << total_decompressed
  13184. << " bytes from a gzip response. The decompressed size should be "
  13185. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13186. }
  13187. #endif
  13188. TEST(HostAndPortPropertiesTest, NoSSL) {
  13189. httplib::Client cli("www.google.com", 1234);
  13190. ASSERT_EQ("www.google.com", cli.host());
  13191. ASSERT_EQ(1234, cli.port());
  13192. }
  13193. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13194. httplib::Client cli("www.google.com:1234");
  13195. ASSERT_EQ("www.google.com", cli.host());
  13196. ASSERT_EQ(1234, cli.port());
  13197. }
  13198. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13199. // Port number that overflows int — should not crash, client becomes invalid
  13200. httplib::Client cli("http://www.google.com:99999999999999999999");
  13201. ASSERT_FALSE(cli.is_valid());
  13202. }
  13203. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13204. // Port 99999 exceeds valid range (1-65535) — should not crash
  13205. httplib::Client cli("http://www.google.com:99999");
  13206. ASSERT_FALSE(cli.is_valid());
  13207. auto res = cli.Get("/");
  13208. EXPECT_FALSE(res);
  13209. EXPECT_EQ(Error::Connection, res.error());
  13210. }
  13211. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13212. httplib::Client cli("http://user:pass@localhost:1234");
  13213. ASSERT_FALSE(cli.is_valid());
  13214. EXPECT_FALSE(cli.Get("/"));
  13215. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13216. }
  13217. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13218. httplib::Client cli("http://www.google.com:80abc");
  13219. ASSERT_FALSE(cli.is_valid());
  13220. }
  13221. #ifdef CPPHTTPLIB_SSL_ENABLED
  13222. TEST(HostAndPortPropertiesTest, SSL) {
  13223. httplib::SSLClient cli("www.google.com");
  13224. ASSERT_EQ("www.google.com", cli.host());
  13225. ASSERT_EQ(443, cli.port());
  13226. }
  13227. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13228. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13229. std::string cert;
  13230. read_file(CA_CERT_FILE, cert);
  13231. httplib::SSLClient httplib_client("www.google.com");
  13232. // Load CA store first time
  13233. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13234. // Load CA store second time (update)
  13235. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13236. // Verify client is still valid and can make connections
  13237. httplib_client.enable_server_certificate_verification(true);
  13238. auto res = httplib_client.Get("/");
  13239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13240. // Google may return 200 or 301 depending on various factors
  13241. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13242. res->status == StatusCode::MovedPermanently_301);
  13243. }
  13244. TEST(SSLClientTest, ServerNameIndication_Online) {
  13245. auto host = "httpbingo.org";
  13246. auto path = std::string{"/get"};
  13247. SSLClient cli(host, 443);
  13248. auto res = cli.Get(path);
  13249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13250. ASSERT_EQ(StatusCode::OK_200, res->status);
  13251. }
  13252. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13253. // Use a site that will cause SSL verification failure due to self-signed cert
  13254. SSLClient cli("self-signed.badssl.com", 443);
  13255. cli.enable_server_certificate_verification(true);
  13256. auto res = cli.Get("/");
  13257. ASSERT_TRUE(!res);
  13258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13259. // Verify backend error is captured for SSLServerVerification
  13260. // This occurs when certificate verification fails
  13261. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13262. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13263. EXPECT_NE(0UL, res.ssl_backend_error());
  13264. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13265. // For OpenSSL, ssl_error is 0 for verification errors
  13266. EXPECT_EQ(0, res.ssl_error());
  13267. #if !defined(_WIN32) || \
  13268. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13269. // On non-Windows or when Windows Schannel is disabled, the error comes
  13270. // from OpenSSL's verification
  13271. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13272. res.ssl_backend_error());
  13273. #endif
  13274. #endif
  13275. }
  13276. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13277. // Use a site where hostname doesn't match the certificate
  13278. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13279. SSLClient cli("wrong.host.badssl.com", 443);
  13280. cli.enable_server_certificate_verification(true);
  13281. cli.enable_server_hostname_verification(true);
  13282. auto res = cli.Get("/");
  13283. ASSERT_TRUE(!res);
  13284. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13285. // Verify backend error is captured for hostname verification failure
  13286. EXPECT_NE(0UL, res.ssl_backend_error());
  13287. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13288. // For OpenSSL, ssl_error is 0 for verification errors
  13289. EXPECT_EQ(0, res.ssl_error());
  13290. #if !defined(_WIN32) || \
  13291. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13292. // On non-Windows or when Windows Schannel is disabled, the error comes
  13293. // from OpenSSL's hostname verification
  13294. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13295. res.ssl_backend_error());
  13296. #endif
  13297. #endif
  13298. }
  13299. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13300. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13301. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13302. SSLClient cli("www.google.com", 443);
  13303. cli.enable_server_certificate_verification(true);
  13304. auto res = cli.Get("/");
  13305. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13306. }
  13307. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13308. SSLClient cli("www.google.com", 443);
  13309. cli.enable_server_certificate_verification(true);
  13310. cli.enable_windows_certificate_verification(false);
  13311. auto res = cli.Get("/");
  13312. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13313. }
  13314. // The server sends an intermediate cross-signed by a root Windows trusts,
  13315. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13316. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13317. SSLClient cli("accounts.spotify.com", 443);
  13318. auto res = cli.Get("/");
  13319. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13320. << " ssl_backend_error=" << res.ssl_backend_error();
  13321. }
  13322. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13323. // policy status, which no backend reports for a self-signed certificate.
  13324. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13325. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13328. auto se = detail::scope_exit([&] {
  13329. svr.stop();
  13330. t.join();
  13331. ASSERT_FALSE(svr.is_running());
  13332. });
  13333. svr.wait_until_ready();
  13334. SSLClient cli("127.0.0.1", PORT);
  13335. cli.set_connection_timeout(30);
  13336. auto res = cli.Get("/");
  13337. ASSERT_FALSE(res);
  13338. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13339. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13340. }
  13341. #endif
  13342. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13343. Client cli("https://google.com");
  13344. auto res = cli.Get("/");
  13345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13346. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13347. }
  13348. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13349. SSLClient cli("google.com");
  13350. cli.set_ca_cert_path(CA_CERT_FILE);
  13351. auto res = cli.Get("/");
  13352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13353. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13354. }
  13355. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13356. SSLClient cli("google.com");
  13357. cli.enable_server_certificate_verification(true);
  13358. cli.set_ca_cert_path("hello");
  13359. auto res = cli.Get("/");
  13360. ASSERT_TRUE(!res);
  13361. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13362. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13363. // should be set
  13364. EXPECT_EQ(0, res.ssl_error());
  13365. // Verify backend error is captured for SSLLoadingCerts
  13366. // This error occurs when loading CA certificates fails
  13367. EXPECT_NE(0UL, res.ssl_backend_error());
  13368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13369. // OpenSSL specific error codes:
  13370. // > openssl errstr 0x80000002
  13371. // error:80000002:system library::No such file or directory
  13372. // > openssl errstr 0xA000126
  13373. // error:0A000126:SSL routines::unexpected eof while reading
  13374. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13375. res.ssl_backend_error() == 0xA000126);
  13376. #endif
  13377. }
  13378. TEST(SSLClientTest, ServerCertificateVerification4) {
  13379. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13380. ASSERT_TRUE(svr.is_valid());
  13381. svr.Get("/test", [&](const Request &, Response &res) {
  13382. res.set_content("test", "text/plain");
  13383. svr.stop();
  13384. ASSERT_TRUE(true);
  13385. });
  13386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13387. auto se = detail::scope_exit([&] {
  13388. t.join();
  13389. ASSERT_FALSE(svr.is_running());
  13390. });
  13391. svr.wait_until_ready();
  13392. SSLClient cli("127.0.0.1", PORT);
  13393. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13394. cli.enable_server_certificate_verification(true);
  13395. cli.set_connection_timeout(30);
  13396. auto res = cli.Get("/test");
  13397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13398. ASSERT_EQ(StatusCode::OK_200, res->status);
  13399. }
  13400. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13401. std::string cert;
  13402. read_file(CA_CERT_FILE, cert);
  13403. SSLClient cli("google.com");
  13404. cli.load_ca_cert_store(cert.data(), cert.size());
  13405. const auto res = cli.Get("/");
  13406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13407. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13408. }
  13409. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13410. // clang-format off
  13411. static constexpr char cert[] =
  13412. "GlobalSign Root CA\n"
  13413. "==================\n"
  13414. "-----BEGIN CERTIFICATE-----\n"
  13415. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13416. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13417. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13418. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13419. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13420. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13421. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13422. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13423. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13424. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13425. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13426. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13427. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13428. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13429. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13430. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13431. "-----END CERTIFICATE-----\n";
  13432. // clang-format on
  13433. SSLClient cli("google.com");
  13434. cli.load_ca_cert_store(cert, sizeof(cert));
  13435. const auto res = cli.Get("/");
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13438. }
  13439. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13440. SSLClient cli("www.youtube.com");
  13441. cli.set_ca_cert_path(CA_CERT_FILE);
  13442. cli.enable_server_certificate_verification(true);
  13443. cli.set_follow_location(true);
  13444. auto res = cli.Get("/");
  13445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13446. ASSERT_EQ(StatusCode::OK_200, res->status);
  13447. }
  13448. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13449. SSLClient cli("wWw.YouTube.Com");
  13450. cli.set_ca_cert_path(CA_CERT_FILE);
  13451. cli.enable_server_certificate_verification(true);
  13452. cli.enable_server_hostname_verification(true);
  13453. cli.set_follow_location(true);
  13454. auto res = cli.Get("/");
  13455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13456. ASSERT_EQ(StatusCode::OK_200, res->status);
  13457. }
  13458. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13459. SSLClient cli("gOoGlE.COm");
  13460. cli.enable_server_certificate_verification(true);
  13461. cli.enable_server_hostname_verification(true);
  13462. cli.set_follow_location(true);
  13463. auto res = cli.Get("/");
  13464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13465. ASSERT_EQ(StatusCode::OK_200, res->status);
  13466. }
  13467. TEST(SSLClientTest, Issue2004_Online) {
  13468. Client client("https://google.com");
  13469. client.set_follow_location(true);
  13470. auto res = client.Get("/");
  13471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13472. ASSERT_EQ(StatusCode::OK_200, res->status);
  13473. auto body = res->body;
  13474. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13475. }
  13476. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13477. // Create SSLClient with invalid cert/key to make is_valid() return false
  13478. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13479. "nonexistent_key.pem");
  13480. // is_valid() should be false due to cert loading failure
  13481. ASSERT_FALSE(cli.is_valid());
  13482. auto res = cli.Get("/");
  13483. ASSERT_FALSE(res);
  13484. EXPECT_EQ(Error::SSLConnection, res.error());
  13485. }
  13486. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13487. // Test for Issue #2251: SSL error not properly reported when client cert
  13488. // and key paths are swapped or mismatched
  13489. // This simulates the scenario where user accidentally swaps the cert and key
  13490. // files
  13491. // Using client cert file as private key and vice versa (completely wrong)
  13492. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13493. // Should fail validation due to cert/key mismatch
  13494. ASSERT_FALSE(cli.is_valid());
  13495. // Attempt to make a request should fail with proper error
  13496. auto res = cli.Get("/");
  13497. ASSERT_FALSE(res);
  13498. EXPECT_EQ(Error::SSLConnection, res.error());
  13499. // SSL error should be recorded in the Result object (this is the key fix for
  13500. // Issue #2251)
  13501. auto backend_error = res.ssl_backend_error();
  13502. EXPECT_NE(0u, backend_error);
  13503. }
  13504. // Tests cert/key mismatch detection at the TLS context level
  13505. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13506. // Test that using mismatched cert/key causes connection failure.
  13507. // We verify this at the SSLClient level rather than through internal
  13508. // TLS API functions.
  13509. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13510. cli.enable_server_certificate_verification(false);
  13511. cli.set_connection_timeout(2);
  13512. // The mismatch should cause a connection or handshake error
  13513. auto res = cli.Get("/test");
  13514. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13515. // Either way, the request should fail
  13516. EXPECT_FALSE(res);
  13517. }
  13518. #endif
  13519. #if 0
  13520. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13521. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13522. ASSERT_TRUE(cli != nullptr);
  13523. cli->set_address_family(AF_INET6);
  13524. cli->set_interface("en0");
  13525. auto res = cli->Get("/get");
  13526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13527. ASSERT_EQ(StatusCode::OK_200, res->status);
  13528. }
  13529. #endif
  13530. // Client certificate tests - work with all TLS backends
  13531. #ifdef CPPHTTPLIB_SSL_ENABLED
  13532. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13533. void ClientCertPresent(
  13534. const std::string &client_cert_file,
  13535. const std::string &client_private_key_file,
  13536. const std::string &client_encrypted_private_key_pass = std::string(),
  13537. const ClientCertServerSetup &setup = nullptr) {
  13538. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13539. ASSERT_TRUE(svr.is_valid());
  13540. if (setup) { setup(svr); }
  13541. svr.Get("/test", [&](const Request &req, Response &res) {
  13542. res.set_content("test", "text/plain");
  13543. auto cert = req.peer_cert();
  13544. ASSERT_TRUE(static_cast<bool>(cert));
  13545. std::string common_name = cert.subject_cn();
  13546. EXPECT_EQ("Common Name", common_name);
  13547. });
  13548. auto port = svr.bind_to_any_port(HOST);
  13549. ASSERT_LT(0, port);
  13550. thread t = thread([&]() { svr.listen_after_bind(); });
  13551. auto se = detail::scope_exit([&] {
  13552. svr.stop();
  13553. t.join();
  13554. ASSERT_FALSE(svr.is_running());
  13555. });
  13556. svr.wait_until_ready();
  13557. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13558. client_encrypted_private_key_pass);
  13559. cli.enable_server_certificate_verification(false);
  13560. cli.set_connection_timeout(30);
  13561. auto res = cli.Get("/test");
  13562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13563. ASSERT_EQ(StatusCode::OK_200, res->status);
  13564. }
  13565. TEST(SSLClientServerTest, ClientCertPresent) {
  13566. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13567. }
  13568. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13569. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13570. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13571. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13572. }
  13573. // Expects svr, which must require client certificates, to reject a client
  13574. // that has none
  13575. void RejectsClientWithoutCert(SSLServer &svr) {
  13576. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13577. auto port = svr.bind_to_any_port(HOST);
  13578. ASSERT_LT(0, port);
  13579. thread t = thread([&]() { svr.listen_after_bind(); });
  13580. auto se = detail::scope_exit([&] {
  13581. svr.stop();
  13582. t.join();
  13583. ASSERT_FALSE(svr.is_running());
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, port);
  13587. cli.set_connection_timeout(30);
  13588. // Skip the server certificate check, so that the request fails because the
  13589. // client certificate is missing rather than because cert.pem is not trusted
  13590. cli.enable_server_certificate_verification(false);
  13591. auto res = cli.Get("/test");
  13592. ASSERT_FALSE(res);
  13593. // The server rejects the client during the handshake, or on TLS 1.3 right
  13594. // after it, which the client notices on its first write or read
  13595. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13596. res.error() == Error::Write || res.error() == Error::Read)
  13597. << to_string(res.error());
  13598. if (res.error() == Error::SSLConnection) {
  13599. EXPECT_NE(0UL, res.ssl_backend_error());
  13600. }
  13601. // A rejection noticed on the write keeps the TLS error the write hit
  13602. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13603. }
  13604. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13606. ASSERT_TRUE(svr.is_valid());
  13607. if (setup) { setup(svr); }
  13608. RejectsClientWithoutCert(svr);
  13609. }
  13610. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13611. // A server that requires client certificates must keep requiring them after
  13612. // setup changes it, and keep accepting a client that has one
  13613. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13614. ClientCertMissing(setup);
  13615. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13616. setup);
  13617. }
  13618. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13619. ClientCertStillRequired([](SSLServer &svr) {
  13620. ASSERT_TRUE(tls::set_verify_callback(
  13621. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13622. });
  13623. }
  13624. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13625. ClientCertStillRequired([](SSLServer &svr) {
  13626. ASSERT_TRUE(tls::set_verify_callback(
  13627. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13628. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13629. });
  13630. }
  13631. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13632. ClientCertStillRequired([](SSLServer &svr) {
  13633. std::string cert_pem, key_pem, ca_pem;
  13634. read_file(SERVER_CERT_FILE, cert_pem);
  13635. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13636. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13637. ASSERT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  13638. ca_pem.c_str()));
  13639. });
  13640. }
  13641. // A TLS error from one request must not show up in a later request's Result
  13642. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13644. ASSERT_TRUE(svr.is_valid());
  13645. svr.Get("/test", [](const Request &, Response &res) {
  13646. res.set_content("test", "text/plain");
  13647. });
  13648. auto port = svr.bind_to_any_port(HOST);
  13649. ASSERT_LT(0, port);
  13650. thread t = thread([&]() { svr.listen_after_bind(); });
  13651. auto se = detail::scope_exit([&] {
  13652. svr.stop();
  13653. t.join();
  13654. ASSERT_FALSE(svr.is_running());
  13655. });
  13656. svr.wait_until_ready();
  13657. SSLClient cli(HOST, port);
  13658. cli.set_connection_timeout(30);
  13659. cli.enable_server_hostname_verification(false);
  13660. // cert.pem is not trusted, so the handshake fails
  13661. ASSERT_FALSE(cli.Get("/test"));
  13662. cli.enable_server_certificate_verification(false);
  13663. auto res = cli.Get("/test");
  13664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13665. EXPECT_EQ(0, res.ssl_error());
  13666. EXPECT_EQ(0UL, res.ssl_backend_error());
  13667. }
  13668. // PEM memory-based constructor tests (works with all TLS backends).
  13669. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13670. // terminator after it.
  13671. void PemMemoryClientCertPresent(
  13672. const std::string &client_cert_file,
  13673. const std::string &client_private_key_file,
  13674. const std::string &client_encrypted_private_key_pass = std::string(),
  13675. bool exact_size = false) {
  13676. // Read PEM files into memory
  13677. std::string server_cert_pem, server_key_pem;
  13678. std::string client_ca_pem;
  13679. std::string client_cert_pem, client_key_pem;
  13680. read_file(SERVER_CERT_FILE, server_cert_pem);
  13681. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13682. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13683. read_file(client_cert_file, client_cert_pem);
  13684. read_file(client_private_key_file, client_key_pem);
  13685. std::list<std::vector<char>> exact_copies;
  13686. auto data = [&](const std::string &pem) -> const char * {
  13687. if (!exact_size) { return pem.c_str(); }
  13688. exact_copies.emplace_back(pem.begin(), pem.end());
  13689. return exact_copies.back().data();
  13690. };
  13691. // Create server with PEM memory
  13692. SSLServer::PemMemory server_pem = {
  13693. data(server_cert_pem),
  13694. server_cert_pem.size(),
  13695. data(server_key_pem),
  13696. server_key_pem.size(),
  13697. data(client_ca_pem),
  13698. client_ca_pem.size(),
  13699. nullptr // no password for server key
  13700. };
  13701. SSLServer svr(server_pem);
  13702. ASSERT_TRUE(svr.is_valid());
  13703. svr.Get("/test", [&](const Request &req, Response &res) {
  13704. res.set_content("test", "text/plain");
  13705. auto cert = req.peer_cert();
  13706. ASSERT_TRUE(static_cast<bool>(cert));
  13707. EXPECT_EQ("Common Name", cert.subject_cn());
  13708. });
  13709. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13710. auto se = detail::scope_exit([&] {
  13711. svr.stop();
  13712. t.join();
  13713. ASSERT_FALSE(svr.is_running());
  13714. });
  13715. svr.wait_until_ready();
  13716. // Create client with PEM memory
  13717. const char *password = client_encrypted_private_key_pass.empty()
  13718. ? nullptr
  13719. : client_encrypted_private_key_pass.c_str();
  13720. SSLClient::PemMemory client_pem = {
  13721. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13722. client_key_pem.size(), password};
  13723. SSLClient cli(HOST, PORT, client_pem);
  13724. cli.enable_server_certificate_verification(false);
  13725. cli.set_connection_timeout(30);
  13726. auto res = cli.Get("/test");
  13727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13728. ASSERT_EQ(StatusCode::OK_200, res->status);
  13729. }
  13730. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13731. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13732. }
  13733. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13734. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13735. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13736. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13737. }
  13738. // A server built from PEM memory with a client CA requires client certificates
  13739. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13740. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13741. read_file(SERVER_CERT_FILE, server_cert_pem);
  13742. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13743. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13744. SSLServer::PemMemory server_pem = {
  13745. server_cert_pem.c_str(),
  13746. server_cert_pem.size(),
  13747. server_key_pem.c_str(),
  13748. server_key_pem.size(),
  13749. client_ca_pem.c_str(),
  13750. client_ca_pem.size(),
  13751. nullptr // no password for server key
  13752. };
  13753. SSLServer svr(server_pem);
  13754. ASSERT_TRUE(svr.is_valid());
  13755. RejectsClientWithoutCert(svr);
  13756. }
  13757. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13758. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13759. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13760. true);
  13761. }
  13762. // A length shorter than the PEM cuts it short, so it no longer loads
  13763. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13764. std::string cert, key;
  13765. read_file(SERVER_CERT_FILE, cert);
  13766. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13767. for (auto cut_cert : {true, false}) {
  13768. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13769. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13770. SSLServer::PemMemory server_pem = {
  13771. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13772. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13773. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13774. key_len, nullptr};
  13775. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13776. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13777. key.c_str(), key_len, nullptr};
  13778. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13779. }
  13780. }
  13781. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13782. class NoListenSSLServer : public SSLServer {
  13783. public:
  13784. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13785. const char *client_ca_cert_file_path,
  13786. const char *client_ca_cert_dir_path = nullptr)
  13787. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13788. client_ca_cert_dir_path),
  13789. stop_(false) {}
  13790. std::atomic_bool stop_;
  13791. private:
  13792. bool process_and_close_socket(socket_t /*sock*/) override {
  13793. // Don't create SSL context
  13794. while (!stop_.load()) {
  13795. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13796. }
  13797. return true;
  13798. }
  13799. };
  13800. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13801. CLIENT_CA_CERT_FILE);
  13802. ASSERT_TRUE(svr.is_valid());
  13803. svr.Get("/test", [&](const Request &, Response &res) {
  13804. res.set_content("test", "text/plain");
  13805. });
  13806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13807. auto se = detail::scope_exit([&] {
  13808. svr.stop_ = true;
  13809. svr.stop();
  13810. t.join();
  13811. ASSERT_FALSE(svr.is_running());
  13812. });
  13813. svr.wait_until_ready();
  13814. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13815. cli.enable_server_certificate_verification(false);
  13816. cli.set_connection_timeout(1);
  13817. auto res = cli.Get("/test");
  13818. ASSERT_TRUE(!res);
  13819. EXPECT_EQ(Error::SSLConnection, res.error());
  13820. // Timeout results in WantRead error code (maps to backend-specific value)
  13821. EXPECT_NE(0, res.ssl_error());
  13822. }
  13823. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13824. // Test SSLServer with client certificate verification using the standard
  13825. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13827. CLIENT_CA_CERT_DIR);
  13828. ASSERT_TRUE(svr.is_valid());
  13829. svr.Get("/test", [&](const Request &req, Response &res) {
  13830. res.set_content("test", "text/plain");
  13831. auto cert = req.peer_cert();
  13832. ASSERT_TRUE(static_cast<bool>(cert));
  13833. auto common_name = cert.subject_cn();
  13834. EXPECT_EQ("Common Name", common_name);
  13835. });
  13836. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. ASSERT_FALSE(svr.is_running());
  13841. });
  13842. svr.wait_until_ready();
  13843. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13844. cli.enable_server_certificate_verification(false);
  13845. cli.set_connection_timeout(30);
  13846. auto res = cli.Get("/test");
  13847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13848. ASSERT_EQ(StatusCode::OK_200, res->status);
  13849. }
  13850. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13851. // Verifies that wildcard matching and exact matching work consistently
  13852. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13853. using namespace httplib::tls;
  13854. // We need a running server to test against
  13855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13856. ASSERT_TRUE(svr.is_valid());
  13857. svr.Get("/test", [](const Request &, Response &res) {
  13858. res.set_content("ok", "text/plain");
  13859. });
  13860. thread t([&]() { svr.listen(HOST, PORT); });
  13861. auto se = detail::scope_exit([&] {
  13862. svr.stop();
  13863. t.join();
  13864. });
  13865. svr.wait_until_ready();
  13866. bool verify_callback_called = false;
  13867. bool verify_result_wrong = false;
  13868. SSLClient cli(HOST, PORT);
  13869. cli.enable_server_certificate_verification(true);
  13870. cli.set_ca_cert_path(CA_CERT_FILE);
  13871. cli.set_connection_timeout(5);
  13872. // Note: Test certificate has CN="Common Name", not "localhost"
  13873. bool verify_result_cn = false;
  13874. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13875. verify_callback_called = true;
  13876. if (!ctx.cert) return false;
  13877. // Test 1: "Common Name" should match (our test server cert CN)
  13878. verify_result_cn = ctx.check_hostname("Common Name");
  13879. // Test 2: wrong hostname should not match
  13880. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13881. return true; // Accept for the purpose of this test
  13882. });
  13883. auto res = cli.Get("/test");
  13884. // The request may succeed or fail depending on cert configuration
  13885. // but the callback should have been called
  13886. ASSERT_TRUE(verify_callback_called)
  13887. << "Verify callback should have been called";
  13888. // CN="Common Name" should match our test certificate
  13889. //
  13890. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13891. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13892. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13893. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13894. // <openssl/base.h>, which is included transitively when
  13895. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13896. #if defined(OPENSSL_IS_BORINGSSL)
  13897. EXPECT_FALSE(verify_result_cn)
  13898. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13899. #else
  13900. EXPECT_TRUE(verify_result_cn)
  13901. << "verify_hostname should match 'Common Name' (certificate CN)";
  13902. #endif
  13903. // Wrong hostname should not match
  13904. EXPECT_FALSE(verify_result_wrong)
  13905. << "verify_hostname should not match 'wronghost.example.com'";
  13906. }
  13907. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13908. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13909. // X509_check_ip behavior and must hold for every backend.
  13910. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13911. using namespace httplib::tls;
  13912. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13913. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13914. ASSERT_TRUE(svr.is_valid());
  13915. svr.Get("/test", [](const Request &, Response &res) {
  13916. res.set_content("ok", "text/plain");
  13917. });
  13918. thread t([&]() { svr.listen(HOST, PORT); });
  13919. auto se = detail::scope_exit([&] {
  13920. svr.stop();
  13921. t.join();
  13922. });
  13923. svr.wait_until_ready();
  13924. bool verify_callback_called = false;
  13925. bool ip_matched_via_cn = true;
  13926. SSLClient cli(HOST, PORT);
  13927. cli.enable_server_certificate_verification(true);
  13928. cli.set_ca_cert_path(CA_CERT_FILE);
  13929. cli.set_connection_timeout(5);
  13930. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13931. verify_callback_called = true;
  13932. if (!ctx.cert) return false;
  13933. // The IP appears only in the CN, so it must NOT be accepted.
  13934. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13935. return true; // Accept for the purpose of this test
  13936. });
  13937. cli.Get("/test");
  13938. ASSERT_TRUE(verify_callback_called)
  13939. << "Verify callback should have been called";
  13940. EXPECT_FALSE(ip_matched_via_cn)
  13941. << "An IP host must not be authenticated via the certificate CN";
  13942. }
  13943. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13944. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13945. using namespace httplib::tls;
  13946. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13947. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13948. ASSERT_TRUE(svr.is_valid());
  13949. svr.Get("/test", [](const Request &, Response &res) {
  13950. res.set_content("ok", "text/plain");
  13951. });
  13952. thread t([&]() { svr.listen(HOST, PORT); });
  13953. auto se = detail::scope_exit([&] {
  13954. svr.stop();
  13955. t.join();
  13956. });
  13957. svr.wait_until_ready();
  13958. bool verify_callback_called = false;
  13959. bool san_matched = false;
  13960. bool wrong_ipv6_matched = true;
  13961. bool cn_ipv6_matched = true;
  13962. SSLClient cli(HOST, PORT);
  13963. cli.enable_server_certificate_verification(true);
  13964. cli.set_ca_cert_path(CA_CERT_FILE);
  13965. cli.set_connection_timeout(5);
  13966. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13967. verify_callback_called = true;
  13968. if (!ctx.cert) return false;
  13969. // Matches the IPv6 iPAddress SAN.
  13970. san_matched = ctx.check_hostname("2001:db8::1");
  13971. // A different IPv6 address must not match.
  13972. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13973. // "::1" lives only in the CN, so it must not be accepted.
  13974. cn_ipv6_matched = ctx.check_hostname("::1");
  13975. return true; // Accept for the purpose of this test
  13976. });
  13977. cli.Get("/test");
  13978. ASSERT_TRUE(verify_callback_called)
  13979. << "Verify callback should have been called";
  13980. EXPECT_TRUE(san_matched)
  13981. << "verify_hostname should match an IPv6 iPAddress SAN";
  13982. EXPECT_FALSE(wrong_ipv6_matched)
  13983. << "verify_hostname should not match a non-matching IPv6 address";
  13984. EXPECT_FALSE(cn_ipv6_matched)
  13985. << "An IPv6 host must not be authenticated via the certificate CN";
  13986. }
  13987. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13988. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13989. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13990. using namespace httplib::tls;
  13991. // SANs: DNS:a.zz, IP:42.46.122.122
  13992. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13993. ASSERT_TRUE(svr.is_valid());
  13994. svr.Get("/test", [](const Request &, Response &res) {
  13995. res.set_content("ok", "text/plain");
  13996. });
  13997. auto port = svr.bind_to_any_port(HOST);
  13998. thread t([&]() { svr.listen_after_bind(); });
  13999. auto se = detail::scope_exit([&] {
  14000. svr.stop();
  14001. t.join();
  14002. });
  14003. svr.wait_until_ready();
  14004. bool verify_callback_called = false;
  14005. bool dns_san_matched = false;
  14006. bool ip_san_matched = false;
  14007. bool ip_matched_via_dns_san = true;
  14008. bool dns_matched_via_ip_san = true;
  14009. bool cn_matched_next_to_dns_san = true;
  14010. SSLClient cli(HOST, port);
  14011. cli.enable_server_certificate_verification(true);
  14012. cli.set_ca_cert_path(CA_CERT_FILE);
  14013. cli.set_connection_timeout(5);
  14014. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14015. verify_callback_called = true;
  14016. if (!ctx.cert) return false;
  14017. dns_san_matched = ctx.check_hostname("a.zz");
  14018. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14019. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14020. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14021. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14022. return true; // Accept for the purpose of this test
  14023. });
  14024. cli.Get("/test");
  14025. ASSERT_TRUE(verify_callback_called)
  14026. << "Verify callback should have been called";
  14027. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14028. EXPECT_TRUE(ip_san_matched)
  14029. << "verify_hostname should match an iPAddress SAN";
  14030. EXPECT_FALSE(ip_matched_via_dns_san)
  14031. << "An IP host must not be authenticated via a dNSName SAN";
  14032. EXPECT_FALSE(dns_matched_via_ip_san)
  14033. << "A DNS host must not be authenticated via an iPAddress SAN";
  14034. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14035. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14036. }
  14037. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14038. // "www.*.example.test" names one host and not every host under example.test.
  14039. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14040. using namespace httplib::tls;
  14041. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14042. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14043. ASSERT_TRUE(svr.is_valid());
  14044. svr.Get("/test", [](const Request &, Response &res) {
  14045. res.set_content("ok", "text/plain");
  14046. });
  14047. auto port = svr.bind_to_any_port(HOST);
  14048. thread t([&]() { svr.listen_after_bind(); });
  14049. auto se = detail::scope_exit([&] {
  14050. svr.stop();
  14051. t.join();
  14052. });
  14053. svr.wait_until_ready();
  14054. bool verify_callback_called = false;
  14055. bool leftmost_wildcard_matched = false;
  14056. bool wildcard_spanned_labels = true;
  14057. bool inner_wildcard_matched = true;
  14058. SSLClient cli(HOST, port);
  14059. cli.enable_server_certificate_verification(true);
  14060. cli.set_ca_cert_path(CA_CERT_FILE);
  14061. cli.set_connection_timeout(5);
  14062. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14063. verify_callback_called = true;
  14064. if (!ctx.cert) return false;
  14065. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14066. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14067. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14068. return true; // Accept for the purpose of this test
  14069. });
  14070. cli.Get("/test");
  14071. ASSERT_TRUE(verify_callback_called)
  14072. << "Verify callback should have been called";
  14073. EXPECT_TRUE(leftmost_wildcard_matched)
  14074. << "A leftmost wildcard should match a single label";
  14075. EXPECT_FALSE(wildcard_spanned_labels)
  14076. << "A wildcard label must not match more than one label";
  14077. EXPECT_FALSE(inner_wildcard_matched)
  14078. << "A wildcard outside the leftmost label must not be honoured";
  14079. }
  14080. // sans() must report each SAN entry under its own type.
  14081. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14082. using namespace httplib::tls;
  14083. // SANs: DNS:a.zz, IP:42.46.122.122
  14084. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14085. ASSERT_TRUE(svr.is_valid());
  14086. svr.Get("/test", [](const Request &, Response &res) {
  14087. res.set_content("ok", "text/plain");
  14088. });
  14089. auto port = svr.bind_to_any_port(HOST);
  14090. thread t([&]() { svr.listen_after_bind(); });
  14091. auto se = detail::scope_exit([&] {
  14092. svr.stop();
  14093. t.join();
  14094. });
  14095. svr.wait_until_ready();
  14096. bool verify_callback_called = false;
  14097. std::vector<SanEntry> sans;
  14098. SSLClient cli(HOST, port);
  14099. cli.enable_server_certificate_verification(true);
  14100. cli.set_ca_cert_path(CA_CERT_FILE);
  14101. cli.set_connection_timeout(5);
  14102. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14103. verify_callback_called = true;
  14104. if (!ctx.cert) return false;
  14105. sans = ctx.sans();
  14106. return true; // Accept for the purpose of this test
  14107. });
  14108. cli.Get("/test");
  14109. ASSERT_TRUE(verify_callback_called)
  14110. << "Verify callback should have been called";
  14111. auto has_san = [&](SanType type, const std::string &value) {
  14112. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14113. return san.type == type && san.value == value;
  14114. });
  14115. };
  14116. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14117. << "sans() should report the dNSName SAN";
  14118. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14119. << "sans() should report the iPAddress SAN";
  14120. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14121. << "sans() must not report the dNSName SAN as an address";
  14122. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14123. << "sans() must not report the iPAddress SAN as a DNS name";
  14124. }
  14125. #endif
  14126. // mbedTLS-specific callback constructor test
  14127. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14128. #ifdef CPPHTTPLIB_SSL_ENABLED
  14129. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14130. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14131. ASSERT_TRUE(svr.is_valid());
  14132. // Set up a handler to verify client certificate is present
  14133. bool client_cert_verified = false;
  14134. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14135. // Verify that client certificate was provided
  14136. client_cert_verified = true;
  14137. res.set_content("success", "text/plain");
  14138. });
  14139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. ASSERT_FALSE(svr.is_running());
  14144. });
  14145. svr.wait_until_ready();
  14146. // Client with certificate
  14147. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14148. cli.enable_server_certificate_verification(false);
  14149. cli.set_connection_timeout(30);
  14150. auto res = cli.Get("/test");
  14151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14152. ASSERT_EQ(StatusCode::OK_200, res->status);
  14153. ASSERT_TRUE(client_cert_verified);
  14154. EXPECT_EQ("success", res->body);
  14155. }
  14156. #endif
  14157. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14158. // backends
  14159. #ifdef CPPHTTPLIB_SSL_ENABLED
  14160. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14161. using namespace httplib::tls;
  14162. // Test that when client CA cert file is provided,
  14163. // the server properly requests and validates client certificates
  14164. // Create a server with client authentication
  14165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14166. ASSERT_TRUE(svr.is_valid());
  14167. bool handler_called = false;
  14168. svr.Get("/test", [&](const Request &req, Response &res) {
  14169. handler_called = true;
  14170. // Verify that a client certificate was provided
  14171. auto cert = req.peer_cert();
  14172. ASSERT_TRUE(static_cast<bool>(cert));
  14173. // Get the issuer name
  14174. std::string issuer_str = cert.issuer_name();
  14175. ASSERT_FALSE(issuer_str.empty());
  14176. // The client certificate should be issued by our test CA
  14177. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14178. res.set_content("authenticated", "text/plain");
  14179. });
  14180. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14181. auto se = detail::scope_exit([&] {
  14182. svr.stop();
  14183. t.join();
  14184. ASSERT_FALSE(svr.is_running());
  14185. });
  14186. svr.wait_until_ready();
  14187. // Connect with a client certificate issued by the CA
  14188. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14189. cli.enable_server_certificate_verification(false);
  14190. cli.set_connection_timeout(30);
  14191. auto res = cli.Get("/test");
  14192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14193. ASSERT_EQ(StatusCode::OK_200, res->status);
  14194. ASSERT_TRUE(handler_called);
  14195. EXPECT_EQ("authenticated", res->body);
  14196. }
  14197. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14198. using namespace httplib::tls;
  14199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14200. ASSERT_TRUE(svr.is_valid());
  14201. svr.Get("/test", [](const Request &, Response &res) {
  14202. res.set_content("ok", "text/plain");
  14203. });
  14204. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14205. auto se = detail::scope_exit([&] {
  14206. svr.stop();
  14207. t.join();
  14208. });
  14209. svr.wait_until_ready();
  14210. SSLClient cli(HOST, PORT);
  14211. cli.enable_server_certificate_verification(false);
  14212. cli.set_connection_timeout(30);
  14213. bool cert_checked = false;
  14214. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14215. if (ctx.cert) {
  14216. auto sans = ctx.sans();
  14217. // Test certificate may or may not have SANs - just verify the API
  14218. // works If SANs exist, verify the types are valid
  14219. for (const auto &san : sans) {
  14220. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14221. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14222. san.type == SanType::OTHER);
  14223. EXPECT_FALSE(san.value.empty());
  14224. }
  14225. cert_checked = true;
  14226. }
  14227. return true;
  14228. });
  14229. auto res = cli.Get("/test");
  14230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14231. EXPECT_TRUE(cert_checked);
  14232. }
  14233. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14234. using namespace httplib::tls;
  14235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14236. ASSERT_TRUE(svr.is_valid());
  14237. svr.Get("/test", [](const Request &, Response &res) {
  14238. res.set_content("ok", "text/plain");
  14239. });
  14240. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14241. auto se = detail::scope_exit([&] {
  14242. svr.stop();
  14243. t.join();
  14244. });
  14245. svr.wait_until_ready();
  14246. SSLClient cli(HOST, PORT);
  14247. cli.enable_server_certificate_verification(false);
  14248. cli.set_connection_timeout(30);
  14249. bool validity_checked = false;
  14250. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14251. if (ctx.cert) {
  14252. time_t not_before = 0, not_after = 0;
  14253. bool result = ctx.validity(not_before, not_after);
  14254. EXPECT_TRUE(result);
  14255. // Verify that not_before < now < not_after for a valid cert
  14256. time_t now = time(nullptr);
  14257. EXPECT_LT(not_before, now);
  14258. EXPECT_GT(not_after, now);
  14259. validity_checked = true;
  14260. }
  14261. return true;
  14262. });
  14263. auto res = cli.Get("/test");
  14264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14265. EXPECT_TRUE(validity_checked);
  14266. }
  14267. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14268. using namespace httplib::tls;
  14269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14270. ASSERT_TRUE(svr.is_valid());
  14271. svr.Get("/test", [](const Request &, Response &res) {
  14272. res.set_content("ok", "text/plain");
  14273. });
  14274. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. t.join();
  14278. });
  14279. svr.wait_until_ready();
  14280. SSLClient cli(HOST, PORT);
  14281. cli.enable_server_certificate_verification(false);
  14282. cli.set_connection_timeout(30);
  14283. bool serial_checked = false;
  14284. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14285. if (ctx.cert) {
  14286. std::string serial = ctx.serial();
  14287. EXPECT_FALSE(serial.empty());
  14288. // Serial should be a hex string
  14289. for (char c : serial) {
  14290. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14291. (c >= 'a' && c <= 'f'));
  14292. }
  14293. serial_checked = true;
  14294. }
  14295. return true;
  14296. });
  14297. auto res = cli.Get("/test");
  14298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14299. EXPECT_TRUE(serial_checked);
  14300. }
  14301. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14302. // Test 1: Valid CA file - no error should be recorded
  14303. {
  14304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14305. CLIENT_CA_CERT_FILE);
  14306. ASSERT_TRUE(svr.is_valid());
  14307. // With valid setup, last_ssl_error should be 0
  14308. EXPECT_EQ(0, svr.ssl_last_error());
  14309. }
  14310. // Test 2: Invalid CA file content
  14311. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14312. {
  14313. // Create a temporary file with completely invalid content
  14314. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14315. {
  14316. std::ofstream ofs(temp_invalid_ca);
  14317. ofs << "This is not a certificate file at all\n";
  14318. ofs << "Just plain text content\n";
  14319. }
  14320. // Create server with invalid CA file
  14321. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14322. // Clean up temporary file
  14323. std::remove(temp_invalid_ca);
  14324. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14325. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14326. // Note: SSL_CTX_load_verify_locations typically fails first,
  14327. // but our error handling code path is still exercised
  14328. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14329. }
  14330. }
  14331. TEST(VerifyCallbackTest, VerifyContextFields) {
  14332. using namespace httplib::tls;
  14333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14334. ASSERT_TRUE(svr.is_valid());
  14335. svr.Get("/test", [](const Request &, Response &res) {
  14336. res.set_content("ok", "text/plain");
  14337. });
  14338. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14339. auto se = detail::scope_exit([&] {
  14340. svr.stop();
  14341. t.join();
  14342. });
  14343. svr.wait_until_ready();
  14344. SSLClient cli(HOST, PORT);
  14345. cli.enable_server_certificate_verification(false);
  14346. cli.set_connection_timeout(30);
  14347. int callback_count = 0;
  14348. bool saw_leaf_cert = false;
  14349. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14350. if (ctx.cert) {
  14351. callback_count++;
  14352. // We should see at least one certificate (the leaf)
  14353. std::string cn = ctx.subject_cn();
  14354. if (!cn.empty()) { saw_leaf_cert = true; }
  14355. // Verify context fields are populated
  14356. EXPECT_NE(ctx.session, nullptr);
  14357. EXPECT_GE(ctx.depth, 0);
  14358. }
  14359. return true;
  14360. });
  14361. auto res = cli.Get("/test");
  14362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14363. EXPECT_GT(callback_count, 0);
  14364. EXPECT_TRUE(saw_leaf_cert);
  14365. }
  14366. // A verifier that accepts runs alongside the built-in verification, and is the
  14367. // only check once that is turned off.
  14368. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14369. using namespace httplib::tls;
  14370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14371. ASSERT_TRUE(svr.is_valid());
  14372. svr.Get("/test", [](const Request &, Response &res) {
  14373. res.set_content("ok", "text/plain");
  14374. });
  14375. auto port = svr.bind_to_any_port(HOST);
  14376. thread t([&]() { svr.listen_after_bind(); });
  14377. auto se = detail::scope_exit([&] {
  14378. svr.stop();
  14379. t.join();
  14380. });
  14381. svr.wait_until_ready();
  14382. SSLClient cli(HOST, port);
  14383. cli.enable_server_hostname_verification(false);
  14384. auto calls = 0;
  14385. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14386. calls++;
  14387. return true;
  14388. });
  14389. // cert.pem is not trusted
  14390. auto res = cli.Get("/test");
  14391. ASSERT_FALSE(res);
  14392. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14393. EXPECT_GT(calls, 0);
  14394. cli.enable_server_certificate_verification(false);
  14395. res = cli.Get("/test");
  14396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14397. EXPECT_EQ("ok", res->body);
  14398. }
  14399. // A verifier belongs to the client that set it, not to the thread that set it.
  14400. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14401. using namespace httplib::tls;
  14402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14403. ASSERT_TRUE(svr.is_valid());
  14404. svr.Get("/test", [](const Request &, Response &res) {
  14405. res.set_content("ok", "text/plain");
  14406. });
  14407. auto port = svr.bind_to_any_port(HOST);
  14408. thread t([&]() { svr.listen_after_bind(); });
  14409. auto se = detail::scope_exit([&] {
  14410. svr.stop();
  14411. t.join();
  14412. });
  14413. svr.wait_until_ready();
  14414. auto rejecting_calls = 0;
  14415. SSLClient rejecting(HOST, port);
  14416. rejecting.enable_server_certificate_verification(false);
  14417. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14418. rejecting_calls++;
  14419. return false;
  14420. });
  14421. auto accepting_calls = 0;
  14422. SSLClient accepting(HOST, port);
  14423. accepting.enable_server_certificate_verification(false);
  14424. // Set on another thread than the requests below.
  14425. thread([&]() {
  14426. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14427. accepting_calls++;
  14428. return true;
  14429. });
  14430. }).join();
  14431. // Requested on another thread than the verifier was set on.
  14432. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14433. EXPECT_GT(rejecting_calls, 0);
  14434. auto res = accepting.Get("/test");
  14435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14436. EXPECT_GT(accepting_calls, 0);
  14437. }
  14438. // A verifier replaced while a handshake runs it lives until it returns.
  14439. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14440. using namespace httplib::tls;
  14441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14442. ASSERT_TRUE(svr.is_valid());
  14443. svr.Get("/test", [](const Request &, Response &res) {
  14444. res.set_content("ok", "text/plain");
  14445. });
  14446. auto port = svr.bind_to_any_port(HOST);
  14447. thread t([&]() { svr.listen_after_bind(); });
  14448. auto se = detail::scope_exit([&] {
  14449. svr.stop();
  14450. t.join();
  14451. });
  14452. svr.wait_until_ready();
  14453. SSLClient cli(HOST, port);
  14454. cli.enable_server_certificate_verification(false);
  14455. std::promise<void> entered;
  14456. std::promise<void> replaced;
  14457. auto replaced_future = replaced.get_future();
  14458. auto first_call = true;
  14459. // Long enough to live on the heap
  14460. std::string expected(64, 'v');
  14461. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14462. if (first_call) {
  14463. first_call = false;
  14464. entered.set_value();
  14465. replaced_future.wait();
  14466. }
  14467. return expected == std::string(64, 'v');
  14468. });
  14469. thread request([&]() {
  14470. auto res = cli.Get("/test");
  14471. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14472. });
  14473. entered.get_future().wait();
  14474. cli.set_server_certificate_verifier(
  14475. [](const VerifyContext &) { return true; });
  14476. replaced.set_value();
  14477. request.join();
  14478. }
  14479. // VerifyContext::session is the same handle the other tls:: functions take.
  14480. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14481. using namespace httplib::tls;
  14482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14483. ASSERT_TRUE(svr.is_valid());
  14484. svr.Get("/test", [](const Request &, Response &res) {
  14485. res.set_content("ok", "text/plain");
  14486. });
  14487. auto port = svr.bind_to_any_port(HOST);
  14488. thread t([&]() { svr.listen_after_bind(); });
  14489. auto se = detail::scope_exit([&] {
  14490. svr.stop();
  14491. t.join();
  14492. });
  14493. svr.wait_until_ready();
  14494. SSLClient cli(HOST, port);
  14495. cli.enable_server_certificate_verification(false);
  14496. session_t verifier_session = nullptr;
  14497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14498. verifier_session = ctx.session;
  14499. return true;
  14500. });
  14501. session_t session_verifier_session = nullptr;
  14502. cli.set_session_verifier([&](session_t session) {
  14503. session_verifier_session = session;
  14504. return SSLVerifierResponse::NoDecisionMade;
  14505. });
  14506. auto res = cli.Get("/test");
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. EXPECT_NE(nullptr, verifier_session);
  14509. EXPECT_EQ(session_verifier_session, verifier_session);
  14510. }
  14511. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14512. using httplib::tls::TlsError;
  14513. // Test that verify_error_to_string returns empty for success
  14514. std::string success_str = TlsError::verify_error_to_string(0);
  14515. EXPECT_TRUE(success_str.empty());
  14516. // Test that verify_error_to_string returns non-empty for error codes
  14517. // Using a common error code (certificate expired)
  14518. std::string error_str =
  14519. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14520. EXPECT_FALSE(error_str.empty());
  14521. }
  14522. TEST(SessionVerifierTest, CertificateAccepted) {
  14523. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14524. ASSERT_TRUE(svr.is_valid());
  14525. svr.Get("/test", [](const Request &, Response &res) {
  14526. res.set_content("ok", "text/plain");
  14527. });
  14528. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14529. auto se = detail::scope_exit([&] {
  14530. svr.stop();
  14531. t.join();
  14532. });
  14533. svr.wait_until_ready();
  14534. SSLClient cli(HOST, PORT);
  14535. cli.enable_server_certificate_verification(false);
  14536. cli.set_connection_timeout(30);
  14537. bool callback_called = false;
  14538. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14539. EXPECT_NE(session, nullptr);
  14540. callback_called = true;
  14541. return SSLVerifierResponse::CertificateAccepted;
  14542. });
  14543. auto res = cli.Get("/test");
  14544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14545. EXPECT_EQ(200, res->status);
  14546. EXPECT_TRUE(callback_called);
  14547. }
  14548. TEST(SessionVerifierTest, CertificateRejected) {
  14549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14550. ASSERT_TRUE(svr.is_valid());
  14551. svr.Get("/test", [](const Request &, Response &res) {
  14552. res.set_content("ok", "text/plain");
  14553. });
  14554. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14555. auto se = detail::scope_exit([&] {
  14556. svr.stop();
  14557. t.join();
  14558. });
  14559. svr.wait_until_ready();
  14560. SSLClient cli(HOST, PORT);
  14561. cli.enable_server_certificate_verification(false);
  14562. cli.set_connection_timeout(30);
  14563. bool callback_called = false;
  14564. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14565. EXPECT_NE(session, nullptr);
  14566. callback_called = true;
  14567. return SSLVerifierResponse::CertificateRejected;
  14568. });
  14569. auto res = cli.Get("/test");
  14570. EXPECT_FALSE(res);
  14571. EXPECT_TRUE(callback_called);
  14572. }
  14573. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14574. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14575. ASSERT_TRUE(svr.is_valid());
  14576. svr.Get("/test", [](const Request &, Response &res) {
  14577. res.set_content("ok", "text/plain");
  14578. });
  14579. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. });
  14584. svr.wait_until_ready();
  14585. // NoDecisionMade with verification disabled should succeed (no default check)
  14586. SSLClient cli(HOST, PORT);
  14587. cli.enable_server_certificate_verification(false);
  14588. cli.set_connection_timeout(30);
  14589. bool callback_called = false;
  14590. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14591. EXPECT_NE(session, nullptr);
  14592. callback_called = true;
  14593. return SSLVerifierResponse::NoDecisionMade;
  14594. });
  14595. auto res = cli.Get("/test");
  14596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14597. EXPECT_EQ(200, res->status);
  14598. EXPECT_TRUE(callback_called);
  14599. }
  14600. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14602. ASSERT_TRUE(svr.is_valid());
  14603. svr.Get("/test", [](const Request &, Response &res) {
  14604. res.set_content("ok", "text/plain");
  14605. });
  14606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. t.join();
  14610. });
  14611. svr.wait_until_ready();
  14612. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14613. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14614. // so we only check that the request fails, not whether the callback was
  14615. // called.
  14616. SSLClient cli(HOST, PORT);
  14617. cli.enable_server_certificate_verification(true);
  14618. cli.set_connection_timeout(30);
  14619. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14620. EXPECT_NE(session, nullptr);
  14621. return SSLVerifierResponse::NoDecisionMade;
  14622. });
  14623. auto res = cli.Get("/test");
  14624. EXPECT_FALSE(res);
  14625. }
  14626. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14627. // Test SSL server using PemMemory constructor with client CA certificates
  14628. // Read PEM files
  14629. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14630. read_file(SERVER_CERT_FILE, server_cert_pem);
  14631. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14632. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14633. // Create SSLServer with PemMemory constructor including client CA
  14634. SSLServer::PemMemory server_pem = {
  14635. server_cert_pem.c_str(),
  14636. server_cert_pem.size(),
  14637. server_key_pem.c_str(),
  14638. server_key_pem.size(),
  14639. client_ca_pem.c_str(),
  14640. client_ca_pem.size(),
  14641. nullptr // no password for server key
  14642. };
  14643. SSLServer svr(server_pem);
  14644. ASSERT_TRUE(svr.is_valid());
  14645. // No SSL error should be recorded for valid setup
  14646. EXPECT_EQ(0, svr.ssl_last_error());
  14647. // Set up server endpoints
  14648. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14649. res.set_content("ok", "text/plain");
  14650. });
  14651. // Start server in a thread
  14652. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14653. svr.wait_until_ready();
  14654. // Connect with client certificate (using constructor with paths)
  14655. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14656. cli.enable_server_certificate_verification(false);
  14657. auto res = cli.Get("/test-pem-ca");
  14658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14659. EXPECT_EQ(200, res->status);
  14660. EXPECT_EQ("ok", res->body);
  14661. svr.stop();
  14662. server_thread.join();
  14663. }
  14664. #endif
  14665. #ifdef _WIN32
  14666. TEST(CleanupTest, WSACleanup) {
  14667. int ret = WSACleanup();
  14668. ASSERT_EQ(0, ret);
  14669. }
  14670. #endif
  14671. #ifndef CPPHTTPLIB_SSL_ENABLED
  14672. TEST(NoSSLSupport, SimpleInterface) {
  14673. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14674. }
  14675. #endif
  14676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14677. TEST(InvalidScheme, SimpleInterface) {
  14678. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14679. }
  14680. #endif
  14681. TEST(NoScheme, SimpleInterface) {
  14682. Client cli("yahoo.com:80");
  14683. ASSERT_TRUE(cli.is_valid());
  14684. }
  14685. TEST(SendAPI, SimpleInterface_Online) {
  14686. Client cli("http://yahoo.com");
  14687. Request req;
  14688. req.method = "GET";
  14689. req.path = "/";
  14690. auto res = cli.send(req);
  14691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14692. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14693. }
  14694. TEST(SendAPI, WithParamsInRequest) {
  14695. Server svr;
  14696. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14697. EXPECT_TRUE(req.has_param("test"));
  14698. EXPECT_EQ("test_value", req.get_param_value("test"));
  14699. });
  14700. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14701. auto se = detail::scope_exit([&] {
  14702. svr.stop();
  14703. t.join();
  14704. ASSERT_FALSE(svr.is_running());
  14705. });
  14706. svr.wait_until_ready();
  14707. Client cli(HOST, PORT);
  14708. {
  14709. Request req;
  14710. req.method = "GET";
  14711. req.path = "/";
  14712. req.params.emplace("test", "test_value");
  14713. auto res = cli.send(req);
  14714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14715. }
  14716. {
  14717. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14719. }
  14720. }
  14721. TEST(ClientImplMethods, GetSocketTest) {
  14722. httplib::Server svr;
  14723. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14724. res.status = StatusCode::OK_200;
  14725. });
  14726. auto port = svr.bind_to_any_port("127.0.0.1");
  14727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. thread.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. {
  14735. httplib::Client cli("127.0.0.1", port);
  14736. cli.set_keep_alive(true);
  14737. // Use the behavior of cpp-httplib of opening the connection
  14738. // only when the first request happens. If that changes,
  14739. // this test would be obsolete.
  14740. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14741. // This also implicitly tests the server. But other tests would fail much
  14742. // earlier than this one to be considered.
  14743. auto res = cli.Get("/");
  14744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14745. EXPECT_EQ(StatusCode::OK_200, res->status);
  14746. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14747. }
  14748. }
  14749. #ifdef CPPHTTPLIB_SSL_ENABLED
  14750. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14751. Client cli("http://yahoo.com");
  14752. auto res = cli.Get("/");
  14753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14754. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14755. cli.set_follow_location(true);
  14756. res = cli.Get("/");
  14757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14758. EXPECT_EQ(StatusCode::OK_200, res->status);
  14759. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14760. }
  14761. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14762. Client cli("https://yahoo.com");
  14763. auto res = cli.Get("/");
  14764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14766. cli.set_follow_location(true);
  14767. res = cli.Get("/");
  14768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14769. EXPECT_EQ(StatusCode::OK_200, res->status);
  14770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14771. }
  14772. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14773. Client cli("https://yahoo.com");
  14774. auto res = cli.Get("/");
  14775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14776. ASSERT_FALSE(!res);
  14777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14778. ASSERT_FALSE(res == nullptr);
  14779. ASSERT_TRUE(res != nullptr);
  14780. EXPECT_EQ(Error::Success, res.error());
  14781. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14782. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14783. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14784. cli.set_follow_location(true);
  14785. res = cli.Get("/");
  14786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14787. EXPECT_EQ(Error::Success, res.error());
  14788. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14789. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14790. EXPECT_EQ(StatusCode::OK_200, res->status);
  14791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14792. }
  14793. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14794. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14795. Client cli("https://cdnjs.cloudflare.com");
  14796. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14797. Headers{{"Accept-Encoding", "br"}});
  14798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14799. EXPECT_EQ(StatusCode::OK_200, res->status);
  14800. EXPECT_EQ(287630U, res->body.size());
  14801. EXPECT_EQ("application/javascript; charset=utf-8",
  14802. res->get_header_value("Content-Type"));
  14803. }
  14804. #endif
  14805. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14806. #undef REDIR_HOST // Silence compiler warning
  14807. #define REDIR_HOST "https://httpbingo.org"
  14808. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14809. Client cli(REDIR_HOST);
  14810. cli.set_follow_location(true);
  14811. auto res =
  14812. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14814. EXPECT_EQ(StatusCode::OK_200, res->status);
  14815. }
  14816. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14817. Client cli(REDIR_HOST);
  14818. cli.set_follow_location(true);
  14819. Params params;
  14820. params.emplace("url", "http://example.com");
  14821. params.emplace("status_code", "302");
  14822. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14824. EXPECT_EQ(StatusCode::OK_200, res->status);
  14825. }
  14826. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14827. Client cli(REDIR_HOST);
  14828. cli.set_follow_location(true);
  14829. Params params;
  14830. params.emplace("url", "http://example.com");
  14831. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14833. EXPECT_EQ(StatusCode::OK_200, res->status);
  14834. }
  14835. TEST(HttpToHttpsRedirectTest, CertFile) {
  14836. auto ssl_port = PORT + 1;
  14837. Server svr;
  14838. ASSERT_TRUE(svr.is_valid());
  14839. svr.Get("/index", [&](const Request &, Response &res) {
  14840. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14841. "/index");
  14842. svr.stop();
  14843. });
  14844. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14845. ASSERT_TRUE(ssl_svr.is_valid());
  14846. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14847. res.set_content("test", "text/plain");
  14848. ssl_svr.stop();
  14849. });
  14850. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14851. thread t2 =
  14852. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14853. auto se = detail::scope_exit([&] {
  14854. t2.join();
  14855. t.join();
  14856. ASSERT_FALSE(svr.is_running());
  14857. });
  14858. svr.wait_until_ready();
  14859. ssl_svr.wait_until_ready();
  14860. Client cli("127.0.0.1", PORT);
  14861. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14862. cli.enable_server_certificate_verification(true);
  14863. cli.set_follow_location(true);
  14864. cli.set_connection_timeout(30);
  14865. auto res = cli.Get("/index");
  14866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14867. ASSERT_EQ(StatusCode::OK_200, res->status);
  14868. }
  14869. TEST(SSLClientRedirectTest, CertFile) {
  14870. auto ssl_port = PORT + 1;
  14871. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14872. ASSERT_TRUE(ssl_svr1.is_valid());
  14873. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14874. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14875. "/index");
  14876. ssl_svr1.stop();
  14877. });
  14878. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14879. ASSERT_TRUE(ssl_svr2.is_valid());
  14880. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14881. res.set_content("test", "text/plain");
  14882. ssl_svr2.stop();
  14883. });
  14884. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14885. thread t2 =
  14886. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14887. auto se = detail::scope_exit([&] {
  14888. t2.join();
  14889. t.join();
  14890. ASSERT_FALSE(ssl_svr1.is_running());
  14891. });
  14892. ssl_svr1.wait_until_ready();
  14893. ssl_svr2.wait_until_ready();
  14894. SSLClient cli("127.0.0.1", PORT);
  14895. std::string cert;
  14896. read_file(SERVER_CERT2_FILE, cert);
  14897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14898. cli.enable_server_certificate_verification(true);
  14899. cli.set_follow_location(true);
  14900. cli.set_connection_timeout(30);
  14901. auto res = cli.Get("/index");
  14902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14903. ASSERT_EQ(StatusCode::OK_200, res->status);
  14904. }
  14905. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14906. // another port, so the client follows it with a new client.
  14907. static Result GetThroughTlsRedirectToDifferentPort(
  14908. const std::function<void(SSLClient &)> &setup,
  14909. const char *target_cert = SERVER_CERT2_FILE,
  14910. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14911. auto ssl_port = PORT + 1;
  14912. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14913. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14914. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14915. "/index");
  14916. });
  14917. SSLServer ssl_svr2(target_cert, target_key);
  14918. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14919. res.set_content("test", "text/plain");
  14920. });
  14921. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14922. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14923. auto se = detail::scope_exit([&] {
  14924. ssl_svr2.stop();
  14925. ssl_svr1.stop();
  14926. t2.join();
  14927. t.join();
  14928. });
  14929. ssl_svr1.wait_until_ready();
  14930. ssl_svr2.wait_until_ready();
  14931. SSLClient cli("127.0.0.1", PORT);
  14932. cli.set_follow_location(true);
  14933. cli.set_connection_timeout(30);
  14934. setup(cli);
  14935. return cli.Get("/index");
  14936. }
  14937. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14938. auto calls = 0;
  14939. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14940. cli.enable_server_certificate_verification(false);
  14941. // Accept the first server only.
  14942. cli.set_session_verifier([&](tls::session_t) {
  14943. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14944. : SSLVerifierResponse::CertificateRejected;
  14945. });
  14946. });
  14947. ASSERT_FALSE(res);
  14948. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14949. EXPECT_EQ(2, calls);
  14950. }
  14951. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14952. std::string pinned;
  14953. auto res = GetThroughTlsRedirectToDifferentPort(
  14954. [&](SSLClient &cli) {
  14955. cli.enable_server_certificate_verification(false);
  14956. // Pin the first certificate seen.
  14957. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14958. if (pinned.empty()) { pinned = ctx.serial(); }
  14959. return ctx.serial() == pinned;
  14960. });
  14961. },
  14962. // A certificate other than the first server's.
  14963. SERVER_CERT_FILE);
  14964. EXPECT_FALSE(res);
  14965. EXPECT_FALSE(pinned.empty());
  14966. }
  14967. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14968. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14969. std::string cert;
  14970. read_file(SERVER_CERT2_FILE, cert);
  14971. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14972. });
  14973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::OK_200, res->status);
  14975. }
  14976. // The target's certificate is signed by the root CA, which the first server's
  14977. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14978. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14979. auto res = GetThroughTlsRedirectToDifferentPort(
  14980. [](SSLClient &cli) {
  14981. std::string root_ca, cert;
  14982. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14983. read_file(SERVER_CERT2_FILE, cert);
  14984. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14985. cli.load_ca_cert_store(cert.data(), cert.size());
  14986. cli.enable_server_hostname_verification(false);
  14987. },
  14988. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14990. EXPECT_EQ(StatusCode::OK_200, res->status);
  14991. }
  14992. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14993. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14994. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14995. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14996. auto res = GetThroughTlsRedirectToDifferentPort(
  14997. [](SSLClient &cli) {
  14998. std::string root_ca, cert;
  14999. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15000. read_file(SERVER_CERT2_FILE, cert);
  15001. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15002. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15003. cli.enable_server_hostname_verification(false);
  15004. },
  15005. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15006. ASSERT_FALSE(res);
  15007. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15008. }
  15009. #endif
  15010. #endif
  15011. #ifdef CPPHTTPLIB_SSL_ENABLED
  15012. // Test that set_ca_cert_store() skips system certs (consistent with
  15013. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15014. // should be trusted - system certs should NOT be loaded.
  15015. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15016. // Load a specific cert that is NOT a system CA cert
  15017. std::string cert;
  15018. read_file(SERVER_CERT2_FILE, cert);
  15019. SSLClient cli("google.com");
  15020. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15021. cli.enable_server_certificate_verification(true);
  15022. // This should FAIL because:
  15023. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15024. // 2. System certs should NOT be loaded when custom store is set
  15025. // If system certs WERE loaded, this would succeed
  15026. auto res = cli.Get("/");
  15027. ASSERT_FALSE(res);
  15028. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15029. }
  15030. // Same as above, but through the native store handle path. Regression test:
  15031. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15032. // merged system certs into the user-provided store.
  15033. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15034. std::string cert;
  15035. read_file(SERVER_CERT2_FILE, cert);
  15036. SSLClient cli("google.com");
  15037. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15038. cli.enable_server_certificate_verification(true);
  15039. auto res = cli.Get("/");
  15040. ASSERT_FALSE(res);
  15041. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15042. }
  15043. // A custom store set via the native handle must still verify a server whose
  15044. // cert it does contain.
  15045. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15046. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15047. ASSERT_TRUE(svr.is_valid());
  15048. svr.Get("/test", [&](const Request &, Response &res) {
  15049. res.set_content("test", "text/plain");
  15050. });
  15051. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15052. auto se = detail::scope_exit([&] {
  15053. svr.stop();
  15054. t.join();
  15055. ASSERT_FALSE(svr.is_running());
  15056. });
  15057. svr.wait_until_ready();
  15058. SSLClient cli("127.0.0.1", PORT);
  15059. std::string cert;
  15060. read_file(SERVER_CERT2_FILE, cert);
  15061. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15062. cli.enable_server_certificate_verification(true);
  15063. cli.set_connection_timeout(30);
  15064. auto res = cli.Get("/test");
  15065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15066. ASSERT_EQ(StatusCode::OK_200, res->status);
  15067. }
  15068. // CA certs loaded through the universal Client must be transferred to the
  15069. // client created internally for following an HTTPS redirect. Regression test:
  15070. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15071. // the CA data for redirect transfer.
  15072. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15073. auto ssl_port = PORT + 1;
  15074. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15075. ASSERT_TRUE(ssl_svr1.is_valid());
  15076. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15077. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15078. "/index");
  15079. });
  15080. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15081. ASSERT_TRUE(ssl_svr2.is_valid());
  15082. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15083. res.set_content("test", "text/plain");
  15084. });
  15085. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15086. thread t2 =
  15087. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15088. auto se = detail::scope_exit([&] {
  15089. ssl_svr2.stop();
  15090. ssl_svr1.stop();
  15091. t2.join();
  15092. t.join();
  15093. ASSERT_FALSE(ssl_svr1.is_running());
  15094. });
  15095. ssl_svr1.wait_until_ready();
  15096. ssl_svr2.wait_until_ready();
  15097. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15098. std::string cert;
  15099. read_file(SERVER_CERT2_FILE, cert);
  15100. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15101. cli.enable_server_certificate_verification(true);
  15102. cli.set_follow_location(true);
  15103. cli.set_connection_timeout(30);
  15104. auto res = cli.Get("/index");
  15105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15106. ASSERT_EQ(StatusCode::OK_200, res->status);
  15107. }
  15108. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15109. // so a host signed by a system CA verifies even though a custom CA is set
  15110. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15111. std::string cert;
  15112. read_file(SERVER_CERT2_FILE, cert);
  15113. SSLClient cli("google.com");
  15114. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15115. cli.enable_system_ca(true);
  15116. cli.enable_server_certificate_verification(true);
  15117. auto res = cli.Get("/");
  15118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15119. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15120. }
  15121. // The custom CA remains effective when combined with the system CA
  15122. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15123. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15124. ASSERT_TRUE(svr.is_valid());
  15125. svr.Get("/test", [&](const Request &, Response &res) {
  15126. res.set_content("test", "text/plain");
  15127. });
  15128. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15129. auto se = detail::scope_exit([&] {
  15130. svr.stop();
  15131. t.join();
  15132. ASSERT_FALSE(svr.is_running());
  15133. });
  15134. svr.wait_until_ready();
  15135. SSLClient cli("127.0.0.1", PORT);
  15136. std::string cert;
  15137. read_file(SERVER_CERT2_FILE, cert);
  15138. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15139. cli.enable_system_ca(true);
  15140. cli.enable_server_certificate_verification(true);
  15141. cli.set_connection_timeout(30);
  15142. auto res = cli.Get("/test");
  15143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15144. ASSERT_EQ(StatusCode::OK_200, res->status);
  15145. }
  15146. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15147. // skip chain verification entirely (only the certificate identity was
  15148. // checked), so a server presenting an untrusted certificate with a matching
  15149. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15150. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15151. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15152. ASSERT_TRUE(svr.is_valid());
  15153. svr.Get("/test", [&](const Request &, Response &res) {
  15154. res.set_content("test", "text/plain");
  15155. });
  15156. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. t.join();
  15160. ASSERT_FALSE(svr.is_running());
  15161. });
  15162. svr.wait_until_ready();
  15163. SSLClient cli("127.0.0.1", PORT);
  15164. std::string cert;
  15165. // A trusted CA that did not sign the server certificate. The server cert
  15166. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15167. // this connection.
  15168. read_file(CLIENT_CA_CERT_FILE, cert);
  15169. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15170. cli.enable_server_certificate_verification(true);
  15171. cli.set_connection_timeout(30);
  15172. auto res = cli.Get("/test");
  15173. ASSERT_FALSE(res);
  15174. }
  15175. // enable_system_ca(false) prevents system CA loading entirely
  15176. TEST(SSLClientTest, DisableSystemCa_Online) {
  15177. SSLClient cli("google.com");
  15178. cli.enable_system_ca(false);
  15179. cli.enable_server_certificate_verification(true);
  15180. auto res = cli.Get("/");
  15181. ASSERT_FALSE(res);
  15182. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15183. // itself when the CA chain is empty
  15184. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15185. res.error() == Error::SSLConnection);
  15186. }
  15187. // The universal Client forwards enable_system_ca()
  15188. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15189. std::string cert;
  15190. read_file(SERVER_CERT2_FILE, cert);
  15191. Client cli("https://google.com");
  15192. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15193. cli.enable_system_ca(true);
  15194. cli.enable_server_certificate_verification(true);
  15195. auto res = cli.Get("/");
  15196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15197. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15198. }
  15199. // The system CA policy must carry over to the client created internally for
  15200. // following a cross-host HTTPS redirect
  15201. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15202. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15203. ASSERT_TRUE(svr.is_valid());
  15204. svr.Get("/index", [&](const Request &, Response &res) {
  15205. res.set_redirect("https://www.google.com/");
  15206. });
  15207. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15208. auto se = detail::scope_exit([&] {
  15209. svr.stop();
  15210. t.join();
  15211. ASSERT_FALSE(svr.is_running());
  15212. });
  15213. svr.wait_until_ready();
  15214. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15215. std::string cert;
  15216. read_file(SERVER_CERT2_FILE, cert);
  15217. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15218. cli.enable_system_ca(true);
  15219. cli.enable_server_certificate_verification(true);
  15220. cli.set_follow_location(true);
  15221. cli.set_connection_timeout(30);
  15222. // Receiving any response proves the redirect client completed the TLS
  15223. // handshake with a system-CA-signed host
  15224. auto res = cli.Get("/index");
  15225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15226. }
  15227. TEST(MultipartFormDataTest, LargeData) {
  15228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15229. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15230. const ContentReader &content_reader) {
  15231. if (req.is_multipart_form_data()) {
  15232. std::vector<FormData> items;
  15233. content_reader(
  15234. [&](const FormData &file) {
  15235. items.push_back(file);
  15236. return true;
  15237. },
  15238. [&](const char *data, size_t data_length) {
  15239. items.back().content.append(data, data_length);
  15240. return true;
  15241. });
  15242. EXPECT_TRUE(std::string(items[0].name) == "document");
  15243. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15244. EXPECT_TRUE(items[0].filename == "2MB_data");
  15245. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15246. EXPECT_TRUE(items[1].name == "hello");
  15247. EXPECT_TRUE(items[1].content == "world");
  15248. EXPECT_TRUE(items[1].filename == "");
  15249. EXPECT_TRUE(items[1].content_type == "");
  15250. } else {
  15251. std::string body;
  15252. content_reader([&](const char *data, size_t data_length) {
  15253. body.append(data, data_length);
  15254. return true;
  15255. });
  15256. }
  15257. });
  15258. auto port = svr.bind_to_any_port(HOST);
  15259. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15260. auto se = detail::scope_exit([&] {
  15261. svr.stop();
  15262. t.join();
  15263. ASSERT_FALSE(svr.is_running());
  15264. });
  15265. svr.wait_until_ready();
  15266. {
  15267. std::string data(1024 * 1024 * 2, '.');
  15268. std::stringstream buffer;
  15269. buffer << data;
  15270. SSLClient cli(HOST, port);
  15271. cli.enable_server_certificate_verification(false);
  15272. UploadFormDataItems items{
  15273. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15274. {"hello", "world", "", ""},
  15275. };
  15276. auto res = cli.Post("/post", items);
  15277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15278. ASSERT_EQ(StatusCode::OK_200, res->status);
  15279. }
  15280. }
  15281. TEST(MultipartFormDataTest, DataProviderItems) {
  15282. std::random_device seed_gen;
  15283. std::mt19937 random(seed_gen());
  15284. std::string rand1;
  15285. rand1.resize(1000);
  15286. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15287. std::string rand2;
  15288. rand2.resize(3000);
  15289. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15290. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15291. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15292. const ContentReader &content_reader) {
  15293. ASSERT_FALSE(req.is_multipart_form_data());
  15294. std::string body;
  15295. content_reader([&](const char *data, size_t data_length) {
  15296. body.append(data, data_length);
  15297. return true;
  15298. });
  15299. EXPECT_EQ(body, "");
  15300. });
  15301. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15302. const ContentReader &content_reader) {
  15303. ASSERT_TRUE(req.is_multipart_form_data());
  15304. std::vector<FormData> items;
  15305. content_reader(
  15306. [&](const FormData &file) {
  15307. items.push_back(file);
  15308. return true;
  15309. },
  15310. [&](const char *data, size_t data_length) {
  15311. items.back().content.append(data, data_length);
  15312. return true;
  15313. });
  15314. ASSERT_TRUE(items.size() == 2);
  15315. EXPECT_EQ(std::string(items[0].name), "name1");
  15316. EXPECT_EQ(items[0].content, "Testing123");
  15317. EXPECT_EQ(items[0].filename, "filename1");
  15318. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15319. EXPECT_EQ(items[1].name, "name2");
  15320. EXPECT_EQ(items[1].content, "Testing456");
  15321. EXPECT_EQ(items[1].filename, "");
  15322. EXPECT_EQ(items[1].content_type, "");
  15323. });
  15324. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15325. const ContentReader &content_reader) {
  15326. ASSERT_TRUE(req.is_multipart_form_data());
  15327. std::vector<FormData> items;
  15328. content_reader(
  15329. [&](const FormData &file) {
  15330. items.push_back(file);
  15331. return true;
  15332. },
  15333. [&](const char *data, size_t data_length) {
  15334. items.back().content.append(data, data_length);
  15335. return true;
  15336. });
  15337. ASSERT_TRUE(items.size() == 2);
  15338. EXPECT_EQ(items[0].name, "name3");
  15339. EXPECT_EQ(items[0].content, rand1);
  15340. EXPECT_EQ(items[0].filename, "filename3");
  15341. EXPECT_EQ(items[0].content_type, "");
  15342. EXPECT_EQ(items[1].name, "name4");
  15343. EXPECT_EQ(items[1].content, rand2);
  15344. EXPECT_EQ(items[1].filename, "filename4");
  15345. EXPECT_EQ(items[1].content_type, "");
  15346. });
  15347. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15348. const ContentReader &content_reader) {
  15349. ASSERT_TRUE(req.is_multipart_form_data());
  15350. std::vector<FormData> items;
  15351. content_reader(
  15352. [&](const FormData &file) {
  15353. items.push_back(file);
  15354. return true;
  15355. },
  15356. [&](const char *data, size_t data_length) {
  15357. items.back().content.append(data, data_length);
  15358. return true;
  15359. });
  15360. ASSERT_TRUE(items.size() == 4);
  15361. EXPECT_EQ(std::string(items[0].name), "name1");
  15362. EXPECT_EQ(items[0].content, "Testing123");
  15363. EXPECT_EQ(items[0].filename, "filename1");
  15364. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15365. EXPECT_EQ(items[1].name, "name2");
  15366. EXPECT_EQ(items[1].content, "Testing456");
  15367. EXPECT_EQ(items[1].filename, "");
  15368. EXPECT_EQ(items[1].content_type, "");
  15369. EXPECT_EQ(items[2].name, "name3");
  15370. EXPECT_EQ(items[2].content, rand1);
  15371. EXPECT_EQ(items[2].filename, "filename3");
  15372. EXPECT_EQ(items[2].content_type, "");
  15373. EXPECT_EQ(items[3].name, "name4");
  15374. EXPECT_EQ(items[3].content, rand2);
  15375. EXPECT_EQ(items[3].filename, "filename4");
  15376. EXPECT_EQ(items[3].content_type, "");
  15377. });
  15378. auto port = svr.bind_to_any_port("localhost");
  15379. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15380. auto se = detail::scope_exit([&] {
  15381. svr.stop();
  15382. t.join();
  15383. ASSERT_FALSE(svr.is_running());
  15384. });
  15385. svr.wait_until_ready();
  15386. {
  15387. SSLClient cli("localhost", port);
  15388. cli.enable_server_certificate_verification(false);
  15389. UploadFormDataItems items{
  15390. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15391. {"name2", "Testing456", "", ""}, // not a file
  15392. };
  15393. {
  15394. auto res = cli.Post("/post-none", {}, {}, {});
  15395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15396. ASSERT_EQ(StatusCode::OK_200, res->status);
  15397. }
  15398. FormDataProviderItems providers;
  15399. {
  15400. auto res =
  15401. cli.Post("/post-items", {}, items, providers); // empty providers
  15402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15403. ASSERT_EQ(StatusCode::OK_200, res->status);
  15404. }
  15405. providers.push_back({"name3",
  15406. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15407. // test the offset is given correctly at each step
  15408. if (!offset)
  15409. sink.os.write(rand1.data(), 30);
  15410. else if (offset == 30)
  15411. sink.os.write(rand1.data() + 30, 300);
  15412. else if (offset == 330)
  15413. sink.os.write(rand1.data() + 330, 670);
  15414. else if (offset == rand1.size())
  15415. sink.done();
  15416. return true;
  15417. },
  15418. "filename3",
  15419. {}});
  15420. providers.push_back({"name4",
  15421. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15422. // test the offset is given correctly at each step
  15423. if (!offset)
  15424. sink.os.write(rand2.data(), 2000);
  15425. else if (offset == 2000)
  15426. sink.os.write(rand2.data() + 2000, 1);
  15427. else if (offset == 2001)
  15428. sink.os.write(rand2.data() + 2001, 999);
  15429. else if (offset == rand2.size())
  15430. sink.done();
  15431. return true;
  15432. },
  15433. "filename4",
  15434. {}});
  15435. {
  15436. auto res = cli.Post("/post-providers", {}, {}, providers);
  15437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15438. ASSERT_EQ(StatusCode::OK_200, res->status);
  15439. }
  15440. {
  15441. auto res = cli.Post("/post-both", {}, items, providers);
  15442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15443. ASSERT_EQ(StatusCode::OK_200, res->status);
  15444. }
  15445. }
  15446. }
  15447. TEST(MultipartFormDataTest, BadHeader) {
  15448. Server svr;
  15449. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15450. res.set_content("ok", "text/plain");
  15451. });
  15452. thread t = thread([&] { svr.listen(HOST, PORT); });
  15453. auto se = detail::scope_exit([&] {
  15454. svr.stop();
  15455. t.join();
  15456. ASSERT_FALSE(svr.is_running());
  15457. });
  15458. svr.wait_until_ready();
  15459. const std::string body =
  15460. "This is the preamble. It is to be ignored, though it\r\n"
  15461. "is a handy place for composition agents to include an\r\n"
  15462. "explanatory note to non-MIME conformant readers.\r\n"
  15463. "\r\n"
  15464. "\r\n"
  15465. "--simple boundary\r\n"
  15466. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15467. ": BAD...\r\n"
  15468. "\r\n"
  15469. "value1\r\n"
  15470. "--simple boundary\r\n"
  15471. "Content-Disposition: form-data; name=\"field2\"; "
  15472. "filename=\"example.txt\"\r\n"
  15473. "\r\n"
  15474. "value2\r\n"
  15475. "--simple boundary--\r\n"
  15476. "This is the epilogue. It is also to be ignored.\r\n";
  15477. std::string content_type =
  15478. R"(multipart/form-data; boundary="simple boundary")";
  15479. Client cli(HOST, PORT);
  15480. auto res = cli.Post("/post", body, content_type.c_str());
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15483. }
  15484. TEST(MultipartFormDataTest, WithPreamble) {
  15485. Server svr;
  15486. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15487. res.set_content("ok", "text/plain");
  15488. });
  15489. thread t = thread([&] { svr.listen(HOST, PORT); });
  15490. auto se = detail::scope_exit([&] {
  15491. svr.stop();
  15492. t.join();
  15493. ASSERT_FALSE(svr.is_running());
  15494. });
  15495. svr.wait_until_ready();
  15496. const std::string body =
  15497. "This is the preamble. It is to be ignored, though it\r\n"
  15498. "is a handy place for composition agents to include an\r\n"
  15499. "explanatory note to non-MIME conformant readers.\r\n"
  15500. "\r\n"
  15501. "\r\n"
  15502. "--simple boundary\r\n"
  15503. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15504. "\r\n"
  15505. "value1\r\n"
  15506. "--simple boundary\r\n"
  15507. "Content-Disposition: form-data; name=\"field2\"; "
  15508. "filename=\"example.txt\"\r\n"
  15509. "\r\n"
  15510. "value2\r\n"
  15511. "--simple boundary--\r\n"
  15512. "This is the epilogue. It is also to be ignored.\r\n";
  15513. std::string content_type =
  15514. R"(multipart/form-data; boundary="simple boundary")";
  15515. Client cli(HOST, PORT);
  15516. auto res = cli.Post("/post", body, content_type.c_str());
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. EXPECT_EQ(StatusCode::OK_200, res->status);
  15519. }
  15520. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15522. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15523. const ContentReader &content_reader) {
  15524. if (req.is_multipart_form_data()) {
  15525. std::vector<FormData> items;
  15526. content_reader(
  15527. [&](const FormData &file) {
  15528. items.push_back(file);
  15529. return true;
  15530. },
  15531. [&](const char *data, size_t data_length) {
  15532. items.back().content.append(data, data_length);
  15533. return true;
  15534. });
  15535. EXPECT_TRUE(std::string(items[0].name) == "document");
  15536. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15537. EXPECT_TRUE(items[0].filename == "2MB_data");
  15538. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15539. EXPECT_TRUE(items[1].name == "hello");
  15540. EXPECT_TRUE(items[1].content == "world");
  15541. EXPECT_TRUE(items[1].filename == "");
  15542. EXPECT_TRUE(items[1].content_type == "");
  15543. } else {
  15544. std::string body;
  15545. content_reader([&](const char *data, size_t data_length) {
  15546. body.append(data, data_length);
  15547. return true;
  15548. });
  15549. }
  15550. });
  15551. auto port = svr.bind_to_any_port("localhost");
  15552. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15553. auto se = detail::scope_exit([&] {
  15554. svr.stop();
  15555. t.join();
  15556. ASSERT_FALSE(svr.is_running());
  15557. });
  15558. svr.wait_until_ready();
  15559. {
  15560. std::string data(1024 * 1024 * 2, '.');
  15561. std::stringstream buffer;
  15562. buffer << data;
  15563. SSLClient cli("localhost", port);
  15564. cli.enable_server_certificate_verification(false);
  15565. UploadFormDataItems items{
  15566. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15567. {"hello", "world", "", ""},
  15568. };
  15569. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15571. ASSERT_EQ(StatusCode::OK_200, res->status);
  15572. }
  15573. }
  15574. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15575. std::string data(1024 * 1024 * 2, '&');
  15576. std::stringstream buffer;
  15577. buffer << data;
  15578. Client cli("https://localhost:8080");
  15579. UploadFormDataItems items{
  15580. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15581. {"hello", "world", "", ""},
  15582. };
  15583. for (const char &c : " \t\r\n") {
  15584. auto res =
  15585. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15586. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15587. ASSERT_FALSE(res);
  15588. }
  15589. }
  15590. TEST(MultipartFormDataTest, PutFormData) {
  15591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15592. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15593. const ContentReader &content_reader) {
  15594. if (req.is_multipart_form_data()) {
  15595. std::vector<FormData> items;
  15596. content_reader(
  15597. [&](const FormData &file) {
  15598. items.push_back(file);
  15599. return true;
  15600. },
  15601. [&](const char *data, size_t data_length) {
  15602. items.back().content.append(data, data_length);
  15603. return true;
  15604. });
  15605. EXPECT_TRUE(std::string(items[0].name) == "document");
  15606. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15607. EXPECT_TRUE(items[0].filename == "2MB_data");
  15608. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15609. EXPECT_TRUE(items[1].name == "hello");
  15610. EXPECT_TRUE(items[1].content == "world");
  15611. EXPECT_TRUE(items[1].filename == "");
  15612. EXPECT_TRUE(items[1].content_type == "");
  15613. } else {
  15614. std::string body;
  15615. content_reader([&](const char *data, size_t data_length) {
  15616. body.append(data, data_length);
  15617. return true;
  15618. });
  15619. }
  15620. });
  15621. auto port = svr.bind_to_any_port("localhost");
  15622. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15623. auto se = detail::scope_exit([&] {
  15624. svr.stop();
  15625. t.join();
  15626. ASSERT_FALSE(svr.is_running());
  15627. });
  15628. svr.wait_until_ready();
  15629. {
  15630. std::string data(1024 * 1024 * 2, '&');
  15631. std::stringstream buffer;
  15632. buffer << data;
  15633. SSLClient cli("localhost", port);
  15634. cli.enable_server_certificate_verification(false);
  15635. UploadFormDataItems items{
  15636. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15637. {"hello", "world", "", ""},
  15638. };
  15639. auto res = cli.Put("/put", items);
  15640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15641. ASSERT_EQ(StatusCode::OK_200, res->status);
  15642. }
  15643. }
  15644. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15646. svr.Put("/put_customboundary",
  15647. [&](const Request &req, const Response & /*res*/,
  15648. const ContentReader &content_reader) {
  15649. if (req.is_multipart_form_data()) {
  15650. std::vector<FormData> items;
  15651. content_reader(
  15652. [&](const FormData &file) {
  15653. items.push_back(file);
  15654. return true;
  15655. },
  15656. [&](const char *data, size_t data_length) {
  15657. items.back().content.append(data, data_length);
  15658. return true;
  15659. });
  15660. EXPECT_TRUE(std::string(items[0].name) == "document");
  15661. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15662. EXPECT_TRUE(items[0].filename == "2MB_data");
  15663. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15664. EXPECT_TRUE(items[1].name == "hello");
  15665. EXPECT_TRUE(items[1].content == "world");
  15666. EXPECT_TRUE(items[1].filename == "");
  15667. EXPECT_TRUE(items[1].content_type == "");
  15668. } else {
  15669. std::string body;
  15670. content_reader([&](const char *data, size_t data_length) {
  15671. body.append(data, data_length);
  15672. return true;
  15673. });
  15674. }
  15675. });
  15676. auto port = svr.bind_to_any_port("localhost");
  15677. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15678. auto se = detail::scope_exit([&] {
  15679. svr.stop();
  15680. t.join();
  15681. ASSERT_FALSE(svr.is_running());
  15682. });
  15683. svr.wait_until_ready();
  15684. {
  15685. std::string data(1024 * 1024 * 2, '&');
  15686. std::stringstream buffer;
  15687. buffer << data;
  15688. SSLClient cli("localhost", port);
  15689. cli.enable_server_certificate_verification(false);
  15690. UploadFormDataItems items{
  15691. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15692. {"hello", "world", "", ""},
  15693. };
  15694. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15696. ASSERT_EQ(StatusCode::OK_200, res->status);
  15697. }
  15698. }
  15699. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15700. std::string data(1024 * 1024 * 2, '&');
  15701. std::stringstream buffer;
  15702. buffer << data;
  15703. Client cli("https://localhost:8080");
  15704. cli.enable_server_certificate_verification(false);
  15705. UploadFormDataItems items{
  15706. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15707. {"hello", "world", "", ""},
  15708. };
  15709. for (const char &c : " \t\r\n") {
  15710. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15711. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15712. ASSERT_FALSE(res);
  15713. }
  15714. }
  15715. TEST(MultipartFormDataTest, AlternateFilename) {
  15716. auto handled = false;
  15717. Server svr;
  15718. svr.Post("/test", [&](const Request &req, Response &res) {
  15719. ASSERT_EQ(2u, req.form.files.size());
  15720. ASSERT_EQ(1u, req.form.fields.size());
  15721. // Test files
  15722. const auto &file1 = req.form.get_file("file1");
  15723. ASSERT_EQ("file1", file1.name);
  15724. ASSERT_EQ("A.txt", file1.filename);
  15725. ASSERT_EQ("text/plain", file1.content_type);
  15726. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15727. const auto &file2 = req.form.get_file("file2");
  15728. ASSERT_EQ("file2", file2.name);
  15729. ASSERT_EQ("a.html", file2.filename);
  15730. ASSERT_EQ("text/html", file2.content_type);
  15731. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15732. file2.content);
  15733. // Test text field
  15734. const auto &text = req.form.get_field("text");
  15735. ASSERT_EQ("text default", text);
  15736. res.set_content("ok", "text/plain");
  15737. handled = true;
  15738. });
  15739. thread t = thread([&] { svr.listen(HOST, PORT); });
  15740. auto se = detail::scope_exit([&] {
  15741. svr.stop();
  15742. t.join();
  15743. ASSERT_FALSE(svr.is_running());
  15744. ASSERT_TRUE(handled);
  15745. });
  15746. svr.wait_until_ready();
  15747. auto req = "POST /test HTTP/1.1\r\n"
  15748. "Host: localhost\r\n"
  15749. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15750. "Content-Length: 399\r\n"
  15751. "\r\n"
  15752. "----------\r\n"
  15753. "Content-Disposition: form-data; name=\"text\"\r\n"
  15754. "\r\n"
  15755. "text default\r\n"
  15756. "----------\r\n"
  15757. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15758. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15759. "Content-Type: text/plain\r\n"
  15760. "\r\n"
  15761. "Content of a.txt.\r\n"
  15762. "\r\n"
  15763. "----------\r\n"
  15764. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15765. "\"a.html\"\r\n"
  15766. "Content-Type: text/html\r\n"
  15767. "\r\n"
  15768. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15769. "\r\n"
  15770. "------------\r\n";
  15771. ASSERT_TRUE(send_request(1, req));
  15772. }
  15773. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15774. auto handled = false;
  15775. Server svr;
  15776. svr.Post("/test", [&](const Request &req, Response &res) {
  15777. // Case-insensitive "utf-8''" prefix with a long value
  15778. const auto &file = req.form.get_file("file1");
  15779. ASSERT_EQ("file1", file.name);
  15780. // 8000 chars exercises both the Content-Disposition parser and the
  15781. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15782. // Prior to the fix, std::regex_match on this header would cause O(N)
  15783. // stack recursion in libstdc++, leading to SIGSEGV.
  15784. std::string expected_filename(8000, 'A');
  15785. ASSERT_EQ(expected_filename, file.filename);
  15786. res.set_content("ok", "text/plain");
  15787. handled = true;
  15788. });
  15789. thread t = thread([&] { svr.listen(HOST, PORT); });
  15790. auto se = detail::scope_exit([&] {
  15791. svr.stop();
  15792. t.join();
  15793. ASSERT_FALSE(svr.is_running());
  15794. ASSERT_TRUE(handled);
  15795. });
  15796. svr.wait_until_ready();
  15797. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15798. // Regression test for GHSA-qq6v-r583-3h69
  15799. std::string long_filename(8000, 'A');
  15800. std::string body = "----------\r\n"
  15801. "Content-Disposition: form-data; name=\"file1\"; "
  15802. "filename*=\"Utf-8''" +
  15803. long_filename +
  15804. "\"\r\n"
  15805. "\r\n"
  15806. "hello\r\n"
  15807. "------------\r\n";
  15808. auto req = "POST /test HTTP/1.1\r\n"
  15809. "Host: localhost\r\n"
  15810. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15811. "Content-Length: " +
  15812. std::to_string(body.size()) + "\r\n\r\n" + body;
  15813. ASSERT_TRUE(send_request(1, req));
  15814. }
  15815. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15816. auto handled = false;
  15817. Server svr;
  15818. svr.Post("/test", [&](const Request &req, Response &) {
  15819. ASSERT_EQ(2u, req.form.fields.size());
  15820. const auto &text1 = req.form.get_field("text1");
  15821. ASSERT_EQ("text1", text1);
  15822. const auto &text2 = req.form.get_field("text2");
  15823. ASSERT_EQ("text2", text2);
  15824. handled = true;
  15825. });
  15826. thread t = thread([&] { svr.listen(HOST, PORT); });
  15827. auto se = detail::scope_exit([&] {
  15828. svr.stop();
  15829. t.join();
  15830. ASSERT_FALSE(svr.is_running());
  15831. ASSERT_TRUE(handled);
  15832. });
  15833. svr.wait_until_ready();
  15834. auto req = "POST /test HTTP/1.1\r\n"
  15835. "Host: localhost\r\n"
  15836. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15837. "Content-Length: 146\r\n"
  15838. "\r\n----------\r\n"
  15839. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15840. "\r\n"
  15841. "text1"
  15842. "\r\n----------\r\n"
  15843. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15844. "\r\n"
  15845. "text2"
  15846. "\r\n------------";
  15847. std::string response;
  15848. ASSERT_TRUE(send_request(1, req, &response));
  15849. ASSERT_EQ("200", response.substr(9, 3));
  15850. }
  15851. TEST(MultipartFormDataTest, ContentLength) {
  15852. auto handled = false;
  15853. Server svr;
  15854. svr.Post("/test", [&](const Request &req, Response &) {
  15855. ASSERT_EQ(2u, req.form.fields.size());
  15856. const auto &text1 = req.form.get_field("text1");
  15857. ASSERT_EQ("text1", text1);
  15858. const auto &text2 = req.form.get_field("text2");
  15859. ASSERT_EQ("text2", text2);
  15860. handled = true;
  15861. });
  15862. thread t = thread([&] { svr.listen(HOST, PORT); });
  15863. auto se = detail::scope_exit([&] {
  15864. svr.stop();
  15865. t.join();
  15866. ASSERT_FALSE(svr.is_running());
  15867. ASSERT_TRUE(handled);
  15868. });
  15869. svr.wait_until_ready();
  15870. auto req = "POST /test HTTP/1.1\r\n"
  15871. "Host: localhost\r\n"
  15872. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15873. "Content-Length: 167\r\n"
  15874. "\r\n----------\r\n"
  15875. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15876. "Content-Length: 5\r\n"
  15877. "\r\n"
  15878. "text1"
  15879. "\r\n----------\r\n"
  15880. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15881. "\r\n"
  15882. "text2"
  15883. "\r\n------------\r\n";
  15884. std::string response;
  15885. ASSERT_TRUE(send_request(1, req, &response));
  15886. ASSERT_EQ("200", response.substr(9, 3));
  15887. }
  15888. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15889. auto handled = false;
  15890. Server svr;
  15891. svr.Post("/test", [&](const Request &req, Response &) {
  15892. ASSERT_EQ(2u, req.form.fields.size());
  15893. const auto &text1 = req.form.get_field("text1");
  15894. ASSERT_EQ("text1", text1);
  15895. // TODO: Add header access for text fields if needed
  15896. const auto &text2 = req.form.get_field("text2");
  15897. ASSERT_EQ("text2", text2);
  15898. // TODO: Header access for text fields needs to be implemented
  15899. // auto &headers = it->second.headers;
  15900. // ASSERT_EQ(3U, headers.size());
  15901. // auto custom_header = headers.find("x-whatever");
  15902. // ASSERT_TRUE(custom_header != headers.end());
  15903. // ASSERT_NE("customvalue", custom_header->second);
  15904. // ASSERT_EQ("CustomValue", custom_header->second);
  15905. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15906. handled = true;
  15907. });
  15908. thread t = thread([&] { svr.listen(HOST, PORT); });
  15909. auto se = detail::scope_exit([&] {
  15910. svr.stop();
  15911. t.join();
  15912. ASSERT_FALSE(svr.is_running());
  15913. ASSERT_TRUE(handled);
  15914. });
  15915. svr.wait_until_ready();
  15916. auto req = "POST /test HTTP/1.1\r\n"
  15917. "Host: localhost\r\n"
  15918. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15919. "Content-Length: 232\r\n"
  15920. "\r\n----------\r\n"
  15921. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15922. "Content-Length: 5\r\n"
  15923. "X-Test: 1\r\n"
  15924. "\r\n"
  15925. "text1"
  15926. "\r\n----------\r\n"
  15927. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15928. "Content-Type: text/plain\r\n"
  15929. "X-Whatever: CustomValue\r\n"
  15930. "\r\n"
  15931. "text2"
  15932. "\r\n------------\r\n"
  15933. "That should be disregarded. Not even read";
  15934. std::string response;
  15935. ASSERT_TRUE(send_request(1, req, &response));
  15936. ASSERT_EQ("200", response.substr(9, 3));
  15937. }
  15938. TEST(MultipartFormDataTest, LargeHeader) {
  15939. auto handled = false;
  15940. Server svr;
  15941. svr.Post("/test", [&](const Request &req, Response &) {
  15942. ASSERT_EQ(1u, req.form.fields.size());
  15943. const auto &text = req.form.get_field("name1");
  15944. ASSERT_EQ("text1", text);
  15945. handled = true;
  15946. });
  15947. thread t = thread([&] { svr.listen(HOST, PORT); });
  15948. auto se = detail::scope_exit([&] {
  15949. svr.stop();
  15950. t.join();
  15951. ASSERT_FALSE(svr.is_running());
  15952. ASSERT_TRUE(handled);
  15953. });
  15954. svr.wait_until_ready();
  15955. auto boundary = std::string("cpp-httplib-multipart-data");
  15956. std::string content = "--" + boundary +
  15957. "\r\n"
  15958. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15959. "\r\n"
  15960. "text1\r\n"
  15961. "--" +
  15962. boundary + "--\r\n";
  15963. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15964. "Host: localhost\r\n"
  15965. "Content-Type: multipart/form-data;boundary=" +
  15966. boundary +
  15967. "\r\n"
  15968. "Content-Length: " +
  15969. std::to_string(content.size()) +
  15970. "\r\n"
  15971. "Dummy-Header: ";
  15972. std::string header_suffix = "\r\n"
  15973. "\r\n";
  15974. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15975. size_t header_dummy_size =
  15976. read_buff_size -
  15977. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15978. auto header_dummy = std::string(header_dummy_size, '@');
  15979. auto req = header_prefix + header_dummy + header_suffix + content;
  15980. std::string response;
  15981. ASSERT_TRUE(send_request(1, req, &response));
  15982. ASSERT_EQ("200", response.substr(9, 3));
  15983. }
  15984. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15985. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15986. // (not chunked Transfer-Encoding) after the streaming refactor.
  15987. auto handled = false;
  15988. Server svr;
  15989. svr.Post("/upload", [&](const Request &req, Response &res) {
  15990. auto cl_it = req.headers.find("Content-Length");
  15991. EXPECT_TRUE(cl_it != req.headers.end());
  15992. auto te_it = req.headers.find("Transfer-Encoding");
  15993. EXPECT_TRUE(te_it == req.headers.end());
  15994. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15995. res.set_content("ok", "text/plain");
  15996. handled = true;
  15997. });
  15998. auto port = svr.bind_to_any_port(HOST);
  15999. auto t = thread([&] { svr.listen_after_bind(); });
  16000. auto se = detail::scope_exit([&] {
  16001. svr.stop();
  16002. t.join();
  16003. ASSERT_FALSE(svr.is_running());
  16004. ASSERT_TRUE(handled);
  16005. });
  16006. svr.wait_until_ready();
  16007. UploadFormDataItems items = {
  16008. {"field1", "hello", "", "text/plain"},
  16009. {"file1", "world", "test.txt", "application/octet-stream"},
  16010. };
  16011. Client cli(HOST, port);
  16012. auto res = cli.Post("/upload", {}, items);
  16013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16014. EXPECT_EQ(StatusCode::OK_200, res->status);
  16015. }
  16016. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16017. // Verify that make_multipart_content_provider coalesces many small segments
  16018. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16019. constexpr size_t kItemCount = 1000;
  16020. UploadFormDataItems items;
  16021. items.reserve(kItemCount);
  16022. for (size_t i = 0; i < kItemCount; i++) {
  16023. items.push_back(
  16024. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16025. }
  16026. const std::string boundary = "----test-boundary";
  16027. auto content_length = detail::get_multipart_content_length(items, boundary);
  16028. auto provider = detail::make_multipart_content_provider(items, boundary);
  16029. // Drive the provider the same way write_content_with_progress does
  16030. size_t write_count = 0;
  16031. size_t total_bytes = 0;
  16032. DataSink sink;
  16033. size_t offset = 0;
  16034. sink.write = [&](const char *d, size_t l) -> bool {
  16035. (void)d;
  16036. write_count++;
  16037. total_bytes += l;
  16038. offset += l;
  16039. return true;
  16040. };
  16041. sink.is_writable = []() -> bool { return true; };
  16042. while (offset < content_length) {
  16043. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16044. }
  16045. EXPECT_EQ(content_length, total_bytes);
  16046. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16047. // With buffering into 64KB blocks, write_count should be much smaller.
  16048. auto segment_count = 3 * kItemCount + 1;
  16049. EXPECT_LT(write_count, segment_count / 10);
  16050. }
  16051. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16052. // Integration test: send many UploadFormDataItems and verify the server
  16053. // receives all of them correctly (#2410).
  16054. constexpr size_t kItemCount = 500;
  16055. auto handled = false;
  16056. Server svr;
  16057. svr.Post("/upload", [&](const Request &req, Response &res) {
  16058. EXPECT_EQ(kItemCount, req.form.fields.size());
  16059. for (size_t i = 0; i < kItemCount; i++) {
  16060. auto key = "field" + std::to_string(i);
  16061. auto val = "value" + std::to_string(i);
  16062. auto it = req.form.fields.find(key);
  16063. if (it != req.form.fields.end()) {
  16064. EXPECT_EQ(val, it->second.content);
  16065. } else {
  16066. ADD_FAILURE() << "Missing field: " << key;
  16067. }
  16068. }
  16069. res.set_content("ok", "text/plain");
  16070. handled = true;
  16071. });
  16072. auto port = svr.bind_to_any_port(HOST);
  16073. auto t = thread([&] { svr.listen_after_bind(); });
  16074. auto se = detail::scope_exit([&] {
  16075. svr.stop();
  16076. t.join();
  16077. ASSERT_FALSE(svr.is_running());
  16078. ASSERT_TRUE(handled);
  16079. });
  16080. svr.wait_until_ready();
  16081. UploadFormDataItems items;
  16082. items.reserve(kItemCount);
  16083. for (size_t i = 0; i < kItemCount; i++) {
  16084. items.push_back(
  16085. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16086. }
  16087. Client cli(HOST, port);
  16088. auto res = cli.Post("/upload", items);
  16089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16090. EXPECT_EQ(StatusCode::OK_200, res->status);
  16091. }
  16092. TEST(MultipartFormDataTest, MakeFileProvider) {
  16093. // Verify make_file_provider sends a file's contents correctly.
  16094. const std::string file_content(4096, 'Z');
  16095. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16096. {
  16097. std::ofstream ofs(tmp_path, std::ios::binary);
  16098. ofs.write(file_content.data(),
  16099. static_cast<std::streamsize>(file_content.size()));
  16100. }
  16101. auto handled = false;
  16102. Server svr;
  16103. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16104. const ContentReader &content_reader) {
  16105. ASSERT_TRUE(req.is_multipart_form_data());
  16106. std::vector<FormData> items;
  16107. content_reader(
  16108. [&](const FormData &file) {
  16109. items.push_back(file);
  16110. return true;
  16111. },
  16112. [&](const char *data, size_t data_length) {
  16113. items.back().content.append(data, data_length);
  16114. return true;
  16115. });
  16116. ASSERT_EQ(1u, items.size());
  16117. EXPECT_EQ("myfile", items[0].name);
  16118. EXPECT_EQ("data.bin", items[0].filename);
  16119. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16120. EXPECT_EQ(file_content, items[0].content);
  16121. handled = true;
  16122. });
  16123. auto port = svr.bind_to_any_port(HOST);
  16124. auto t = thread([&] { svr.listen_after_bind(); });
  16125. auto se = detail::scope_exit([&] {
  16126. svr.stop();
  16127. t.join();
  16128. ASSERT_FALSE(svr.is_running());
  16129. ASSERT_TRUE(handled);
  16130. std::remove(tmp_path.c_str());
  16131. });
  16132. svr.wait_until_ready();
  16133. FormDataProviderItems providers;
  16134. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16135. "application/octet-stream"));
  16136. Client cli(HOST, port);
  16137. auto res = cli.Post("/upload", {}, {}, providers);
  16138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16139. EXPECT_EQ(StatusCode::OK_200, res->status);
  16140. }
  16141. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16142. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16143. // (100) headers is rejected with a 400 Bad Request response.
  16144. Server svr;
  16145. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16146. res.set_content("ok", "text/plain");
  16147. });
  16148. thread t = thread([&] { svr.listen(HOST, PORT); });
  16149. auto se = detail::scope_exit([&] {
  16150. svr.stop();
  16151. t.join();
  16152. ASSERT_FALSE(svr.is_running());
  16153. });
  16154. svr.wait_until_ready();
  16155. // Build a multipart part with 101 custom headers (exceeding
  16156. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16157. std::stringstream body;
  16158. body << "--simpleboundary\r\n"
  16159. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16160. for (int i = 0; i < 101; i++) {
  16161. body << "X-Custom-Header-" << i << ": value\r\n";
  16162. }
  16163. body << "\r\n"
  16164. << "value1\r\n"
  16165. << "--simpleboundary--\r\n";
  16166. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16167. Client cli(HOST, PORT);
  16168. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16170. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16171. }
  16172. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16173. // A body that never contains the declared boundary must not be accumulated
  16174. // while the parser waits for it. Buffering it would also make every read
  16175. // rescan everything seen so far, which is quadratic in the body size.
  16176. Server svr;
  16177. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16178. res.set_content("ok", "text/plain");
  16179. });
  16180. auto port = svr.bind_to_any_port(HOST);
  16181. thread t = thread([&] { svr.listen_after_bind(); });
  16182. auto se = detail::scope_exit([&] {
  16183. svr.stop();
  16184. t.join();
  16185. ASSERT_FALSE(svr.is_running());
  16186. });
  16187. svr.wait_until_ready();
  16188. Client cli(HOST, port);
  16189. cli.set_read_timeout(60, 0);
  16190. cli.set_write_timeout(60, 0);
  16191. // '-' is the worst case: it matches the first character of the boundary, so
  16192. // every position has to be checked against it.
  16193. auto post_dashes = [&](size_t size) {
  16194. const std::string body(size, '-');
  16195. auto start = std::chrono::steady_clock::now();
  16196. auto res =
  16197. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16198. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16199. std::chrono::steady_clock::now() - start)
  16200. .count();
  16201. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16202. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16203. return ms;
  16204. };
  16205. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16206. // Windows.
  16207. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16208. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16209. // Comparing the two sizes rather than checking an absolute duration keeps
  16210. // this meaningful across build types and CI load, both of which move the
  16211. // absolute numbers by more than an order of magnitude. Four times the bytes
  16212. // costs about four times the time when parsing is linear, and about sixteen
  16213. // times when the body is buffered and rescanned.
  16214. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16215. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16216. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16217. << "ms, which suggests the body is being buffered and rescanned";
  16218. }
  16219. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16220. // A boundary can only be followed by CRLF or by "--", so anything else is
  16221. // malformed no matter what comes next. The parser must say so right away
  16222. // instead of buffering the rest of the declared body.
  16223. Server svr;
  16224. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16225. res.set_content("ok", "text/plain");
  16226. });
  16227. auto port = svr.bind_to_any_port(HOST);
  16228. thread t = thread([&] { svr.listen_after_bind(); });
  16229. auto se = detail::scope_exit([&] {
  16230. svr.stop();
  16231. t.join();
  16232. ASSERT_FALSE(svr.is_running());
  16233. });
  16234. svr.wait_until_ready();
  16235. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16236. // buffers instead of failing would still be waiting for the remaining bytes.
  16237. const std::string body = "--zzzz\r\n"
  16238. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16239. "\r\n"
  16240. "text1"
  16241. "\r\n--zzzzXX";
  16242. const std::string req = "POST /post HTTP/1.1\r\n"
  16243. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16244. "Content-Length: 1048576\r\n"
  16245. "\r\n" +
  16246. body;
  16247. std::string response;
  16248. ASSERT_TRUE(send_request(3, req, &response, port));
  16249. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16250. EXPECT_EQ("400", response.substr(9, 3));
  16251. }
  16252. // Posts a multipart body split into two writes, so that the server sees the
  16253. // split at whatever offset the caller chose, and expects the single "text1"
  16254. // field to come through.
  16255. static void expect_split_multipart_ok(const std::string &body1,
  16256. const std::string &body2) {
  16257. auto handled = false;
  16258. Server svr;
  16259. svr.Post("/post", [&](const Request &req, Response &) {
  16260. EXPECT_EQ(1u, req.form.fields.size());
  16261. EXPECT_EQ("text1", req.form.get_field("text1"));
  16262. handled = true;
  16263. });
  16264. auto port = svr.bind_to_any_port(HOST);
  16265. thread t = thread([&] { svr.listen_after_bind(); });
  16266. auto se = detail::scope_exit([&] {
  16267. svr.stop();
  16268. t.join();
  16269. ASSERT_FALSE(svr.is_running());
  16270. ASSERT_TRUE(handled);
  16271. });
  16272. svr.wait_until_ready();
  16273. // "Connection: close" makes the server close once it has answered, so the
  16274. // response drain ends immediately instead of idling until the read timeout.
  16275. const std::string head =
  16276. "POST /post HTTP/1.1\r\n"
  16277. "Host: localhost\r\n"
  16278. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16279. "Connection: close\r\n"
  16280. "Content-Length: " +
  16281. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16282. std::string response;
  16283. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16284. ASSERT_GE(response.size(), 12u) << "no response";
  16285. EXPECT_EQ("200", response.substr(9, 3));
  16286. }
  16287. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16288. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16289. // ignored, including when it does not arrive in the same read as the
  16290. // close-delimiter itself.
  16291. expect_split_multipart_ok("--zzzz\r\n"
  16292. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16293. "\r\n"
  16294. "text1"
  16295. "\r\n--zzzz--",
  16296. "\r\nthis epilogue must be ignored\r\n");
  16297. }
  16298. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16299. // The initial boundary may be preceded by a preamble of any length and may
  16300. // straddle a read boundary. Discarding data while waiting for it must not
  16301. // throw away a partial boundary sitting at the end of the buffer.
  16302. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16303. "zz\r\n"
  16304. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16305. "\r\n"
  16306. "text1"
  16307. "\r\n--zzzz--\r\n");
  16308. }
  16309. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16310. // The received boundary was only checked for being non-empty, so it could be
  16311. // as long as a header is allowed to be. The parser scans the body for
  16312. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16313. // costs a nearly full comparison at nearly every position, making the
  16314. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16315. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16316. Server svr;
  16317. svr.Post("/post", [](const Request &req, Response &res) {
  16318. EXPECT_EQ(1u, req.form.fields.size());
  16319. EXPECT_EQ("text1", req.form.get_field("text1"));
  16320. res.set_content("ok", "text/plain");
  16321. });
  16322. auto port = svr.bind_to_any_port(HOST);
  16323. thread t = thread([&] { svr.listen_after_bind(); });
  16324. auto se = detail::scope_exit([&] {
  16325. svr.stop();
  16326. t.join();
  16327. ASSERT_FALSE(svr.is_running());
  16328. });
  16329. svr.wait_until_ready();
  16330. Client cli(HOST, port);
  16331. auto post_with_boundary_of_length = [&](size_t len) {
  16332. const std::string boundary(len, 'a');
  16333. const std::string body =
  16334. "--" + boundary +
  16335. "\r\n"
  16336. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16337. "\r\n"
  16338. "text1"
  16339. "\r\n--" +
  16340. boundary + "--\r\n";
  16341. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16342. };
  16343. auto res = post_with_boundary_of_length(70);
  16344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16345. EXPECT_EQ(StatusCode::OK_200, res->status);
  16346. res = post_with_boundary_of_length(71);
  16347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16348. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16349. }
  16350. TEST(MakeFileBodyTest, Basic) {
  16351. const std::string file_content(4096, 'Z');
  16352. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16353. {
  16354. std::ofstream ofs(tmp_path, std::ios::binary);
  16355. ofs.write(file_content.data(),
  16356. static_cast<std::streamsize>(file_content.size()));
  16357. }
  16358. auto handled = false;
  16359. Server svr;
  16360. svr.Post("/upload", [&](const Request &req, Response &res) {
  16361. EXPECT_EQ(file_content, req.body);
  16362. handled = true;
  16363. res.status = StatusCode::OK_200;
  16364. });
  16365. auto port = svr.bind_to_any_port(HOST);
  16366. auto t = thread([&] { svr.listen_after_bind(); });
  16367. auto se = detail::scope_exit([&] {
  16368. svr.stop();
  16369. t.join();
  16370. ASSERT_FALSE(svr.is_running());
  16371. ASSERT_TRUE(handled);
  16372. std::remove(tmp_path.c_str());
  16373. });
  16374. svr.wait_until_ready();
  16375. auto fb = make_file_body(tmp_path);
  16376. ASSERT_GT(fb.first, 0u);
  16377. Client cli(HOST, port);
  16378. auto res =
  16379. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16381. EXPECT_EQ(StatusCode::OK_200, res->status);
  16382. }
  16383. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16384. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16385. {
  16386. std::ofstream ofs(path, std::ios::binary);
  16387. const std::string content(100, 'A');
  16388. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16389. }
  16390. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16391. auto body = make_file_body(path);
  16392. ASSERT_EQ(100u, body.first);
  16393. ASSERT_TRUE(static_cast<bool>(body.second));
  16394. // Rewritten shorter after its length was measured - and, on a server, after
  16395. // that length has already gone out as Content-Length.
  16396. {
  16397. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16398. const std::string content(10, 'A');
  16399. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16400. }
  16401. std::string written;
  16402. DataSink sink;
  16403. sink.write = [&](const char *d, size_t l) {
  16404. written.append(d, l);
  16405. return true;
  16406. };
  16407. // The provider has to report failure. write_content_with_progress() advances
  16408. // its offset only by what was written, so a provider that returns true
  16409. // without completing the length it promised is called again straight away,
  16410. // and again.
  16411. EXPECT_FALSE(body.second(0, body.first, sink));
  16412. EXPECT_EQ(std::string(10, 'A'), written);
  16413. }
  16414. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16415. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16416. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16417. {
  16418. std::ofstream ofs(path, std::ios::binary);
  16419. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16420. }
  16421. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16422. auto body = make_file_body(path);
  16423. ASSERT_EQ(content.size(), body.first);
  16424. ASSERT_TRUE(static_cast<bool>(body.second));
  16425. std::string written;
  16426. DataSink sink;
  16427. sink.write = [&](const char *d, size_t l) {
  16428. written.append(d, l);
  16429. return true;
  16430. };
  16431. EXPECT_TRUE(body.second(0, body.first, sink));
  16432. EXPECT_EQ(content, written);
  16433. }
  16434. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16435. static constexpr unsigned int number_of_tasks{1000000};
  16436. std::atomic_uint count{0};
  16437. std::unique_ptr<TaskQueue> task_queue{
  16438. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16439. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16440. auto queued = task_queue->enqueue(
  16441. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16442. EXPECT_TRUE(queued);
  16443. }
  16444. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16445. task_queue->shutdown();
  16446. #else
  16447. EXPECT_NO_THROW(task_queue->shutdown());
  16448. #endif
  16449. EXPECT_EQ(number_of_tasks, count.load());
  16450. }
  16451. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16452. static constexpr unsigned int number_of_tasks{1000000};
  16453. static constexpr unsigned int qlimit{2};
  16454. unsigned int queued_count{0};
  16455. std::atomic_uint count{0};
  16456. std::unique_ptr<TaskQueue> task_queue{
  16457. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16458. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16459. if (task_queue->enqueue(
  16460. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16461. queued_count++;
  16462. }
  16463. }
  16464. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16465. task_queue->shutdown();
  16466. #else
  16467. EXPECT_NO_THROW(task_queue->shutdown());
  16468. #endif
  16469. EXPECT_EQ(queued_count, count.load());
  16470. EXPECT_TRUE(queued_count <= number_of_tasks);
  16471. EXPECT_TRUE(queued_count >= qlimit);
  16472. }
  16473. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16474. // Use a short idle timeout so a dynamic thread spawns, times out and
  16475. // exits during the test, and the pool keeps working afterwards.
  16476. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16477. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16478. /*idle_timeout_sec=*/1}};
  16479. std::atomic_uint count{0};
  16480. std::condition_variable cv;
  16481. std::mutex mtx;
  16482. bool release = false;
  16483. // Block the base thread so the second task spawns a dynamic thread.
  16484. EXPECT_TRUE(task_queue->enqueue([&] {
  16485. std::unique_lock<std::mutex> lock(mtx);
  16486. while (!release) {
  16487. cv.wait(lock);
  16488. }
  16489. count++;
  16490. }));
  16491. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16492. // Let the dynamic thread finish its task and exceed the idle timeout.
  16493. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16494. {
  16495. std::unique_lock<std::mutex> lock(mtx);
  16496. release = true;
  16497. }
  16498. cv.notify_all();
  16499. // The pool must still accept and run tasks after the dynamic thread exited.
  16500. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16501. task_queue->shutdown();
  16502. EXPECT_EQ(3u, count.load());
  16503. }
  16504. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16505. static constexpr size_t number_of_tasks{32};
  16506. std::unique_ptr<TaskQueue> task_queue{
  16507. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16508. // Let the base threads go idle so the burst below finds them waiting.
  16509. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16510. std::mutex mtx;
  16511. std::condition_variable cv;
  16512. size_t running = 0;
  16513. bool release = false;
  16514. for (size_t i = 0; i < number_of_tasks; i++) {
  16515. EXPECT_TRUE(task_queue->enqueue([&] {
  16516. std::unique_lock<std::mutex> lock(mtx);
  16517. running++;
  16518. cv.notify_all();
  16519. cv.wait(lock, [&] { return release; });
  16520. }));
  16521. }
  16522. {
  16523. std::unique_lock<std::mutex> lock(mtx);
  16524. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16525. [&] { return running == number_of_tasks; }));
  16526. release = true;
  16527. }
  16528. cv.notify_all();
  16529. task_queue->shutdown();
  16530. }
  16531. TEST(TaskQueueTest, MaxQueuedRequests) {
  16532. static constexpr unsigned int qlimit{3};
  16533. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16534. std::condition_variable sem_cv;
  16535. std::mutex sem_mtx;
  16536. int credits = 0;
  16537. bool queued;
  16538. /* Fill up the queue with tasks that will block until we give them credits to
  16539. * complete. */
  16540. for (unsigned int n = 0; n <= qlimit;) {
  16541. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16542. std::unique_lock<std::mutex> lock(sem_mtx);
  16543. while (credits <= 0) {
  16544. sem_cv.wait(lock);
  16545. }
  16546. /* Consume the credit and signal the test code if they are all gone. */
  16547. if (--credits == 0) { sem_cv.notify_one(); }
  16548. });
  16549. if (n < qlimit) {
  16550. /* The first qlimit enqueues must succeed. */
  16551. EXPECT_TRUE(queued);
  16552. } else {
  16553. /* The last one will succeed only when the worker thread
  16554. * starts and dequeues the first blocking task. Although
  16555. * not necessary for the correctness of this test, we sleep for
  16556. * a short while to avoid busy waiting. */
  16557. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16558. }
  16559. if (queued) { n++; }
  16560. }
  16561. /* Further enqueues must fail since the queue is full. */
  16562. for (auto i = 0; i < 4; i++) {
  16563. queued = task_queue->enqueue([] {});
  16564. EXPECT_FALSE(queued);
  16565. }
  16566. /* Give the credits to allow the previous tasks to complete. */
  16567. {
  16568. std::unique_lock<std::mutex> lock(sem_mtx);
  16569. credits += qlimit + 1;
  16570. }
  16571. sem_cv.notify_all();
  16572. /* Wait for all the credits to be consumed. */
  16573. {
  16574. std::unique_lock<std::mutex> lock(sem_mtx);
  16575. while (credits > 0) {
  16576. sem_cv.wait(lock);
  16577. }
  16578. }
  16579. /* Check that we are able again to enqueue at least qlimit tasks. */
  16580. for (unsigned int i = 0; i < qlimit; i++) {
  16581. queued = task_queue->enqueue([] {});
  16582. EXPECT_TRUE(queued);
  16583. }
  16584. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16585. task_queue->shutdown();
  16586. #else
  16587. EXPECT_NO_THROW(task_queue->shutdown());
  16588. #endif
  16589. }
  16590. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16591. Server svr;
  16592. std::string method;
  16593. std::string body;
  16594. auto has_content_length = false;
  16595. auto has_transfer_encoding = false;
  16596. std::atomic<int> bad_requests{0};
  16597. // Leftover body bytes get parsed as a malformed request and answered with
  16598. // 400
  16599. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16600. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16601. });
  16602. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16603. res.set_redirect("/down", StatusCode::SeeOther_303);
  16604. });
  16605. svr.Get("/down", [&](const Request &req, Response &res) {
  16606. method = req.method;
  16607. body = req.body;
  16608. has_content_length = req.has_header("Content-Length");
  16609. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16610. res.set_content("ok", "text/plain");
  16611. });
  16612. auto port = svr.bind_to_any_port(HOST);
  16613. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16614. auto se = detail::scope_exit([&] {
  16615. svr.stop();
  16616. thread.join();
  16617. ASSERT_FALSE(svr.is_running());
  16618. });
  16619. svr.wait_until_ready();
  16620. const std::string payload = "SECRET-BODY";
  16621. auto check = [&](Client &cli, const Result &res) {
  16622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16623. EXPECT_EQ(StatusCode::OK_200, res->status);
  16624. EXPECT_EQ("ok", res->body);
  16625. EXPECT_EQ("GET", method);
  16626. EXPECT_TRUE(body.empty());
  16627. EXPECT_FALSE(has_content_length);
  16628. EXPECT_FALSE(has_transfer_encoding);
  16629. // Nothing of the original body may be left on the connection
  16630. auto res2 = cli.Get("/down");
  16631. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16632. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16633. EXPECT_EQ("ok", res2->body);
  16634. EXPECT_EQ(0, bad_requests);
  16635. };
  16636. // With content length
  16637. {
  16638. Client cli(HOST, port);
  16639. cli.set_keep_alive(true);
  16640. cli.set_follow_location(true);
  16641. auto res = cli.Post(
  16642. "/up", payload.size(),
  16643. [&](size_t offset, size_t length, DataSink &sink) {
  16644. return sink.write(payload.data() + offset, length);
  16645. },
  16646. "text/plain");
  16647. check(cli, res);
  16648. }
  16649. // Without content length (chunked)
  16650. {
  16651. Client cli(HOST, port);
  16652. cli.set_keep_alive(true);
  16653. cli.set_follow_location(true);
  16654. auto res = cli.Post(
  16655. "/up",
  16656. [&](size_t /*offset*/, DataSink &sink) {
  16657. sink.write(payload.data(), payload.size());
  16658. sink.done();
  16659. return true;
  16660. },
  16661. "text/plain");
  16662. check(cli, res);
  16663. }
  16664. }
  16665. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16666. Server svr;
  16667. std::string target;
  16668. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16669. // Echo the still-encoded name back in the Location
  16670. const std::string prefix = "/start/";
  16671. res.status = StatusCode::Found_302;
  16672. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16673. });
  16674. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16675. target = req.target;
  16676. res.set_content("ok", "text/plain");
  16677. });
  16678. auto port = svr.bind_to_any_port(HOST);
  16679. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16680. auto se = detail::scope_exit([&] {
  16681. svr.stop();
  16682. thread.join();
  16683. ASSERT_FALSE(svr.is_running());
  16684. });
  16685. svr.wait_until_ready();
  16686. // Decoding the Location path would turn the first four into a path
  16687. // separator, a query delimiter, a fragment delimiter and a different
  16688. // percent-encoded octet. The rest must keep reaching the server as they are.
  16689. const std::vector<std::string> names = {
  16690. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16691. };
  16692. for (auto path_encode : {true, false}) {
  16693. Client cli(HOST, port);
  16694. cli.set_follow_location(true);
  16695. cli.set_path_encode(path_encode);
  16696. for (const auto &name : names) {
  16697. target.clear();
  16698. auto res = cli.Get("/start/" + name);
  16699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16700. EXPECT_EQ(StatusCode::OK_200, res->status);
  16701. EXPECT_EQ("/dest/" + name, target);
  16702. }
  16703. }
  16704. }
  16705. TEST(RedirectTest, NotModifiedIsReturned) {
  16706. Server svr;
  16707. svr.Get("/cached", [](const Request &, Response &res) {
  16708. res.status = StatusCode::NotModified_304;
  16709. });
  16710. auto port = svr.bind_to_any_port(HOST);
  16711. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16712. auto se = detail::scope_exit([&] {
  16713. svr.stop();
  16714. thread.join();
  16715. ASSERT_FALSE(svr.is_running());
  16716. });
  16717. svr.wait_until_ready();
  16718. Client cli(HOST, port);
  16719. cli.set_follow_location(true);
  16720. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16723. }
  16724. TEST(RedirectTest, NoLocationIsReturned) {
  16725. Server svr;
  16726. svr.Get("/no-location", [](const Request &, Response &res) {
  16727. res.status = StatusCode::Found_302;
  16728. res.set_content("no location", "text/plain");
  16729. });
  16730. auto port = svr.bind_to_any_port(HOST);
  16731. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16732. auto se = detail::scope_exit([&] {
  16733. svr.stop();
  16734. thread.join();
  16735. ASSERT_FALSE(svr.is_running());
  16736. });
  16737. svr.wait_until_ready();
  16738. Client cli(HOST, port);
  16739. cli.set_follow_location(true);
  16740. auto res = cli.Get("/no-location");
  16741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16742. EXPECT_EQ(StatusCode::Found_302, res->status);
  16743. EXPECT_EQ("no location", res->body);
  16744. // The callbacks see the body of the response that is returned
  16745. auto handler_called = false;
  16746. auto progress_called = false;
  16747. std::string body;
  16748. auto res2 = cli.Get(
  16749. "/no-location",
  16750. [&](const Response &) {
  16751. handler_called = true;
  16752. return true;
  16753. },
  16754. [&](const char *data, size_t data_length) {
  16755. body.append(data, data_length);
  16756. return true;
  16757. },
  16758. [&](size_t, size_t) {
  16759. progress_called = true;
  16760. return true;
  16761. });
  16762. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16763. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16764. EXPECT_TRUE(handler_called);
  16765. EXPECT_TRUE(progress_called);
  16766. EXPECT_EQ("no location", body);
  16767. }
  16768. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16769. Server svr;
  16770. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16771. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16772. });
  16773. svr.Get("/hello", [](const Request &req, Response &res) {
  16774. res.set_content(req.get_param_value("key"), "text/plain");
  16775. });
  16776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16777. auto se = detail::scope_exit([&] {
  16778. svr.stop();
  16779. thread.join();
  16780. ASSERT_FALSE(svr.is_running());
  16781. });
  16782. svr.wait_until_ready();
  16783. {
  16784. Client cli(HOST, PORT);
  16785. cli.set_follow_location(true);
  16786. auto res = cli.Get("/");
  16787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16788. EXPECT_EQ(StatusCode::OK_200, res->status);
  16789. EXPECT_EQ("val&key2=val2", res->body);
  16790. }
  16791. }
  16792. #endif
  16793. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16794. Server svr;
  16795. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16796. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16797. });
  16798. svr.Get("/hello", [](const Request &req, Response &res) {
  16799. res.set_content(req.get_param_value("key"), "text/plain");
  16800. });
  16801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16802. auto se = detail::scope_exit([&] {
  16803. svr.stop();
  16804. thread.join();
  16805. ASSERT_FALSE(svr.is_running());
  16806. });
  16807. svr.wait_until_ready();
  16808. {
  16809. Client cli(HOST, PORT);
  16810. cli.set_follow_location(true);
  16811. auto res = cli.Get("/");
  16812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16813. EXPECT_EQ(StatusCode::OK_200, res->status);
  16814. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16815. }
  16816. }
  16817. TEST(RedirectTest, RedirectWithPlusInPath) {
  16818. Server svr;
  16819. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16820. res.set_redirect("/a+b");
  16821. });
  16822. // Route pattern uses regex; escape + as \\+
  16823. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16824. res.set_content(req.path, "text/plain");
  16825. });
  16826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16827. auto se = detail::scope_exit([&] {
  16828. svr.stop();
  16829. thread.join();
  16830. ASSERT_FALSE(svr.is_running());
  16831. });
  16832. svr.wait_until_ready();
  16833. {
  16834. Client cli(HOST, PORT);
  16835. cli.set_follow_location(true);
  16836. auto res = cli.Get("/");
  16837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16838. EXPECT_EQ(StatusCode::OK_200, res->status);
  16839. EXPECT_EQ("/a+b", res->body);
  16840. }
  16841. }
  16842. TEST(RedirectTest, ResolveRelativeLocation) {
  16843. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16844. const std::vector<std::pair<std::string, std::string>> cases = {
  16845. {"g", "/b/c/g"},
  16846. {"./g", "/b/c/g"},
  16847. {"g/", "/b/c/g/"},
  16848. {"?y", "/b/c/d;p?y"},
  16849. {"g?y", "/b/c/g?y"},
  16850. {"#s", "/b/c/d;p?q#s"},
  16851. {"g#s", "/b/c/g#s"},
  16852. {"g?y#s", "/b/c/g?y#s"},
  16853. {";x", "/b/c/;x"},
  16854. {"g;x", "/b/c/g;x"},
  16855. {".", "/b/c/"},
  16856. {"./", "/b/c/"},
  16857. {"..", "/b/"},
  16858. {"../", "/b/"},
  16859. {"../g", "/b/g"},
  16860. {"../..", "/"},
  16861. {"../../", "/"},
  16862. {"../../g", "/g"},
  16863. {"../../../g", "/g"},
  16864. {"g.", "/b/c/g."},
  16865. {".g", "/b/c/.g"},
  16866. {"g..", "/b/c/g.."},
  16867. {"..g", "/b/c/..g"},
  16868. {"./../g", "/b/g"},
  16869. {"./g/.", "/b/c/g/"},
  16870. {"g/./h", "/b/c/g/h"},
  16871. {"g/../h", "/b/c/h"},
  16872. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16873. {"g;x=1/../y", "/b/c/y"},
  16874. {"g?y/./x", "/b/c/g?y/./x"},
  16875. {"g#s/../x", "/b/c/g#s/../x"},
  16876. // Not relative-path references, so left for parse_url.
  16877. {"/g", "/g"},
  16878. {"//g", "//g"},
  16879. {"http://g/x", "http://g/x"},
  16880. {"g:h", "g:h"},
  16881. };
  16882. for (const auto &c : cases) {
  16883. EXPECT_EQ(c.second,
  16884. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16885. << c.first;
  16886. }
  16887. }
  16888. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16889. Server svr;
  16890. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16891. res.set_redirect(req.get_param_value("to"));
  16892. });
  16893. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16894. res.set_content(req.target, "text/plain");
  16895. });
  16896. svr.Get("/other", [](const Request &req, Response &res) {
  16897. res.set_content(req.target, "text/plain");
  16898. });
  16899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16900. auto se = detail::scope_exit([&] {
  16901. svr.stop();
  16902. thread.join();
  16903. ASSERT_FALSE(svr.is_running());
  16904. });
  16905. svr.wait_until_ready();
  16906. const std::vector<std::pair<std::string, std::string>> cases = {
  16907. {"next", "/dir/next"},
  16908. {"./next?x=1", "/dir/next?x=1"},
  16909. {"../other", "/other"},
  16910. };
  16911. for (const auto &c : cases) {
  16912. Client cli(HOST, PORT);
  16913. cli.set_follow_location(true);
  16914. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16915. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16916. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16917. EXPECT_EQ(c.second, res->body) << c.first;
  16918. }
  16919. }
  16920. #ifdef CPPHTTPLIB_SSL_ENABLED
  16921. TEST(RedirectTest, Issue2185_Online) {
  16922. SSLClient client("github.com");
  16923. client.set_follow_location(true);
  16924. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16925. "Coollab-Windows.zip");
  16926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16927. EXPECT_EQ(StatusCode::OK_200, res->status);
  16928. EXPECT_EQ(9920427U, res->body.size());
  16929. }
  16930. #endif
  16931. TEST(VulnerabilityTest, CRLFInjection) {
  16932. Server svr;
  16933. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16934. res.set_content("Hello 1", "text/plain");
  16935. });
  16936. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16937. res.set_content("Hello 2", "text/plain");
  16938. });
  16939. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16940. res.set_content("Hello 3", "text/plain");
  16941. });
  16942. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16943. res.set_content("Hello 4", "text/plain");
  16944. });
  16945. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16946. for (const auto &x : req.headers) {
  16947. auto key = x.first;
  16948. EXPECT_STRNE("evil", key.c_str());
  16949. }
  16950. });
  16951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16952. auto se = detail::scope_exit([&] {
  16953. svr.stop();
  16954. thread.join();
  16955. ASSERT_FALSE(svr.is_running());
  16956. });
  16957. svr.wait_until_ready();
  16958. {
  16959. Client cli(HOST, PORT);
  16960. cli.Post("/test1", "A=B",
  16961. "application/x-www-form-urlencoded\r\nevil: hello1");
  16962. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16963. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16964. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16965. }
  16966. }
  16967. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16968. auto server_thread = std::thread([] {
  16969. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16970. default_socket_options(srv);
  16971. sockaddr_in addr{};
  16972. addr.sin_family = AF_INET;
  16973. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16975. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16976. ::listen(srv, 1);
  16977. sockaddr_in cli_addr{};
  16978. socklen_t cli_len = sizeof(cli_addr);
  16979. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16980. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16981. std::string buf_all;
  16982. char buf[2048];
  16983. ssize_t n;
  16984. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16985. buf_all.append(buf, static_cast<size_t>(n));
  16986. size_t pos;
  16987. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16988. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16989. auto e = request_block.find("\r\n");
  16990. if (e != std::string::npos) {
  16991. auto request_line = request_block.substr(0, e);
  16992. std::string msg =
  16993. "CRLF injection detected in request line: '" + request_line + "'";
  16994. EXPECT_FALSE(true) << msg;
  16995. }
  16996. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16997. ::send(cli,
  16998. #ifdef _WIN32
  16999. static_cast<const char *>(resp.c_str()),
  17000. static_cast<int>(resp.size()),
  17001. #else
  17002. resp.c_str(), resp.size(),
  17003. #endif
  17004. 0);
  17005. buf_all.erase(0, pos + 4);
  17006. }
  17007. }
  17008. detail::close_socket(cli);
  17009. detail::close_socket(srv);
  17010. });
  17011. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17012. auto cli = Client("127.0.0.1", PORT + 1);
  17013. auto headers = Headers{
  17014. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17015. {"Connection", "keep-alive"}};
  17016. auto res = cli.Get("/hi", headers);
  17017. EXPECT_FALSE(res);
  17018. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17019. server_thread.join();
  17020. }
  17021. // A request rejected before any byte reaches the socket must fail right away
  17022. // instead of waiting for a response the server will never send.
  17023. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17024. // The kernel completes the TCP handshake from the listen backlog, so the
  17025. // client connects, but nothing ever reads, responds or closes.
  17026. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17027. default_socket_options(srv);
  17028. sockaddr_in addr{};
  17029. addr.sin_family = AF_INET;
  17030. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17031. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17032. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17033. ASSERT_EQ(0, ::listen(srv, 8));
  17034. auto cli = Client("127.0.0.1", PORT + 1);
  17035. cli.set_read_timeout(10, 0);
  17036. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17037. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17038. std::chrono::steady_clock::now() - start)
  17039. .count();
  17040. };
  17041. {
  17042. Request req;
  17043. req.method = "GE T";
  17044. req.path = "/";
  17045. auto start = std::chrono::steady_clock::now();
  17046. auto res = cli.send(req);
  17047. EXPECT_FALSE(res);
  17048. EXPECT_EQ(Error::Write, res.error());
  17049. EXPECT_LT(elapsed_ms(start), 1000);
  17050. }
  17051. {
  17052. auto start = std::chrono::steady_clock::now();
  17053. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17054. EXPECT_FALSE(res);
  17055. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17056. EXPECT_LT(elapsed_ms(start), 1000);
  17057. }
  17058. EXPECT_FALSE(cli.is_socket_open());
  17059. detail::close_socket(srv);
  17060. }
  17061. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17062. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17063. default_socket_options(srv);
  17064. sockaddr_in addr{};
  17065. addr.sin_family = AF_INET;
  17066. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17067. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17068. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17069. ASSERT_EQ(0, ::listen(srv, 1));
  17070. std::string received;
  17071. auto server_thread = std::thread([&] {
  17072. auto sock = ::accept(srv, nullptr, nullptr);
  17073. if (sock == INVALID_SOCKET) { return; }
  17074. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17075. char buf[2048];
  17076. ssize_t n;
  17077. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17078. received.append(buf, static_cast<size_t>(n));
  17079. }
  17080. detail::close_socket(sock);
  17081. });
  17082. {
  17083. auto cli = Client("127.0.0.1", PORT + 1);
  17084. // "Z" sorts after the default headers, so writing straight to the socket
  17085. // would have sent the request line and those headers before the rejection.
  17086. auto handle =
  17087. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17088. EXPECT_FALSE(handle.is_valid());
  17089. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17090. }
  17091. server_thread.join();
  17092. detail::close_socket(srv);
  17093. EXPECT_TRUE(received.empty()) << received;
  17094. }
  17095. TEST(PathParamsTest, StaticMatch) {
  17096. const auto pattern = "/users/all";
  17097. detail::PathParamsMatcher matcher(pattern);
  17098. Request request;
  17099. request.path = "/users/all";
  17100. ASSERT_TRUE(matcher.match(request));
  17101. std::unordered_map<std::string, std::string> expected_params = {};
  17102. EXPECT_EQ(request.path_params, expected_params);
  17103. }
  17104. TEST(PathParamsTest, StaticMismatch) {
  17105. const auto pattern = "/users/all";
  17106. detail::PathParamsMatcher matcher(pattern);
  17107. Request request;
  17108. request.path = "/users/1";
  17109. ASSERT_FALSE(matcher.match(request));
  17110. }
  17111. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17112. const auto pattern = "/users/:id/subscriptions";
  17113. detail::PathParamsMatcher matcher(pattern);
  17114. Request request;
  17115. request.path = "/users/42/subscriptions";
  17116. ASSERT_TRUE(matcher.match(request));
  17117. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17118. EXPECT_EQ(request.path_params, expected_params);
  17119. }
  17120. TEST(PathParamsTest, SingleParamInTheEnd) {
  17121. const auto pattern = "/users/:id";
  17122. detail::PathParamsMatcher matcher(pattern);
  17123. Request request;
  17124. request.path = "/users/24";
  17125. ASSERT_TRUE(matcher.match(request));
  17126. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17127. EXPECT_EQ(request.path_params, expected_params);
  17128. }
  17129. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17130. const auto pattern = "/users/:id/";
  17131. detail::PathParamsMatcher matcher(pattern);
  17132. Request request;
  17133. request.path = "/users/42/";
  17134. ASSERT_TRUE(matcher.match(request));
  17135. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17136. EXPECT_EQ(request.path_params, expected_params);
  17137. }
  17138. TEST(PathParamsTest, EmptyParam) {
  17139. const auto pattern = "/users/:id/";
  17140. detail::PathParamsMatcher matcher(pattern);
  17141. Request request;
  17142. request.path = "/users//";
  17143. ASSERT_TRUE(matcher.match(request));
  17144. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17145. EXPECT_EQ(request.path_params, expected_params);
  17146. }
  17147. TEST(PathParamsTest, FragmentMismatch) {
  17148. const auto pattern = "/users/:id/";
  17149. detail::PathParamsMatcher matcher(pattern);
  17150. Request request;
  17151. request.path = "/admins/24/";
  17152. ASSERT_FALSE(matcher.match(request));
  17153. }
  17154. TEST(PathParamsTest, ExtraFragments) {
  17155. const auto pattern = "/users/:id";
  17156. detail::PathParamsMatcher matcher(pattern);
  17157. Request request;
  17158. request.path = "/users/42/subscriptions";
  17159. ASSERT_FALSE(matcher.match(request));
  17160. }
  17161. TEST(PathParamsTest, MissingTrailingParam) {
  17162. const auto pattern = "/users/:id";
  17163. detail::PathParamsMatcher matcher(pattern);
  17164. Request request;
  17165. request.path = "/users";
  17166. ASSERT_FALSE(matcher.match(request));
  17167. }
  17168. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17169. const auto pattern = "/users/:id/subscriptions";
  17170. detail::PathParamsMatcher matcher(pattern);
  17171. Request request;
  17172. request.path = "/users/subscriptions";
  17173. ASSERT_FALSE(matcher.match(request));
  17174. }
  17175. TEST(PathParamsTest, MultipleParams) {
  17176. const auto pattern = "/users/:userid/subscriptions/:subid";
  17177. detail::PathParamsMatcher matcher(pattern);
  17178. Request request;
  17179. request.path = "/users/42/subscriptions/2";
  17180. ASSERT_TRUE(matcher.match(request));
  17181. std::unordered_map<std::string, std::string> expected_params = {
  17182. {"userid", "42"}, {"subid", "2"}};
  17183. EXPECT_EQ(request.path_params, expected_params);
  17184. }
  17185. TEST(PathParamsTest, SequenceOfParams) {
  17186. const auto pattern = "/values/:x/:y/:z";
  17187. detail::PathParamsMatcher matcher(pattern);
  17188. Request request;
  17189. request.path = "/values/1/2/3";
  17190. ASSERT_TRUE(matcher.match(request));
  17191. std::unordered_map<std::string, std::string> expected_params = {
  17192. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17193. EXPECT_EQ(request.path_params, expected_params);
  17194. }
  17195. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17196. const auto pattern = "/prefix:suffix";
  17197. detail::PathParamsMatcher matcher(pattern);
  17198. Request request;
  17199. request.path = "/prefix:suffix";
  17200. ASSERT_TRUE(matcher.match(request));
  17201. const std::unordered_map<std::string, std::string> expected_params = {};
  17202. EXPECT_EQ(request.path_params, expected_params);
  17203. }
  17204. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17205. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17206. // calling thread's stack on a long enough path for a quantified pattern;
  17207. // RegexMatcher must refuse to run regex matching on paths beyond
  17208. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17209. detail::RegexMatcher matcher("/files/(.*)");
  17210. Request within_limit;
  17211. within_limit.path = "/files/" + std::string(10, 'A');
  17212. EXPECT_TRUE(matcher.match(within_limit));
  17213. Request over_limit;
  17214. over_limit.path =
  17215. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17216. EXPECT_FALSE(matcher.match(over_limit));
  17217. }
  17218. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17219. Server svr;
  17220. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17221. res.set_content("ok", "text/plain");
  17222. });
  17223. auto port = svr.bind_to_any_port(HOST);
  17224. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17225. auto se = detail::scope_exit([&] {
  17226. svr.stop();
  17227. thread.join();
  17228. ASSERT_FALSE(svr.is_running());
  17229. });
  17230. svr.wait_until_ready();
  17231. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17232. // request URI limit; this used to be able to crash the process.
  17233. std::string path =
  17234. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17235. std::string req = "GET " + path +
  17236. " HTTP/1.1\r\n"
  17237. "Host: " +
  17238. std::string(HOST) + ":" + std::to_string(port) +
  17239. "\r\n"
  17240. "Connection: close\r\n"
  17241. "\r\n";
  17242. std::string response;
  17243. ASSERT_TRUE(send_request(5, req, &response, port));
  17244. EXPECT_NE(std::string::npos, response.find("404"));
  17245. }
  17246. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17247. Server svr;
  17248. auto handler = [](const Request & /*req*/, Response &res) {
  17249. res.set_content("hit", "text/plain");
  17250. };
  17251. // No regex metacharacter, so this one is compared literally
  17252. svr.Get("/literal/route", handler);
  17253. // '.' is a regex metacharacter, so this one must keep regex semantics
  17254. svr.Get("/a.c", handler);
  17255. auto port = svr.bind_to_any_port(HOST);
  17256. std::thread t([&]() { svr.listen_after_bind(); });
  17257. auto se = detail::scope_exit([&] {
  17258. svr.stop();
  17259. t.join();
  17260. ASSERT_FALSE(svr.is_running());
  17261. });
  17262. svr.wait_until_ready();
  17263. Client cli(HOST, port);
  17264. struct {
  17265. const char *path;
  17266. int status;
  17267. } cases[] = {
  17268. {"/literal/route", StatusCode::OK_200},
  17269. {"/literal/routes", StatusCode::NotFound_404},
  17270. {"/literal/rout", StatusCode::NotFound_404},
  17271. {"/abc", StatusCode::OK_200},
  17272. {"/a.c", StatusCode::OK_200},
  17273. };
  17274. for (const auto &x : cases) {
  17275. auto res = cli.Get(x.path);
  17276. ASSERT_TRUE(res) << x.path;
  17277. EXPECT_EQ(x.status, res->status) << x.path;
  17278. }
  17279. }
  17280. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17281. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17282. // from exhausting the stack, so it must only constrain routes that actually
  17283. // run a regular expression. A literal route is matched by comparison and
  17284. // stays usable at any length.
  17285. Server svr;
  17286. const std::string pattern =
  17287. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17288. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17289. res.set_content("hit", "text/plain");
  17290. });
  17291. auto port = svr.bind_to_any_port(HOST);
  17292. std::thread t([&]() { svr.listen_after_bind(); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. });
  17298. svr.wait_until_ready();
  17299. Client cli(HOST, port);
  17300. auto res = cli.Get(pattern);
  17301. ASSERT_TRUE(res);
  17302. EXPECT_EQ(StatusCode::OK_200, res->status);
  17303. }
  17304. TEST(ParseUrlTest, VariousPatterns) {
  17305. {
  17306. detail::UrlComponents uc;
  17307. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17308. EXPECT_EQ("http", uc.scheme);
  17309. EXPECT_EQ("example.com", uc.host);
  17310. EXPECT_EQ("8080", uc.port);
  17311. EXPECT_EQ("/path", uc.path);
  17312. EXPECT_EQ("?q=1", uc.query);
  17313. }
  17314. {
  17315. detail::UrlComponents uc;
  17316. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17317. EXPECT_EQ("https", uc.scheme);
  17318. EXPECT_EQ("example.com", uc.host);
  17319. EXPECT_TRUE(uc.port.empty());
  17320. EXPECT_EQ("/path", uc.path);
  17321. }
  17322. {
  17323. detail::UrlComponents uc;
  17324. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17325. EXPECT_EQ("::1", uc.host);
  17326. EXPECT_EQ("8080", uc.port);
  17327. EXPECT_EQ("/path", uc.path);
  17328. }
  17329. {
  17330. detail::UrlComponents uc;
  17331. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17332. }
  17333. {
  17334. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17335. // the path while the connection still targets the bracketed host.
  17336. detail::UrlComponents uc;
  17337. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17338. }
  17339. {
  17340. detail::UrlComponents uc;
  17341. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17342. }
  17343. {
  17344. detail::UrlComponents uc;
  17345. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17346. EXPECT_EQ("::1", uc.host);
  17347. EXPECT_TRUE(uc.port.empty());
  17348. EXPECT_EQ("/path", uc.path);
  17349. }
  17350. {
  17351. detail::UrlComponents uc;
  17352. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17353. EXPECT_TRUE(uc.scheme.empty());
  17354. EXPECT_EQ("example.com", uc.host);
  17355. EXPECT_EQ("/path", uc.path);
  17356. EXPECT_EQ("?q=1", uc.query);
  17357. }
  17358. {
  17359. detail::UrlComponents uc;
  17360. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17361. EXPECT_TRUE(uc.host.empty());
  17362. EXPECT_EQ("/path", uc.path);
  17363. EXPECT_EQ("?q=1", uc.query);
  17364. }
  17365. {
  17366. detail::UrlComponents uc;
  17367. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17368. EXPECT_EQ("example.com", uc.host);
  17369. EXPECT_EQ("8080", uc.port);
  17370. }
  17371. {
  17372. // Unix socket path — must not be parsed as host
  17373. detail::UrlComponents uc;
  17374. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17375. EXPECT_TRUE(uc.host.empty());
  17376. }
  17377. {
  17378. detail::UrlComponents uc;
  17379. ASSERT_TRUE(detail::parse_url("", uc));
  17380. EXPECT_TRUE(uc.host.empty());
  17381. EXPECT_TRUE(uc.path.empty());
  17382. }
  17383. {
  17384. detail::UrlComponents uc;
  17385. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17386. }
  17387. {
  17388. detail::UrlComponents uc;
  17389. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17390. }
  17391. {
  17392. // Accepted by parse_url; callers restrict to http/https
  17393. detail::UrlComponents uc;
  17394. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17395. EXPECT_EQ("ftp", uc.scheme);
  17396. }
  17397. {
  17398. detail::UrlComponents uc;
  17399. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17400. }
  17401. {
  17402. detail::UrlComponents uc;
  17403. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17404. }
  17405. }
  17406. TEST(ParseUrlTest, FragmentHandling) {
  17407. {
  17408. detail::UrlComponents uc;
  17409. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17410. EXPECT_EQ("/path", uc.path);
  17411. EXPECT_TRUE(uc.query.empty());
  17412. }
  17413. {
  17414. detail::UrlComponents uc;
  17415. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17416. EXPECT_TRUE(uc.path.empty());
  17417. EXPECT_TRUE(uc.query.empty());
  17418. }
  17419. }
  17420. TEST(ParseUrlTest, UserinfoHandling) {
  17421. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17422. // parsers would see evil.com as the host.
  17423. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17424. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17425. for (auto url : urls) {
  17426. detail::UrlComponents uc;
  17427. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17428. }
  17429. }
  17430. TEST(ParseUrlTest, IPv6EdgeCases) {
  17431. {
  17432. detail::UrlComponents uc;
  17433. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17434. EXPECT_TRUE(uc.scheme.empty());
  17435. EXPECT_EQ("::1", uc.host);
  17436. EXPECT_EQ("8080", uc.port);
  17437. }
  17438. {
  17439. // Zone ID '%25' is not in [a-fA-F0-9:]
  17440. detail::UrlComponents uc;
  17441. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17442. }
  17443. }
  17444. TEST(ParseUrlTest, SchemeEdgeCases) {
  17445. {
  17446. detail::UrlComponents uc;
  17447. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17448. }
  17449. {
  17450. detail::UrlComponents uc;
  17451. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17452. }
  17453. {
  17454. detail::UrlComponents uc;
  17455. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17456. }
  17457. }
  17458. TEST(ParseUrlTest, PortEdgeCases) {
  17459. {
  17460. detail::UrlComponents uc;
  17461. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17462. EXPECT_TRUE(uc.port.empty());
  17463. EXPECT_EQ("/path", uc.path);
  17464. }
  17465. {
  17466. // parse_url accepts any port string; validation is done by parse_port
  17467. detail::UrlComponents uc;
  17468. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17469. EXPECT_EQ("abc", uc.port);
  17470. }
  17471. }
  17472. TEST(ParseUrlTest, WebSocketPatterns) {
  17473. {
  17474. detail::UrlComponents uc;
  17475. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17476. EXPECT_EQ("ws", uc.scheme);
  17477. EXPECT_EQ("echo.example.com", uc.host);
  17478. EXPECT_EQ("8080", uc.port);
  17479. EXPECT_EQ("/ws", uc.path);
  17480. }
  17481. {
  17482. detail::UrlComponents uc;
  17483. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17484. EXPECT_EQ("wss", uc.scheme);
  17485. EXPECT_EQ("echo.example.com", uc.host);
  17486. EXPECT_TRUE(uc.port.empty());
  17487. EXPECT_EQ("/ws", uc.path);
  17488. }
  17489. }
  17490. TEST(ParseUrlTest, QueryOnly) {
  17491. detail::UrlComponents uc;
  17492. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17493. EXPECT_TRUE(uc.host.empty());
  17494. EXPECT_TRUE(uc.path.empty());
  17495. EXPECT_EQ("?q=1&r=2", uc.query);
  17496. }
  17497. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17498. detail::UrlComponents uc;
  17499. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17500. EXPECT_TRUE(uc.scheme.empty());
  17501. EXPECT_EQ("example.com", uc.host);
  17502. EXPECT_EQ("443", uc.port);
  17503. EXPECT_EQ("/path", uc.path);
  17504. }
  17505. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17506. // If ipv6 regex working, regex match codepath is taken.
  17507. // else port will default to 80 in Client impl
  17508. int clientImplMagicPort = 80;
  17509. int port = 4321;
  17510. // above ports must be different to avoid false negative
  17511. EXPECT_NE(clientImplMagicPort, port);
  17512. std::string ipV6TestURL = "http://[ff06::c3]";
  17513. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17514. CLIENT_PRIVATE_KEY_FILE);
  17515. EXPECT_EQ(cli.port(), port);
  17516. }
  17517. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17518. auto file_path = "./www/dir/index.html";
  17519. auto dir_path = "./www/dir";
  17520. detail::FileStat stat_file(file_path);
  17521. EXPECT_TRUE(stat_file.is_file());
  17522. EXPECT_FALSE(stat_file.is_dir());
  17523. detail::FileStat stat_dir(dir_path);
  17524. EXPECT_FALSE(stat_dir.is_file());
  17525. EXPECT_TRUE(stat_dir.is_dir());
  17526. }
  17527. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17528. // IPv4 with default HTTP port (80)
  17529. EXPECT_EQ("example.com",
  17530. detail::make_host_and_port_string("example.com", 80, false));
  17531. // IPv4 with default HTTPS port (443)
  17532. EXPECT_EQ("example.com",
  17533. detail::make_host_and_port_string("example.com", 443, true));
  17534. // IPv4 with non-default HTTP port
  17535. EXPECT_EQ("example.com:8080",
  17536. detail::make_host_and_port_string("example.com", 8080, false));
  17537. // IPv4 with non-default HTTPS port
  17538. EXPECT_EQ("example.com:8443",
  17539. detail::make_host_and_port_string("example.com", 8443, true));
  17540. // IPv6 with default HTTP port (80)
  17541. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17542. // IPv6 with default HTTPS port (443)
  17543. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17544. // IPv6 with non-default HTTP port
  17545. EXPECT_EQ("[::1]:8080",
  17546. detail::make_host_and_port_string("::1", 8080, false));
  17547. // IPv6 with non-default HTTPS port
  17548. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17549. // IPv6 full address with default port
  17550. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17551. detail::make_host_and_port_string(
  17552. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17553. // IPv6 full address with non-default port
  17554. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17555. detail::make_host_and_port_string(
  17556. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17557. // IPv6 localhost with non-default port
  17558. EXPECT_EQ("[::1]:3000",
  17559. detail::make_host_and_port_string("::1", 3000, false));
  17560. // IPv6 with zone ID (link-local address) with default port
  17561. EXPECT_EQ("[fe80::1%eth0]",
  17562. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17563. // IPv6 with zone ID (link-local address) with non-default port
  17564. EXPECT_EQ("[fe80::1%eth0]:8080",
  17565. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17566. // Edge case: Port 443 with is_ssl=false (should add port)
  17567. EXPECT_EQ("example.com:443",
  17568. detail::make_host_and_port_string("example.com", 443, false));
  17569. // Edge case: Port 80 with is_ssl=true (should add port)
  17570. EXPECT_EQ("example.com:80",
  17571. detail::make_host_and_port_string("example.com", 80, true));
  17572. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17573. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17574. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17575. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17576. // Security fix: Already bracketed IPv6 should not get double brackets
  17577. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17578. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17579. EXPECT_EQ("[::1]:8080",
  17580. detail::make_host_and_port_string("[::1]", 8080, false));
  17581. EXPECT_EQ("[2001:db8::1]:8080",
  17582. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17583. EXPECT_EQ("[fe80::1%eth0]",
  17584. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17585. EXPECT_EQ("[fe80::1%eth0]:8080",
  17586. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17587. // Edge case: Empty host (should return as-is)
  17588. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17589. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17590. // This is a known limitation but shouldn't crash
  17591. EXPECT_EQ("[host:name]",
  17592. detail::make_host_and_port_string("host:name", 80, false));
  17593. // Port number edge cases (no validation, but should not crash)
  17594. EXPECT_EQ("example.com:0",
  17595. detail::make_host_and_port_string("example.com", 0, false));
  17596. EXPECT_EQ("example.com:-1",
  17597. detail::make_host_and_port_string("example.com", -1, false));
  17598. EXPECT_EQ("example.com:65535",
  17599. detail::make_host_and_port_string("example.com", 65535, false));
  17600. EXPECT_EQ("example.com:65536",
  17601. detail::make_host_and_port_string("example.com", 65536, false));
  17602. }
  17603. #ifdef CPPHTTPLIB_SSL_ENABLED
  17604. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17605. httplib::SSLClient cli("roblox.com", 443);
  17606. cli.set_follow_location(true);
  17607. auto res = cli.Get("/");
  17608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17609. EXPECT_EQ(StatusCode::OK_200, res->status);
  17610. }
  17611. #endif
  17612. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17613. Server svr;
  17614. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17615. EXPECT_EQ(res.status, 400);
  17616. });
  17617. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17618. auto se = detail::scope_exit([&] {
  17619. svr.stop();
  17620. thread.join();
  17621. ASSERT_FALSE(svr.is_running());
  17622. });
  17623. svr.wait_until_ready();
  17624. Client cli(HOST, PORT);
  17625. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17626. }
  17627. TEST(InvalidHeaderCharsTest, is_field_name) {
  17628. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17629. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17630. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17631. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17632. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17633. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17634. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17635. EXPECT_FALSE(detail::fields::is_field_name(""));
  17636. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17637. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17638. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17639. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17640. }
  17641. TEST(InvalidHeaderCharsTest, is_field_value) {
  17642. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17643. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17644. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17645. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17646. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17647. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17648. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17649. EXPECT_TRUE(detail::fields::is_field_value(""));
  17650. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17651. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17652. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17653. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17654. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17655. }
  17656. TEST(InvalidHeaderCharsTest, OnServer) {
  17657. Server svr;
  17658. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17659. std::string header = "Not Set";
  17660. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17661. res.set_header(header, "value");
  17662. res.set_content("Page Content Page Content", "text/plain");
  17663. });
  17664. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17665. std::string header = "Not Set";
  17666. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17667. res.set_header("X-Test", header);
  17668. res.set_content("Page Content Page Content", "text/plain");
  17669. });
  17670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17671. auto se = detail::scope_exit([&] {
  17672. svr.stop();
  17673. thread.join();
  17674. ASSERT_FALSE(svr.is_running());
  17675. });
  17676. svr.wait_until_ready();
  17677. Client cli(HOST, PORT);
  17678. {
  17679. auto res = cli.Get(
  17680. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17682. EXPECT_EQ("Page Content Page Content", res->body);
  17683. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17684. }
  17685. {
  17686. auto res = cli.Get(
  17687. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17689. EXPECT_EQ("Page Content Page Content", res->body);
  17690. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17691. }
  17692. }
  17693. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17694. auto handled = false;
  17695. Server svr;
  17696. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17697. thread t = thread([&] { svr.listen(HOST, PORT); });
  17698. auto se = detail::scope_exit([&] {
  17699. svr.stop();
  17700. t.join();
  17701. ASSERT_FALSE(svr.is_running());
  17702. ASSERT_FALSE(handled);
  17703. });
  17704. svr.wait_until_ready();
  17705. auto req = "POST /test HTTP/1.1\r\n"
  17706. "Content-Length: x\r\n"
  17707. "\r\n";
  17708. std::string response;
  17709. ASSERT_TRUE(send_request(1, req, &response));
  17710. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17711. response.substr(0, response.find("\r\n")));
  17712. }
  17713. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17714. // case-insensitive, and a server that receives a 100-continue expectation in
  17715. // an HTTP/1.0 request MUST ignore it.
  17716. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17717. std::string response;
  17718. ASSERT_TRUE(send_request(1, req, &response, port));
  17719. *got_100 = response.find("100 Continue") != std::string::npos;
  17720. }
  17721. class ExpectTokenTest : public ::testing::Test {
  17722. protected:
  17723. void SetUp() override {
  17724. svr_.Post("/p", [](const Request &, Response &res) {
  17725. res.set_content("ok", "text/plain");
  17726. });
  17727. port_ = svr_.bind_to_any_port(HOST);
  17728. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17729. svr_.wait_until_ready();
  17730. }
  17731. void TearDown() override {
  17732. svr_.stop();
  17733. if (thread_.joinable()) { thread_.join(); }
  17734. }
  17735. std::string request(const char *version, const char *expect_value) const {
  17736. return std::string("POST /p ") + version +
  17737. "\r\n"
  17738. "Host: localhost\r\n"
  17739. "Content-Length: 2\r\n"
  17740. "Connection: close\r\n"
  17741. "Expect: " +
  17742. expect_value +
  17743. "\r\n"
  17744. "\r\n"
  17745. "hi";
  17746. }
  17747. Server svr_;
  17748. int port_ = 0;
  17749. thread thread_;
  17750. };
  17751. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17752. bool got_100 = false;
  17753. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17754. EXPECT_TRUE(got_100);
  17755. }
  17756. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17757. bool got_100 = true;
  17758. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17759. EXPECT_FALSE(got_100);
  17760. }
  17761. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17762. bool got_100 = false;
  17763. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17764. EXPECT_TRUE(got_100);
  17765. }
  17766. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17767. bool got_100 = false;
  17768. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17769. EXPECT_TRUE(got_100);
  17770. }
  17771. // `100 Continue` is sent only when the server starts reading the body, so a
  17772. // request rejected before that never invites the client to send it. The
  17773. // requests below carry the expectation but withhold the body, as a client
  17774. // waiting for `100 Continue` would.
  17775. // A POST that expects `100 Continue` and withholds its two-byte body.
  17776. static std::string expect_headers_only(const std::string &path) {
  17777. return "POST " + path +
  17778. " HTTP/1.1\r\n"
  17779. "Host: localhost\r\n"
  17780. "Content-Length: 2\r\n"
  17781. "Expect: 100-continue\r\n"
  17782. "\r\n";
  17783. }
  17784. class ExpectLazyContinueTest : public ::testing::Test {
  17785. protected:
  17786. void SetUp() override {
  17787. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17788. if (req.path == "/pre-routing") {
  17789. res.status = StatusCode::Unauthorized_401;
  17790. return Server::HandlerResponse::Handled;
  17791. }
  17792. return Server::HandlerResponse::Unhandled;
  17793. });
  17794. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17795. if (req.matched_route == "/pre-request") {
  17796. res.status = StatusCode::Forbidden_403;
  17797. return Server::HandlerResponse::Handled;
  17798. }
  17799. return Server::HandlerResponse::Unhandled;
  17800. });
  17801. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17802. res.set_content("ok", "text/plain");
  17803. });
  17804. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17805. res.set_content("ok", "text/plain");
  17806. });
  17807. svr_.Post("/reader-used", [](const Request &, Response &res,
  17808. const ContentReader &content_reader) {
  17809. std::string body;
  17810. content_reader([&](const char *data, size_t len) {
  17811. body.append(data, len);
  17812. return true;
  17813. });
  17814. res.set_content(body, "text/plain");
  17815. });
  17816. svr_.Post("/reader-unused",
  17817. [](const Request &, Response &res, const ContentReader &) {
  17818. res.set_content("ignored", "text/plain");
  17819. });
  17820. port_ = svr_.bind_to_any_port(HOST);
  17821. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17822. svr_.wait_until_ready();
  17823. }
  17824. void TearDown() override {
  17825. svr_.stop();
  17826. if (thread_.joinable()) { thread_.join(); }
  17827. }
  17828. // Sends `req` and reads until the server closes the connection. Returns
  17829. // false if the read had to wait for the client-side timeout instead.
  17830. bool send_until_closed(const std::string &req, std::string *resp) const {
  17831. auto start = std::chrono::steady_clock::now();
  17832. if (!send_request(3, req, resp, port_)) { return false; }
  17833. auto elapsed = std::chrono::steady_clock::now() - start;
  17834. return elapsed < std::chrono::seconds(2);
  17835. }
  17836. // The final response comes without `100 Continue`, and the server closes
  17837. // the connection since the body may or may not follow.
  17838. void expect_final_without_interim(const std::string &path,
  17839. const char *status_line) const {
  17840. std::string resp;
  17841. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17842. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17843. EXPECT_EQ(0u, resp.find(status_line));
  17844. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17845. }
  17846. Server svr_;
  17847. int port_ = 0;
  17848. thread thread_;
  17849. };
  17850. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17851. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17852. }
  17853. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17854. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17855. }
  17856. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17857. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17858. }
  17859. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17860. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17861. }
  17862. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17863. // The body follows once `100 Continue` has had time to arrive.
  17864. auto req = expect_headers_only("/reader-used");
  17865. req.insert(req.size() - 2, "Connection: close\r\n");
  17866. std::string resp;
  17867. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17868. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17869. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17870. EXPECT_NE(std::string::npos, resp.find("hi"));
  17871. }
  17872. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17873. // Large enough for the client to add `Expect: 100-continue` itself.
  17874. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17875. std::atomic<bool> body_sent{false};
  17876. Client cli(HOST, port_);
  17877. auto res = cli.Post(
  17878. "/pre-request", length,
  17879. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17880. body_sent = true;
  17881. std::string chunk(len, 'x');
  17882. sink.write(chunk.data(), chunk.size());
  17883. return true;
  17884. },
  17885. "application/octet-stream");
  17886. ASSERT_TRUE(res);
  17887. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17888. EXPECT_FALSE(body_sent);
  17889. }
  17890. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17891. Server svr;
  17892. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17893. return StatusCode::ExpectationFailed_417;
  17894. });
  17895. svr.Post("/p", [](const Request &, Response &res) {
  17896. res.set_content("ok", "text/plain");
  17897. });
  17898. auto port = svr.bind_to_any_port(HOST);
  17899. thread t = thread([&] { svr.listen_after_bind(); });
  17900. auto se = detail::scope_exit([&] {
  17901. svr.stop();
  17902. t.join();
  17903. });
  17904. svr.wait_until_ready();
  17905. std::string resp;
  17906. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17907. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17908. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17909. // Exactly one response: the route handler must not run after the 417.
  17910. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17911. }
  17912. #ifndef _WIN32
  17913. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17914. static constexpr char reject[] = "Unauthorized";
  17915. static constexpr char accept[] = "Upload accepted";
  17916. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17917. Server svr;
  17918. svr.set_expect_100_continue_handler(
  17919. [](const Request & /*req*/, Response &res) {
  17920. res.status = StatusCode::Unauthorized_401;
  17921. res.set_content(reject, "text/plain");
  17922. return res.status;
  17923. });
  17924. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17925. res.set_content(accept, "text/plain");
  17926. });
  17927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17928. auto se = detail::scope_exit([&] {
  17929. svr.stop();
  17930. thread.join();
  17931. ASSERT_FALSE(svr.is_running());
  17932. });
  17933. svr.wait_until_ready();
  17934. {
  17935. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17936. curl_easy_init(), &curl_easy_cleanup};
  17937. ASSERT_NE(curl, nullptr);
  17938. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17939. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17940. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17941. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17942. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17943. &curl_slist_free_all};
  17944. ASSERT_NE(list, nullptr);
  17945. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17946. struct read_data {
  17947. uint64_t read_size;
  17948. uint64_t total_size;
  17949. } data = {0, total_size};
  17950. using read_callback_t =
  17951. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17952. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17953. void *userdata) -> size_t {
  17954. read_data *d = (read_data *)userdata;
  17955. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17956. std::fill_n(ptr, size * nmemb, 'A');
  17957. d->read_size += size * nmemb;
  17958. return size * nmemb;
  17959. };
  17960. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  17961. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17962. std::vector<char> buffer;
  17963. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17964. using write_callback_t =
  17965. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17966. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17967. void *userdata) -> size_t {
  17968. std::vector<char> *buf = (std::vector<char> *)userdata;
  17969. buf->reserve(buf->size() + size * nmemb + 1);
  17970. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17971. return size * nmemb;
  17972. };
  17973. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17974. {
  17975. const auto res = curl_easy_perform(curl.get());
  17976. ASSERT_EQ(res, CURLE_OK);
  17977. }
  17978. {
  17979. auto response_code = long{};
  17980. const auto res =
  17981. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17982. ASSERT_EQ(res, CURLE_OK);
  17983. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17984. }
  17985. {
  17986. auto dl = curl_off_t{};
  17987. const auto res =
  17988. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17989. ASSERT_EQ(res, CURLE_OK);
  17990. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17991. }
  17992. {
  17993. buffer.push_back('\0');
  17994. ASSERT_STRCASEEQ(buffer.data(), reject);
  17995. }
  17996. }
  17997. }
  17998. #endif
  17999. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18000. // Regression test for #2458.
  18001. //
  18002. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18003. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18004. // ticket can make the client socket spuriously readable during the
  18005. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18006. // the client withholds the body and then blocks reading a response that never
  18007. // comes, failing with `Failed to read connection`.
  18008. //
  18009. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18010. // within the timeout. This raw OpenSSL server deliberately never sends
  18011. // `100 Continue`; the client must still deliver the body and receive 200.
  18012. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18013. signal(SIGPIPE, SIG_IGN);
  18014. const auto port = PORT + 4;
  18015. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18016. ASSERT_NE(srv, INVALID_SOCKET);
  18017. int opt = 1;
  18018. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18019. sockaddr_in addr{};
  18020. addr.sin_family = AF_INET;
  18021. addr.sin_port = htons(static_cast<uint16_t>(port));
  18022. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18023. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18024. ASSERT_EQ(0, ::listen(srv, 1));
  18025. std::atomic<size_t> server_body_bytes{0};
  18026. auto server_thread = std::thread([&] {
  18027. sockaddr_in cli_addr{};
  18028. socklen_t cli_len = sizeof(cli_addr);
  18029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18030. if (cli == INVALID_SOCKET) { return; }
  18031. // Bound the lifetime of the server side so a buggy client (which never
  18032. // sends the body) cannot make this thread block forever on join.
  18033. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18034. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18035. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18036. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18037. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18038. SSL *ssl = SSL_new(ctx);
  18039. SSL_set_fd(ssl, static_cast<int>(cli));
  18040. if (SSL_accept(ssl) > 0) {
  18041. // Read the request headers. Reading here also flushes the TLS 1.3
  18042. // session tickets to the client. Deliberately do NOT send
  18043. // `100 Continue`.
  18044. std::string buf;
  18045. char tmp[1024];
  18046. while (buf.find("\r\n\r\n") == std::string::npos) {
  18047. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18048. if (n <= 0) { break; }
  18049. buf.append(tmp, static_cast<size_t>(n));
  18050. }
  18051. // A correct client sends the body now; count what arrives.
  18052. auto pos = buf.find("\r\n\r\n");
  18053. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18054. while (body < 4096) {
  18055. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18056. if (n <= 0) { break; }
  18057. body += static_cast<size_t>(n);
  18058. }
  18059. server_body_bytes = body;
  18060. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18061. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18062. SSL_shutdown(ssl);
  18063. }
  18064. SSL_free(ssl);
  18065. detail::close_socket(cli);
  18066. SSL_CTX_free(ctx);
  18067. });
  18068. auto se = detail::scope_exit([&] {
  18069. server_thread.join();
  18070. detail::close_socket(srv);
  18071. });
  18072. SSLClient cli("127.0.0.1", port);
  18073. cli.enable_server_certificate_verification(false);
  18074. cli.set_connection_timeout(5, 0);
  18075. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18076. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18077. std::string body(4096, 'A');
  18078. auto res = cli.Put("/api/test", body, "application/json");
  18079. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18080. EXPECT_EQ(StatusCode::OK_200, res->status);
  18081. EXPECT_EQ(body.size(), server_body_bytes.load());
  18082. }
  18083. #endif
  18084. template <typename S, typename C>
  18085. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18086. svr.Get("/stream", [&](const Request &, Response &res) {
  18087. auto data = new std::string("01234567890123456789");
  18088. res.set_content_provider(
  18089. data->size(), "text/plain",
  18090. [&, data](size_t offset, size_t length, DataSink &sink) {
  18091. const size_t DATA_CHUNK_SIZE = 4;
  18092. const auto &d = *data;
  18093. std::this_thread::sleep_for(std::chrono::seconds(1));
  18094. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18095. return true;
  18096. },
  18097. [data](bool success) {
  18098. EXPECT_FALSE(success);
  18099. delete data;
  18100. });
  18101. });
  18102. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18103. auto i = new size_t(0);
  18104. res.set_content_provider(
  18105. "text/plain",
  18106. [i](size_t, DataSink &sink) {
  18107. if (*i < 5) {
  18108. std::this_thread::sleep_for(std::chrono::seconds(1));
  18109. sink.write("abcd", 4);
  18110. (*i)++;
  18111. } else {
  18112. sink.done();
  18113. }
  18114. return true;
  18115. },
  18116. [i](bool success) {
  18117. EXPECT_FALSE(success);
  18118. delete i;
  18119. });
  18120. });
  18121. svr.Get("/chunked", [&](const Request &, Response &res) {
  18122. auto i = new size_t(0);
  18123. res.set_chunked_content_provider(
  18124. "text/plain",
  18125. [i](size_t, DataSink &sink) {
  18126. if (*i < 5) {
  18127. std::this_thread::sleep_for(std::chrono::seconds(1));
  18128. sink.os << "abcd";
  18129. (*i)++;
  18130. } else {
  18131. sink.done();
  18132. }
  18133. return true;
  18134. },
  18135. [i](bool success) {
  18136. EXPECT_FALSE(success);
  18137. delete i;
  18138. });
  18139. });
  18140. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18141. auto se = detail::scope_exit([&] {
  18142. svr.stop();
  18143. listen_thread.join();
  18144. ASSERT_FALSE(svr.is_running());
  18145. });
  18146. svr.wait_until_ready();
  18147. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18148. {
  18149. auto start = std::chrono::steady_clock::now();
  18150. auto res = cli.Get("/stream");
  18151. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18152. std::chrono::steady_clock::now() - start)
  18153. .count();
  18154. ASSERT_FALSE(res);
  18155. EXPECT_EQ(Error::Read, res.error());
  18156. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18157. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18158. }
  18159. {
  18160. auto start = std::chrono::steady_clock::now();
  18161. auto res = cli.Get("/stream_without_length");
  18162. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18163. std::chrono::steady_clock::now() - start)
  18164. .count();
  18165. ASSERT_FALSE(res);
  18166. EXPECT_EQ(Error::Read, res.error());
  18167. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18168. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18169. }
  18170. {
  18171. auto start = std::chrono::steady_clock::now();
  18172. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18173. EXPECT_EQ("abcd", string(data, data_length));
  18174. return true;
  18175. });
  18176. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18177. std::chrono::steady_clock::now() - start)
  18178. .count();
  18179. ASSERT_FALSE(res);
  18180. EXPECT_EQ(Error::Read, res.error());
  18181. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18182. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18183. }
  18184. }
  18185. TEST(MaxTimeoutTest, ContentStream) {
  18186. time_t timeout = 2000;
  18187. time_t threshold = 200;
  18188. Server svr;
  18189. Client cli("localhost", PORT);
  18190. max_timeout_test(svr, cli, timeout, threshold);
  18191. }
  18192. #ifdef CPPHTTPLIB_SSL_ENABLED
  18193. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18194. time_t timeout = 2000;
  18195. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18197. SSLClient cli("localhost", PORT);
  18198. cli.enable_server_certificate_verification(false);
  18199. max_timeout_test(svr, cli, timeout, threshold);
  18200. }
  18201. #endif
  18202. class EventDispatcher {
  18203. public:
  18204. EventDispatcher() {}
  18205. bool wait_event(DataSink *sink) {
  18206. unique_lock<mutex> lk(m_);
  18207. int id = id_;
  18208. // Wait with timeout to prevent hanging if client disconnects
  18209. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18210. [&] { return cid_ == id; })) {
  18211. return false; // Timeout occurred
  18212. }
  18213. sink->write(message_.data(), message_.size());
  18214. return true;
  18215. }
  18216. void send_event(const string &message) {
  18217. lock_guard<mutex> lk(m_);
  18218. cid_ = id_++;
  18219. message_ = message;
  18220. cv_.notify_all();
  18221. }
  18222. private:
  18223. mutex m_;
  18224. condition_variable cv_;
  18225. atomic_int id_{0};
  18226. atomic_int cid_{-1};
  18227. string message_;
  18228. };
  18229. TEST(ClientInThreadTest, Issue2068) {
  18230. EventDispatcher ed;
  18231. Server svr;
  18232. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18233. res.set_chunked_content_provider("text/event-stream",
  18234. [&](size_t /*offset*/, DataSink &sink) {
  18235. return ed.wait_event(&sink);
  18236. });
  18237. });
  18238. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18239. svr.wait_until_ready();
  18240. thread event_thread([&] {
  18241. int id = 0;
  18242. while (svr.is_running()) {
  18243. this_thread::sleep_for(chrono::milliseconds(500));
  18244. std::stringstream ss;
  18245. ss << "data: " << id << "\n\n";
  18246. ed.send_event(ss.str());
  18247. id++;
  18248. }
  18249. });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. listen_thread.join();
  18253. event_thread.join();
  18254. ASSERT_FALSE(svr.is_running());
  18255. });
  18256. {
  18257. auto client = detail::make_unique<Client>(HOST, PORT);
  18258. client->set_read_timeout(std::chrono::minutes(10));
  18259. std::atomic<bool> stop{false};
  18260. std::thread t([&] {
  18261. client->Get("/event1",
  18262. [&](const char *, size_t) -> bool { return !stop; });
  18263. });
  18264. std::this_thread::sleep_for(std::chrono::seconds(2));
  18265. stop = true;
  18266. client->stop();
  18267. t.join();
  18268. // Reset client after thread has finished
  18269. client.reset();
  18270. }
  18271. }
  18272. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18273. auto handled = false;
  18274. Server svr;
  18275. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18276. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18277. auto se = detail::scope_exit([&] {
  18278. svr.stop();
  18279. t.join();
  18280. ASSERT_FALSE(svr.is_running());
  18281. ASSERT_FALSE(handled);
  18282. });
  18283. svr.wait_until_ready();
  18284. // Two Content-Length headers with different values — must be rejected
  18285. auto req = "POST /test HTTP/1.1\r\n"
  18286. "Content-Length: 5\r\n"
  18287. "Content-Length: 10\r\n"
  18288. "\r\n"
  18289. "hello";
  18290. std::string response;
  18291. ASSERT_TRUE(send_request(1, req, &response));
  18292. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18293. response.substr(0, response.find("\r\n")));
  18294. }
  18295. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18296. auto handled = false;
  18297. Server svr;
  18298. svr.Post("/test", [&](const Request &, Response &res) {
  18299. handled = true;
  18300. res.set_content("ok", "text/plain");
  18301. });
  18302. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18303. auto se = detail::scope_exit([&] {
  18304. svr.stop();
  18305. t.join();
  18306. ASSERT_FALSE(svr.is_running());
  18307. ASSERT_TRUE(handled);
  18308. });
  18309. svr.wait_until_ready();
  18310. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18311. auto req = "POST /test HTTP/1.1\r\n"
  18312. "Host: localhost\r\n"
  18313. "Content-Length: 5\r\n"
  18314. "Content-Length: 5\r\n"
  18315. "\r\n"
  18316. "hello";
  18317. std::string response;
  18318. ASSERT_TRUE(send_request(1, req, &response));
  18319. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18320. }
  18321. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18322. Server svr;
  18323. svr.Get("/test", [](const Request &, Response &res) {
  18324. res.set_content("ok", "text/plain");
  18325. });
  18326. auto port = svr.bind_to_any_port(HOST);
  18327. thread t = thread([&] { svr.listen_after_bind(); });
  18328. auto se = detail::scope_exit([&] {
  18329. svr.stop();
  18330. t.join();
  18331. ASSERT_FALSE(svr.is_running());
  18332. });
  18333. svr.wait_until_ready();
  18334. auto status_line = [&](const std::string &host_lines) {
  18335. std::string res;
  18336. send_request(
  18337. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18338. &res, port);
  18339. return res.substr(0, res.find("\r\n"));
  18340. };
  18341. const char *accepted[] = {
  18342. "Host: localhost\r\n",
  18343. "Host: a.example:8080\r\n",
  18344. "Host: my_service\r\n",
  18345. "Host: [::1]:8080\r\n",
  18346. "Host: [fe80::1%25eth0]\r\n",
  18347. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18348. };
  18349. for (auto host_lines : accepted) {
  18350. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18351. }
  18352. const char *rejected[] = {
  18353. "Host: a.example\r\nHost: b.example\r\n",
  18354. "Host: a.example\r\nHost: a.example\r\n",
  18355. "Host: a@b.example\r\n",
  18356. "Host: a.example/b\r\n",
  18357. "Host: a.example\\b\r\n",
  18358. "Host: a.example?b\r\n",
  18359. "Host: a.example#b\r\n",
  18360. "Host: a.example b.example\r\n",
  18361. };
  18362. for (auto host_lines : rejected) {
  18363. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18364. << host_lines;
  18365. }
  18366. }
  18367. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18368. Server svr;
  18369. svr.Get("/", [](const Request &req, Response &res) {
  18370. EXPECT_EQ(2U, req.trailers.size());
  18371. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18372. // Denied
  18373. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18374. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18375. // Accepted
  18376. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18377. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18378. EXPECT_TRUE(req.has_trailer("X-World"));
  18379. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18380. res.set_content("ok", "text/plain");
  18381. });
  18382. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. t.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. const std::string req = "GET / HTTP/1.1\r\n"
  18390. "Transfer-Encoding: chunked\r\n"
  18391. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18392. "\r\n"
  18393. "0\r\n"
  18394. "Content-Length: 10\r\n"
  18395. "Host: internal.local\r\n"
  18396. "Content-Type: malicious/content\r\n"
  18397. "Cookie: any\r\n"
  18398. "Set-Cookie: any\r\n"
  18399. "X-Forwarded-For: attacker.com\r\n"
  18400. "X-Real-Ip: 1.1.1.1\r\n"
  18401. "X-Hello: hello\r\n"
  18402. "X-World: world\r\n"
  18403. "\r\n";
  18404. std::string res;
  18405. ASSERT_TRUE(send_request(1, req, &res));
  18406. }
  18407. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18408. // several field lines, and the combined value is what has to be parsed. A
  18409. // Trailer field split across lines therefore declares every name it lists;
  18410. // reading only the first line silently drops the trailers the later lines
  18411. // declare. The prohibited-trailer filter still applies to every line.
  18412. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18413. Server svr;
  18414. size_t observed_trailer_count = 0;
  18415. std::string observed_hello;
  18416. std::string observed_world;
  18417. bool observed_content_length = true;
  18418. svr.Get("/", [&](const Request &req, Response &res) {
  18419. observed_trailer_count = req.trailers.size();
  18420. observed_hello = req.get_trailer_value("X-Hello");
  18421. observed_world = req.get_trailer_value("X-World");
  18422. observed_content_length = req.has_trailer("Content-Length");
  18423. res.set_content("ok", "text/plain");
  18424. });
  18425. auto port = svr.bind_to_any_port(HOST);
  18426. thread t = thread([&]() { svr.listen_after_bind(); });
  18427. auto se = detail::scope_exit([&] {
  18428. svr.stop();
  18429. t.join();
  18430. ASSERT_FALSE(svr.is_running());
  18431. });
  18432. svr.wait_until_ready();
  18433. const std::string req = "GET / HTTP/1.1\r\n"
  18434. "Host: localhost\r\n"
  18435. "Transfer-Encoding: chunked\r\n"
  18436. "Trailer: X-Hello\r\n"
  18437. "Trailer: X-World, Content-Length\r\n"
  18438. "\r\n"
  18439. "0\r\n"
  18440. "X-Hello: hello\r\n"
  18441. "X-World: world\r\n"
  18442. "Content-Length: 10\r\n"
  18443. "\r\n";
  18444. std::string res;
  18445. ASSERT_TRUE(send_request(1, req, &res, port));
  18446. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18447. // Accepted: both field lines contribute to the declared set
  18448. EXPECT_EQ(2U, observed_trailer_count);
  18449. EXPECT_EQ(observed_hello, "hello");
  18450. EXPECT_EQ(observed_world, "world");
  18451. // Denied: a prohibited name stays prohibited on a later field line
  18452. EXPECT_FALSE(observed_content_length);
  18453. }
  18454. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18455. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18456. // unbounded run of fields that are never declared, because the counter would
  18457. // only advance for declared fields.
  18458. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18459. Server svr;
  18460. bool handler_called = false;
  18461. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18462. handler_called = true;
  18463. res.set_content("ok", "text/plain");
  18464. });
  18465. auto port = svr.bind_to_any_port(HOST);
  18466. thread t = thread([&]() { svr.listen_after_bind(); });
  18467. auto se = detail::scope_exit([&] {
  18468. svr.stop();
  18469. t.join();
  18470. ASSERT_FALSE(svr.is_running());
  18471. });
  18472. svr.wait_until_ready();
  18473. // Declare nothing, then send far more undeclared trailer fields than the
  18474. // header-count limit. Parsing must stop and reject the request rather than
  18475. // read every line.
  18476. std::string req = "GET / HTTP/1.1\r\n"
  18477. "Transfer-Encoding: chunked\r\n"
  18478. "\r\n"
  18479. "0\r\n";
  18480. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18481. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18482. }
  18483. req += "\r\n";
  18484. std::string res;
  18485. ASSERT_TRUE(send_request(1, req, &res, port));
  18486. // The request is rejected before the handler runs.
  18487. EXPECT_FALSE(handler_called);
  18488. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18489. }
  18490. // The set of declared trailer names is capped so a peer cannot grow it without
  18491. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18492. // declared past the cap is not honored, even if the field is actually sent.
  18493. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18494. Server svr;
  18495. // One name inside the cap and one past it, so the test tracks the cap rather
  18496. // than a fixed count.
  18497. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18498. const std::string within_cap_name = "X-T-0";
  18499. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18500. bool observed_within_cap = false;
  18501. bool observed_past_cap = false;
  18502. svr.Get("/", [&](const Request &req, Response &res) {
  18503. observed_within_cap = req.has_trailer(within_cap_name);
  18504. observed_past_cap = req.has_trailer(past_cap_name);
  18505. res.set_content("ok", "text/plain");
  18506. });
  18507. auto port = svr.bind_to_any_port(HOST);
  18508. thread t = thread([&]() { svr.listen_after_bind(); });
  18509. auto se = detail::scope_exit([&] {
  18510. svr.stop();
  18511. t.join();
  18512. ASSERT_FALSE(svr.is_running());
  18513. });
  18514. svr.wait_until_ready();
  18515. // Declare more trailer names than the cap in a single Trailer field, then
  18516. // actually send the first (within the cap) and the last (past it).
  18517. std::string trailer_decl = "Trailer: ";
  18518. for (int i = 0; i < declared_count; i++) {
  18519. if (i != 0) { trailer_decl += ", "; }
  18520. trailer_decl += "X-T-" + std::to_string(i);
  18521. }
  18522. trailer_decl += "\r\n";
  18523. const std::string req = "GET / HTTP/1.1\r\n"
  18524. "Host: localhost\r\n"
  18525. "Transfer-Encoding: chunked\r\n" +
  18526. trailer_decl +
  18527. "\r\n"
  18528. "0\r\n" +
  18529. within_cap_name + ": a\r\n" + past_cap_name +
  18530. ": b\r\n"
  18531. "\r\n";
  18532. std::string res;
  18533. ASSERT_TRUE(send_request(1, req, &res, port));
  18534. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18535. // A name within the cap is honored; one declared past the cap is dropped.
  18536. EXPECT_TRUE(observed_within_cap);
  18537. EXPECT_FALSE(observed_past_cap);
  18538. }
  18539. // A direct client that is not listed in trusted_proxies must not be able to
  18540. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18541. // the peer address on the actual TCP connection determines whether the
  18542. // header is honored.
  18543. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18544. Server svr;
  18545. // Deliberately does NOT include the loopback address the test client
  18546. // actually connects from, so the direct connection is not a trusted proxy.
  18547. svr.set_trusted_proxies({"203.0.113.66"});
  18548. std::string observed_remote_addr;
  18549. svr.Get("/ip", [&](const Request &req, Response &res) {
  18550. observed_remote_addr = req.remote_addr;
  18551. res.set_content("ok", "text/plain");
  18552. });
  18553. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18554. auto se = detail::scope_exit([&] {
  18555. svr.stop();
  18556. t.join();
  18557. ASSERT_FALSE(svr.is_running());
  18558. });
  18559. svr.wait_until_ready();
  18560. Client cli(HOST, PORT);
  18561. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18563. EXPECT_EQ(StatusCode::OK_200, res->status);
  18564. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18565. // ignored entirely and the real connection-level address retained.
  18566. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18567. observed_remote_addr == "127.0.0.1");
  18568. }
  18569. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18570. Server svr;
  18571. std::string observed_remote_addr;
  18572. std::string observed_xff;
  18573. svr.Get("/ip", [&](const Request &req, Response &res) {
  18574. observed_remote_addr = req.remote_addr;
  18575. observed_xff = req.get_header_value("X-Forwarded-For");
  18576. res.set_content("ok", "text/plain");
  18577. });
  18578. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18579. auto se = detail::scope_exit([&] {
  18580. svr.stop();
  18581. t.join();
  18582. ASSERT_FALSE(svr.is_running());
  18583. });
  18584. svr.wait_until_ready();
  18585. Client cli(HOST, PORT);
  18586. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18588. EXPECT_EQ(StatusCode::OK_200, res->status);
  18589. EXPECT_EQ(observed_xff, "203.0.113.66");
  18590. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18591. observed_remote_addr == "127.0.0.1");
  18592. }
  18593. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18594. Server svr;
  18595. svr.set_trusted_proxies({"203.0.113.66"});
  18596. std::string observed_remote_addr;
  18597. std::string observed_xff;
  18598. svr.Get("/ip", [&](const Request &req, Response &res) {
  18599. observed_remote_addr = req.remote_addr;
  18600. observed_xff = req.get_header_value("X-Forwarded-For");
  18601. res.set_content("ok", "text/plain");
  18602. });
  18603. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18604. auto se = detail::scope_exit([&] {
  18605. svr.stop();
  18606. t.join();
  18607. ASSERT_FALSE(svr.is_running());
  18608. });
  18609. svr.wait_until_ready();
  18610. Client cli(HOST, PORT);
  18611. auto res = cli.Get("/ip");
  18612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18613. EXPECT_EQ(StatusCode::OK_200, res->status);
  18614. EXPECT_EQ(observed_xff, "");
  18615. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18616. observed_remote_addr == "127.0.0.1");
  18617. }
  18618. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18619. Server svr;
  18620. // Include the loopback address the test client actually connects from, so
  18621. // the direct connection itself is recognized as the trusted proxy hop.
  18622. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18623. std::string observed_remote_addr;
  18624. std::string observed_xff;
  18625. svr.Get("/ip", [&](const Request &req, Response &res) {
  18626. observed_remote_addr = req.remote_addr;
  18627. observed_xff = req.get_header_value("X-Forwarded-For");
  18628. res.set_content("ok", "text/plain");
  18629. });
  18630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18631. auto se = detail::scope_exit([&] {
  18632. svr.stop();
  18633. t.join();
  18634. ASSERT_FALSE(svr.is_running());
  18635. });
  18636. svr.wait_until_ready();
  18637. Client cli(HOST, PORT);
  18638. auto res = cli.Get(
  18639. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18641. EXPECT_EQ(StatusCode::OK_200, res->status);
  18642. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18643. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18644. }
  18645. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18646. Server svr;
  18647. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18648. std::string observed_remote_addr;
  18649. std::string observed_xff;
  18650. svr.Get("/ip", [&](const Request &req, Response &res) {
  18651. observed_remote_addr = req.remote_addr;
  18652. observed_xff = req.get_header_value("X-Forwarded-For");
  18653. res.set_content("ok", "text/plain");
  18654. });
  18655. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18656. auto se = detail::scope_exit([&] {
  18657. svr.stop();
  18658. t.join();
  18659. ASSERT_FALSE(svr.is_running());
  18660. });
  18661. svr.wait_until_ready();
  18662. Client cli(HOST, PORT);
  18663. auto res = cli.Get(
  18664. "/ip",
  18665. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18667. EXPECT_EQ(StatusCode::OK_200, res->status);
  18668. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18669. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18670. }
  18671. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18672. Server svr;
  18673. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18674. std::string observed_remote_addr;
  18675. std::string observed_xff;
  18676. svr.Get("/ip", [&](const Request &req, Response &res) {
  18677. observed_remote_addr = req.remote_addr;
  18678. observed_xff = req.get_header_value("X-Forwarded-For");
  18679. res.set_content("ok", "text/plain");
  18680. });
  18681. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18682. auto se = detail::scope_exit([&] {
  18683. svr.stop();
  18684. t.join();
  18685. ASSERT_FALSE(svr.is_running());
  18686. });
  18687. svr.wait_until_ready();
  18688. Client cli(HOST, PORT);
  18689. auto res = cli.Get(
  18690. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18692. EXPECT_EQ(StatusCode::OK_200, res->status);
  18693. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18694. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18695. // and must not be selected.
  18696. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18697. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18698. }
  18699. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18700. Server svr;
  18701. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18702. std::string observed_remote_addr;
  18703. svr.Get("/ip", [&](const Request &req, Response &res) {
  18704. observed_remote_addr = req.remote_addr;
  18705. res.set_content("ok", "text/plain");
  18706. });
  18707. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18708. auto se = detail::scope_exit([&] {
  18709. svr.stop();
  18710. t.join();
  18711. ASSERT_FALSE(svr.is_running());
  18712. });
  18713. svr.wait_until_ready();
  18714. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18715. // a forged address and the trusted proxy's own address; the forged value must
  18716. // not win over the address the trusted proxy actually recorded.
  18717. Client cli(HOST, PORT);
  18718. auto res = cli.Get(
  18719. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18721. EXPECT_EQ(StatusCode::OK_200, res->status);
  18722. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18723. }
  18724. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18725. Server svr;
  18726. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18727. std::string observed_remote_addr;
  18728. std::string observed_xff;
  18729. svr.Get("/ip", [&](const Request &req, Response &res) {
  18730. observed_remote_addr = req.remote_addr;
  18731. observed_xff = req.get_header_value("X-Forwarded-For");
  18732. res.set_content("ok", "text/plain");
  18733. });
  18734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18735. auto se = detail::scope_exit([&] {
  18736. svr.stop();
  18737. t.join();
  18738. ASSERT_FALSE(svr.is_running());
  18739. });
  18740. svr.wait_until_ready();
  18741. Client cli(HOST, PORT);
  18742. auto res = cli.Get(
  18743. "/ip",
  18744. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18746. EXPECT_EQ(StatusCode::OK_200, res->status);
  18747. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18748. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18749. }
  18750. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18751. Server svr;
  18752. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18753. std::string observed_remote_addr;
  18754. std::string observed_xff;
  18755. svr.Get("/ip", [&](const Request &req, Response &res) {
  18756. observed_remote_addr = req.remote_addr;
  18757. observed_xff = req.get_header_value("X-Forwarded-For");
  18758. res.set_content("ok", "text/plain");
  18759. });
  18760. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18761. auto se = detail::scope_exit([&] {
  18762. svr.stop();
  18763. t.join();
  18764. ASSERT_FALSE(svr.is_running());
  18765. });
  18766. svr.wait_until_ready();
  18767. std::string raw_req =
  18768. "GET /ip HTTP/1.1\r\n"
  18769. "Host: localhost\r\n"
  18770. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18771. "Connection: close\r\n"
  18772. "\r\n";
  18773. std::string out;
  18774. ASSERT_TRUE(send_request(5, raw_req, &out));
  18775. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18776. // Header parser trims surrounding whitespace of the header value
  18777. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18778. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18779. }
  18780. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18781. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18782. // their own X-Forwarded-For as a separate field line rather than extending the
  18783. // one the client sent, so every occurrence has to be taken into account.
  18784. // Reading only the first one hands back the address the client chose.
  18785. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18786. Server svr;
  18787. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18788. std::string observed_remote_addr;
  18789. size_t observed_xff_count = 0;
  18790. svr.Get("/ip", [&](const Request &req, Response &res) {
  18791. observed_remote_addr = req.remote_addr;
  18792. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18793. res.set_content("ok", "text/plain");
  18794. });
  18795. auto port = svr.bind_to_any_port(HOST);
  18796. thread t = thread([&]() { svr.listen_after_bind(); });
  18797. auto se = detail::scope_exit([&] {
  18798. svr.stop();
  18799. t.join();
  18800. ASSERT_FALSE(svr.is_running());
  18801. });
  18802. svr.wait_until_ready();
  18803. // The client supplies the first field line; the trusted proxy appends the
  18804. // address it observed as a second one.
  18805. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18806. "Host: localhost\r\n"
  18807. "X-Forwarded-For: 1.2.3.4\r\n"
  18808. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18809. "Connection: close\r\n"
  18810. "\r\n";
  18811. std::string out;
  18812. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18813. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18814. EXPECT_EQ(observed_xff_count, 2U);
  18815. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18816. // The same chain spread over one field line per hop derives the same client
  18817. // address, i.e. the split and the comma-joined representations agree.
  18818. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18819. "Host: localhost\r\n"
  18820. "X-Forwarded-For: 1.2.3.4\r\n"
  18821. "X-Forwarded-For: 198.51.100.23\r\n"
  18822. "X-Forwarded-For: 192.0.2.45\r\n"
  18823. "Connection: close\r\n"
  18824. "\r\n";
  18825. out.clear();
  18826. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18827. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18828. EXPECT_EQ(observed_xff_count, 3U);
  18829. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18830. }
  18831. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18832. // crash the server (it used to call front() on an empty vector inside
  18833. // get_client_ip). The connection-level remote address must be retained instead.
  18834. static void run_malformed_xff_test(const std::string &xff_value) {
  18835. Server svr;
  18836. svr.set_trusted_proxies({"192.0.2.45"});
  18837. std::string observed_remote_addr;
  18838. svr.Get("/ip", [&](const Request &req, Response &res) {
  18839. observed_remote_addr = req.remote_addr;
  18840. res.set_content("ok", "text/plain");
  18841. });
  18842. int port = 0;
  18843. thread t = thread([&]() {
  18844. port = svr.bind_to_any_port(HOST);
  18845. svr.listen_after_bind();
  18846. });
  18847. auto se = detail::scope_exit([&] {
  18848. svr.stop();
  18849. t.join();
  18850. ASSERT_FALSE(svr.is_running());
  18851. });
  18852. svr.wait_until_ready();
  18853. Client cli(HOST, port);
  18854. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18856. EXPECT_EQ(StatusCode::OK_200, res->status);
  18857. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18858. observed_remote_addr == "127.0.0.1");
  18859. }
  18860. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18861. run_malformed_xff_test("");
  18862. }
  18863. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18864. run_malformed_xff_test(",");
  18865. }
  18866. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18867. run_malformed_xff_test(", , ,");
  18868. }
  18869. // The same rule applies to Accept: a request whose acceptable types are spread
  18870. // over several field lines must be negotiated against all of them.
  18871. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18872. // case-insensitive connection options. Comparing the whole field value against
  18873. // one option misses a client that sends several of them, and misses every
  18874. // casing but the one written in the comparison.
  18875. //
  18876. // Sends req, reads the response, then reuses the same socket for a second
  18877. // request to find out whether the server kept the connection.
  18878. static void probe_connection_reuse(int port, const std::string &req,
  18879. bool *announced_close, bool *reusable) {
  18880. auto error = Error::Success;
  18881. auto sock = detail::create_client_socket(
  18882. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18883. /*connection_timeout_sec=*/5, 0,
  18884. /*read_timeout_sec=*/1, 0,
  18885. /*write_timeout_sec=*/5, 0, std::string(), error);
  18886. ASSERT_NE(sock, INVALID_SOCKET);
  18887. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18888. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Connection: close\r\n"
  18891. "\r\n";
  18892. std::string first_response;
  18893. std::string second_response;
  18894. detail::process_client_socket(
  18895. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18896. [&](Stream &strm) {
  18897. if (strm.write(req.data(), req.size()) !=
  18898. static_cast<ssize_t>(req.size())) {
  18899. return false;
  18900. }
  18901. char buf[512];
  18902. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18903. // Headers plus the two-byte body of the handler below
  18904. while (reader.getline()) {
  18905. first_response += reader.ptr();
  18906. if (first_response.find("ok") != std::string::npos) { break; }
  18907. }
  18908. if (strm.write(second.data(), second.size()) !=
  18909. static_cast<ssize_t>(second.size())) {
  18910. return true;
  18911. }
  18912. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18913. while (reader2.getline()) {
  18914. second_response += reader2.ptr();
  18915. if (second_response.find("ok") != std::string::npos) { break; }
  18916. }
  18917. return true;
  18918. });
  18919. *announced_close =
  18920. first_response.find("Connection: close") != std::string::npos;
  18921. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18922. }
  18923. class ConnectionTokenTest : public ::testing::Test {
  18924. protected:
  18925. void SetUp() override {
  18926. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18927. res.set_content("ok", "text/plain");
  18928. });
  18929. port_ = svr_.bind_to_any_port(HOST);
  18930. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18931. svr_.wait_until_ready();
  18932. }
  18933. void TearDown() override {
  18934. svr_.stop();
  18935. if (thread_.joinable()) { thread_.join(); }
  18936. }
  18937. Server svr_;
  18938. int port_ = 0;
  18939. thread thread_;
  18940. };
  18941. // "close" alongside another option still closes the connection, and the
  18942. // response says so rather than leaving the peer to discover it.
  18943. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18944. bool announced_close = false;
  18945. bool reusable = true;
  18946. probe_connection_reuse(port_,
  18947. "GET /keepalive HTTP/1.1\r\n"
  18948. "Host: localhost\r\n"
  18949. "Connection: keep-alive, close\r\n"
  18950. "\r\n",
  18951. &announced_close, &reusable);
  18952. EXPECT_TRUE(announced_close);
  18953. EXPECT_FALSE(reusable);
  18954. }
  18955. // "close" split over two field lines is the same list, so it is honored too.
  18956. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18957. bool announced_close = false;
  18958. bool reusable = true;
  18959. probe_connection_reuse(port_,
  18960. "GET /keepalive HTTP/1.1\r\n"
  18961. "Host: localhost\r\n"
  18962. "Connection: keep-alive\r\n"
  18963. "Connection: close\r\n"
  18964. "\r\n",
  18965. &announced_close, &reusable);
  18966. EXPECT_TRUE(announced_close);
  18967. EXPECT_FALSE(reusable);
  18968. }
  18969. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18970. // keep-alive in the spelling everyone actually sends keeps its connection.
  18971. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18972. bool announced_close = false;
  18973. bool reusable = false;
  18974. probe_connection_reuse(port_,
  18975. "GET /keepalive HTTP/1.0\r\n"
  18976. "Host: localhost\r\n"
  18977. "Connection: keep-alive\r\n"
  18978. "\r\n",
  18979. &announced_close, &reusable);
  18980. EXPECT_FALSE(announced_close);
  18981. EXPECT_TRUE(reusable);
  18982. }
  18983. // A token the value merely contains is not the token itself.
  18984. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18985. bool announced_close = false;
  18986. bool reusable = false;
  18987. probe_connection_reuse(port_,
  18988. "GET /keepalive HTTP/1.1\r\n"
  18989. "Host: localhost\r\n"
  18990. "Connection: notclose\r\n"
  18991. "\r\n",
  18992. &announced_close, &reusable);
  18993. EXPECT_FALSE(announced_close);
  18994. EXPECT_TRUE(reusable);
  18995. }
  18996. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18997. Server svr;
  18998. std::vector<std::string> observed_types;
  18999. svr.Get("/", [&](const Request &req, Response &res) {
  19000. observed_types = req.accept_content_types;
  19001. res.set_content("ok", "text/plain");
  19002. });
  19003. auto port = svr.bind_to_any_port(HOST);
  19004. thread t = thread([&]() { svr.listen_after_bind(); });
  19005. auto se = detail::scope_exit([&] {
  19006. svr.stop();
  19007. t.join();
  19008. ASSERT_FALSE(svr.is_running());
  19009. });
  19010. svr.wait_until_ready();
  19011. Client cli(HOST, port);
  19012. Headers headers;
  19013. headers.emplace("Accept", "text/plain;q=0.5");
  19014. headers.emplace("Accept", "application/json");
  19015. auto res = cli.Get("/", headers);
  19016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19017. EXPECT_EQ(StatusCode::OK_200, res->status);
  19018. // Sorted by q-value, so the second field line's type comes first
  19019. ASSERT_EQ(2U, observed_types.size());
  19020. EXPECT_EQ("application/json", observed_types[0]);
  19021. EXPECT_EQ("text/plain", observed_types[1]);
  19022. }
  19023. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19024. // empty field line must not contribute a bare comma to the combined value.
  19025. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19026. Server svr;
  19027. std::vector<std::string> observed_types;
  19028. svr.Get("/", [&](const Request &req, Response &res) {
  19029. observed_types = req.accept_content_types;
  19030. res.set_content("ok", "text/plain");
  19031. });
  19032. auto port = svr.bind_to_any_port(HOST);
  19033. thread t = thread([&]() { svr.listen_after_bind(); });
  19034. auto se = detail::scope_exit([&] {
  19035. svr.stop();
  19036. t.join();
  19037. ASSERT_FALSE(svr.is_running());
  19038. });
  19039. svr.wait_until_ready();
  19040. // Empty first field line, then a real one
  19041. std::string raw_req = "GET / HTTP/1.1\r\n"
  19042. "Host: localhost\r\n"
  19043. "Accept:\r\n"
  19044. "Accept: application/json\r\n"
  19045. "Connection: close\r\n"
  19046. "\r\n";
  19047. std::string out;
  19048. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19049. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19050. ASSERT_EQ(1U, observed_types.size());
  19051. EXPECT_EQ("application/json", observed_types[0]);
  19052. }
  19053. // The skip in get_combined_header_value() is what keeps an empty field line
  19054. // from contributing a bare comma. Only a trailing empty field line exercises
  19055. // it: a leading one is already covered by the "combined is still empty" check,
  19056. // and parse_accept_header() now ignores the empty element either way, so the
  19057. // request-level test above can no longer tell the two apart.
  19058. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19059. Headers headers;
  19060. headers.emplace("Accept", "text/html");
  19061. headers.emplace("Accept", "");
  19062. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19063. headers.clear();
  19064. headers.emplace("Accept", "");
  19065. headers.emplace("Accept", "application/json");
  19066. EXPECT_EQ("application/json",
  19067. detail::get_combined_header_value(headers, "Accept"));
  19068. }
  19069. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19070. // An encoding offered on a later Accept-Encoding field line is still offered.
  19071. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19072. Server svr;
  19073. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19074. res.set_content(std::string(1024, 'x'), "text/plain");
  19075. });
  19076. auto port = svr.bind_to_any_port(HOST);
  19077. thread t = thread([&]() { svr.listen_after_bind(); });
  19078. auto se = detail::scope_exit([&] {
  19079. svr.stop();
  19080. t.join();
  19081. ASSERT_FALSE(svr.is_running());
  19082. });
  19083. svr.wait_until_ready();
  19084. Client cli(HOST, port);
  19085. cli.set_decompress(false);
  19086. Headers headers;
  19087. headers.emplace("Accept-Encoding", "identity");
  19088. headers.emplace("Accept-Encoding", "gzip");
  19089. auto res = cli.Get("/", headers);
  19090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19091. EXPECT_EQ(StatusCode::OK_200, res->status);
  19092. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19093. }
  19094. #endif
  19095. #ifndef _WIN32
  19096. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19097. Server svr;
  19098. svr.Post("/post", [&](const Request &req, Response &res) {
  19099. res.set_content(req.body, "text/plain");
  19100. });
  19101. svr.Put("/put", [&](const Request &req, Response &res) {
  19102. res.set_content(req.body, "text/plain");
  19103. });
  19104. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19105. res.set_content(req.body, "text/plain");
  19106. });
  19107. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19108. res.set_content(req.body, "text/plain");
  19109. });
  19110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19111. auto se = detail::scope_exit([&] {
  19112. svr.stop();
  19113. t.join();
  19114. ASSERT_FALSE(svr.is_running());
  19115. });
  19116. svr.wait_until_ready();
  19117. std::string resp;
  19118. // POST without Content-Length
  19119. ASSERT_TRUE(send_request(5,
  19120. "POST /post HTTP/1.1\r\n"
  19121. "Host: localhost\r\n"
  19122. "Connection: close\r\n"
  19123. "\r\n",
  19124. &resp));
  19125. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19126. // PUT without Content-Length
  19127. resp.clear();
  19128. ASSERT_TRUE(send_request(5,
  19129. "PUT /put HTTP/1.1\r\n"
  19130. "Host: localhost\r\n"
  19131. "Connection: close\r\n"
  19132. "\r\n",
  19133. &resp));
  19134. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19135. // PATCH without Content-Length
  19136. resp.clear();
  19137. ASSERT_TRUE(send_request(5,
  19138. "PATCH /patch HTTP/1.1\r\n"
  19139. "Host: localhost\r\n"
  19140. "Connection: close\r\n"
  19141. "\r\n",
  19142. &resp));
  19143. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19144. // DELETE without Content-Length
  19145. resp.clear();
  19146. ASSERT_TRUE(send_request(5,
  19147. "DELETE /delete HTTP/1.1\r\n"
  19148. "Host: localhost\r\n"
  19149. "Connection: close\r\n"
  19150. "\r\n",
  19151. &resp));
  19152. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19153. }
  19154. #endif
  19155. //==============================================================================
  19156. // open_stream() Tests
  19157. //==============================================================================
  19158. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19159. std::string result;
  19160. char buf[8192];
  19161. ssize_t n;
  19162. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19163. result.append(buf, static_cast<size_t>(n));
  19164. }
  19165. return result;
  19166. }
  19167. // Mock stream for unit tests
  19168. class MockStream : public Stream {
  19169. public:
  19170. std::string data;
  19171. size_t pos = 0;
  19172. ssize_t error_after = -1; // -1 = no error
  19173. explicit MockStream(const std::string &d, ssize_t err = -1)
  19174. : data(d), error_after(err) {}
  19175. bool is_readable() const override { return true; }
  19176. bool wait_readable() const override { return true; }
  19177. bool wait_writable() const override { return true; }
  19178. ssize_t read(char *ptr, size_t size) override {
  19179. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19180. if (pos >= data.size()) return 0;
  19181. size_t limit =
  19182. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19183. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19184. std::memcpy(ptr, data.data() + pos, to_read);
  19185. pos += to_read;
  19186. return static_cast<ssize_t>(to_read);
  19187. }
  19188. ssize_t write(const char *, size_t) override { return -1; }
  19189. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19190. ip = "127.0.0.1";
  19191. port = 0;
  19192. }
  19193. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19194. ip = "127.0.0.1";
  19195. port = 0;
  19196. }
  19197. socket_t socket() const override { return INVALID_SOCKET; }
  19198. time_t duration() const override { return 0; }
  19199. };
  19200. TEST(StreamHandleTest, Basic) {
  19201. ClientImpl::StreamHandle handle;
  19202. EXPECT_FALSE(handle.is_valid());
  19203. handle.response = detail::make_unique<Response>();
  19204. handle.error = Error::Connection;
  19205. EXPECT_FALSE(handle.is_valid());
  19206. handle.error = Error::Success;
  19207. EXPECT_TRUE(handle.is_valid());
  19208. }
  19209. TEST(BodyReaderTest, Basic) {
  19210. MockStream stream("Hello, World!");
  19211. detail::BodyReader reader;
  19212. reader.stream = &stream;
  19213. reader.content_length = 13;
  19214. char buf[32];
  19215. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19216. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19217. EXPECT_TRUE(reader.eof);
  19218. }
  19219. TEST(BodyReaderTest, NoStream) {
  19220. detail::BodyReader reader;
  19221. char buf[32];
  19222. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19223. EXPECT_EQ(Error::Connection, reader.last_error);
  19224. }
  19225. TEST(BodyReaderTest, Error) {
  19226. MockStream stream("Hello, World!", 5);
  19227. detail::BodyReader reader;
  19228. reader.stream = &stream;
  19229. reader.content_length = 13;
  19230. char buf[32];
  19231. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19232. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19233. EXPECT_EQ(Error::Read, reader.last_error);
  19234. }
  19235. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19236. // Mock-based StreamHandle tests relying on private internals are removed.
  19237. class OpenStreamTest : public ::testing::Test {
  19238. protected:
  19239. void SetUp() override {
  19240. svr_.Get("/hello", [](const Request &, Response &res) {
  19241. res.set_content("Hello World!", "text/plain");
  19242. });
  19243. svr_.Get("/large", [](const Request &, Response &res) {
  19244. res.set_content(std::string(10000, 'X'), "text/plain");
  19245. });
  19246. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19247. res.set_content("Hello World!", "image/jpeg");
  19248. res.set_header("Content-Encoding", "UTF-8");
  19249. });
  19250. svr_.Get("/chunked", [](const Request &, Response &res) {
  19251. res.set_chunked_content_provider("text/plain",
  19252. [](size_t offset, DataSink &sink) {
  19253. if (offset < 15) {
  19254. sink.write("chunk", 5);
  19255. return true;
  19256. }
  19257. sink.done();
  19258. return true;
  19259. });
  19260. });
  19261. svr_.Get("/compressible", [](const Request &, Response &res) {
  19262. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19263. DataSink &sink) {
  19264. if (offset < 100 * 1024) {
  19265. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19266. sink.write(chunk.data(), chunk.size());
  19267. return true;
  19268. }
  19269. sink.done();
  19270. return true;
  19271. });
  19272. });
  19273. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19274. [](const Request & /*req*/, Response &res) {
  19275. auto i = new int(0);
  19276. res.set_header("Trailer", "Content-Length, X-Allowed");
  19277. res.set_chunked_content_provider(
  19278. "text/plain",
  19279. [i](size_t /*offset*/, DataSink &sink) {
  19280. switch (*i) {
  19281. case 0: sink.os << "123"; break;
  19282. case 1: sink.os << "456"; break;
  19283. case 2: sink.os << "789"; break;
  19284. case 3: {
  19285. sink.done_with_trailer(
  19286. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19287. } break;
  19288. }
  19289. (*i)++;
  19290. return true;
  19291. },
  19292. [i](bool success) {
  19293. EXPECT_TRUE(success);
  19294. delete i;
  19295. });
  19296. });
  19297. // Echo headers endpoint for header-related tests
  19298. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19299. std::string body;
  19300. for (const auto &h : req.headers) {
  19301. body.append(h.first);
  19302. body.push_back(':');
  19303. body.append(h.second);
  19304. body.push_back('\n');
  19305. }
  19306. res.set_content(body, "text/plain");
  19307. });
  19308. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19309. std::string body;
  19310. for (const auto &h : req.headers) {
  19311. body.append(h.first);
  19312. body.push_back(':');
  19313. body.append(h.second);
  19314. body.push_back('\n');
  19315. }
  19316. res.set_content(body, "text/plain");
  19317. });
  19318. port_ = svr_.bind_to_any_port("127.0.0.1");
  19319. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19320. svr_.wait_until_ready();
  19321. }
  19322. void TearDown() override {
  19323. svr_.stop();
  19324. if (thread_.joinable()) thread_.join();
  19325. }
  19326. Server svr_;
  19327. std::thread thread_;
  19328. int port_ = 0;
  19329. };
  19330. TEST_F(OpenStreamTest, Basic) {
  19331. Client cli("127.0.0.1", port_);
  19332. auto handle = cli.open_stream("GET", "/hello");
  19333. EXPECT_TRUE(handle.is_valid());
  19334. EXPECT_EQ("Hello World!", read_all(handle));
  19335. }
  19336. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19337. Client cli("127.0.0.1", port_);
  19338. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19339. ASSERT_TRUE(handle.is_valid());
  19340. EXPECT_EQ("Hello World!", read_all(handle));
  19341. }
  19342. TEST_F(OpenStreamTest, SmallBuffer) {
  19343. Client cli("127.0.0.1", port_);
  19344. auto handle = cli.open_stream("GET", "/hello");
  19345. std::string result;
  19346. char buf[4];
  19347. ssize_t n;
  19348. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19349. result.append(buf, static_cast<size_t>(n));
  19350. EXPECT_EQ("Hello World!", result);
  19351. }
  19352. TEST_F(OpenStreamTest, DefaultHeaders) {
  19353. Client cli("127.0.0.1", port_);
  19354. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19355. {
  19356. auto handle = cli.open_stream("GET", "/echo-headers");
  19357. ASSERT_TRUE(handle.is_valid());
  19358. auto body = read_all(handle);
  19359. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19360. std::string::npos);
  19361. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19362. std::string::npos);
  19363. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19364. }
  19365. // open_stream POST with body and no explicit content_type should NOT add
  19366. // text/plain Content-Type (behavior differs from non-streaming path), but
  19367. // should include Content-Length
  19368. {
  19369. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19370. ASSERT_TRUE(handle.is_valid());
  19371. auto body = read_all(handle);
  19372. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19373. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19374. }
  19375. // open_stream POST with explicit Content-Type should preserve it
  19376. {
  19377. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19378. {{"Content-Type", "application/custom"}},
  19379. "{}", "application/custom");
  19380. ASSERT_TRUE(handle.is_valid());
  19381. auto body = read_all(handle);
  19382. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19383. }
  19384. // User-specified User-Agent must not be overwritten for stream API
  19385. {
  19386. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19387. {{"User-Agent", "MyAgent/1.2"}});
  19388. ASSERT_TRUE(handle.is_valid());
  19389. auto body = read_all(handle);
  19390. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19391. }
  19392. }
  19393. TEST_F(OpenStreamTest, Large) {
  19394. Client cli("127.0.0.1", port_);
  19395. auto handle = cli.open_stream("GET", "/large");
  19396. EXPECT_EQ(10000u, read_all(handle).size());
  19397. }
  19398. TEST_F(OpenStreamTest, ConnectionError) {
  19399. Client cli("127.0.0.1", 9999);
  19400. auto handle = cli.open_stream("GET", "/hello");
  19401. EXPECT_FALSE(handle.is_valid());
  19402. }
  19403. TEST_F(OpenStreamTest, Chunked) {
  19404. Client cli("127.0.0.1", port_);
  19405. auto handle = cli.open_stream("GET", "/chunked");
  19406. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19407. "Transfer-Encoding") == "chunked");
  19408. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19409. }
  19410. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19411. Client cli("127.0.0.1", port_);
  19412. auto handle =
  19413. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19414. ASSERT_TRUE(handle.is_valid());
  19415. // Consume body to allow trailers to be received/parsed
  19416. auto body = read_all(handle);
  19417. // Explicitly parse trailers (ensure trailers are available for assertion)
  19418. handle.parse_trailers_if_needed();
  19419. EXPECT_EQ(std::string("123456789"), body);
  19420. // The response should include a Trailer header declaring both names
  19421. ASSERT_TRUE(handle.response);
  19422. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19423. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19424. handle.response->get_header_value("Trailer"));
  19425. // Prohibited trailer must not be present
  19426. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19427. // Allowed trailer should be present
  19428. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19429. EXPECT_EQ(std::string("yes"),
  19430. handle.response->get_trailer_value("X-Allowed"));
  19431. // Verify trailers are NOT present as regular headers
  19432. EXPECT_EQ(std::string(""),
  19433. handle.response->get_header_value("Content-Length"));
  19434. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19435. }
  19436. // Accepts one connection on an OS-assigned port, which it hands over through
  19437. // port_promise, reads the request head and sends back response. after_send,
  19438. // if given, runs on the connection before it is closed.
  19439. static std::thread
  19440. serve_single_response(std::promise<int> &port_promise,
  19441. const std::string &response,
  19442. std::function<void(socket_t)> after_send = nullptr) {
  19443. return std::thread([&port_promise, response, after_send] {
  19444. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19445. default_socket_options(srv);
  19446. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19447. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19448. sockaddr_in addr{};
  19449. addr.sin_family = AF_INET;
  19450. addr.sin_port = htons(0); // Let OS assign a free port
  19451. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19452. int opt = 1;
  19453. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19454. #ifdef _WIN32
  19455. reinterpret_cast<const char *>(&opt),
  19456. #else
  19457. &opt,
  19458. #endif
  19459. sizeof(opt));
  19460. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19461. ::listen(srv, 1) != 0) {
  19462. port_promise.set_value(-1);
  19463. detail::close_socket(srv);
  19464. return;
  19465. }
  19466. socklen_t addr_len = sizeof(addr);
  19467. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19468. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19469. sockaddr_in cli_addr{};
  19470. socklen_t cli_len = sizeof(cli_addr);
  19471. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19472. if (cli != INVALID_SOCKET) {
  19473. // Read the complete HTTP request (until the blank line that terminates
  19474. // headers) before sending the response. If the server closes the socket
  19475. // while the client's request data is still unread in the kernel receive
  19476. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19477. // connection on both sides: it discards the client's receive buffer
  19478. // (which already holds our response) and causes any in-progress write on
  19479. // the client to fail with ECONNRESET. Reading all request data first
  19480. // ensures close() emits a graceful FIN.
  19481. {
  19482. char rbuf[256];
  19483. std::string req;
  19484. while (req.find("\r\n\r\n") == std::string::npos) {
  19485. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19486. if (n <= 0) { break; }
  19487. req.append(rbuf, static_cast<size_t>(n));
  19488. }
  19489. }
  19490. ::send(cli,
  19491. #ifdef _WIN32
  19492. static_cast<const char *>(response.c_str()),
  19493. static_cast<int>(response.size()),
  19494. #else
  19495. response.c_str(), response.size(),
  19496. #endif
  19497. 0);
  19498. if (after_send) { after_send(cli); }
  19499. detail::close_socket(cli);
  19500. }
  19501. detail::close_socket(srv);
  19502. });
  19503. }
  19504. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19505. #ifndef _WIN32
  19506. signal(SIGPIPE, SIG_IGN);
  19507. #endif
  19508. std::promise<int> port_promise;
  19509. auto port_future = port_promise.get_future();
  19510. auto server_thread =
  19511. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19512. "Content-Type: text/plain\r\n"
  19513. "Content-Length: not-a-number\r\n"
  19514. "Connection: close\r\n"
  19515. "\r\n"
  19516. "hello");
  19517. auto port = port_future.get();
  19518. ASSERT_GT(port, 0);
  19519. Client cli("127.0.0.1", port);
  19520. auto handle = cli.open_stream("GET", "/");
  19521. EXPECT_FALSE(handle.is_valid());
  19522. server_thread.join();
  19523. }
  19524. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19525. #ifndef _WIN32
  19526. signal(SIGPIPE, SIG_IGN);
  19527. #endif
  19528. std::promise<int> port_promise;
  19529. auto port_future = port_promise.get_future();
  19530. auto server_thread = serve_single_response(
  19531. port_promise, "HTTP/1.1 200 OK\r\n"
  19532. "Content-Type: text/plain\r\n"
  19533. "Content-Length: 99999999999999999999999999\r\n"
  19534. "Connection: close\r\n"
  19535. "\r\n"
  19536. "hello");
  19537. auto port = port_future.get();
  19538. ASSERT_GT(port, 0);
  19539. // Historically std::stoull would throw std::out_of_range here and crash
  19540. // the process, then parsing silently clamped to a bogus framing length and
  19541. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19542. // so the stream fails to open, matching the not-a-number case above. The
  19543. // process still must NOT terminate.
  19544. Client cli("127.0.0.1", port);
  19545. auto handle = cli.open_stream("GET", "/");
  19546. EXPECT_FALSE(handle.is_valid());
  19547. server_thread.join();
  19548. }
  19549. // Serves `response` to the single request `fn` makes with a fresh client.
  19550. template <typename Fn>
  19551. static void with_single_response(const std::string &response, Fn fn) {
  19552. #ifndef _WIN32
  19553. signal(SIGPIPE, SIG_IGN);
  19554. #endif
  19555. std::promise<int> port_promise;
  19556. auto port_future = port_promise.get_future();
  19557. auto server_thread = serve_single_response(port_promise, response);
  19558. auto se = detail::scope_exit([&] { server_thread.join(); });
  19559. auto port = port_future.get();
  19560. ASSERT_GT(port, 0);
  19561. Client cli("127.0.0.1", port);
  19562. fn(cli);
  19563. }
  19564. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19565. // Neither Content-Length nor chunked: the body ends at the close
  19566. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19567. "Connection: close\r\n"
  19568. "\r\n"
  19569. "hello";
  19570. with_single_response(close_delimited, [](Client &cli) {
  19571. auto handle = cli.open_stream("GET", "/");
  19572. ASSERT_TRUE(handle.is_valid());
  19573. EXPECT_EQ("hello", read_all(handle));
  19574. EXPECT_FALSE(handle.has_read_error());
  19575. });
  19576. // A close before the end of the Content-Length is still an error
  19577. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19578. "Content-Length: 10\r\n"
  19579. "\r\n"
  19580. "hello";
  19581. with_single_response(short_content_length, [](Client &cli) {
  19582. auto handle = cli.open_stream("GET", "/");
  19583. ASSERT_TRUE(handle.is_valid());
  19584. read_all(handle);
  19585. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19586. });
  19587. // So is a close before the last chunk
  19588. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19589. "Transfer-Encoding: chunked\r\n"
  19590. "\r\n"
  19591. "5\r\nhello\r\n";
  19592. with_single_response(short_chunked, [](Client &cli) {
  19593. auto handle = cli.open_stream("GET", "/");
  19594. ASSERT_TRUE(handle.is_valid());
  19595. read_all(handle);
  19596. EXPECT_TRUE(handle.has_read_error());
  19597. });
  19598. }
  19599. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19600. const char *responses[] = {
  19601. "HTTP/1.1 103 Early Hints\r\n"
  19602. "Link: </style.css>; rel=preload\r\n"
  19603. "\r\n"
  19604. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19605. "HTTP/1.1 100 Continue\r\n"
  19606. "X-Note: interim\r\n"
  19607. "\r\n"
  19608. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19609. };
  19610. for (auto response : responses) {
  19611. with_single_response(response, [](Client &cli) {
  19612. auto res = cli.Get("/");
  19613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19614. EXPECT_EQ(StatusCode::OK_200, res->status);
  19615. EXPECT_EQ("ok", res->body);
  19616. });
  19617. }
  19618. }
  19619. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19620. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19621. const std::string final_response =
  19622. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19623. std::string interims;
  19624. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19625. interims += interim;
  19626. }
  19627. with_single_response(interims + final_response, [](Client &cli) {
  19628. auto res = cli.Get("/");
  19629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19630. EXPECT_EQ("ok", res->body);
  19631. });
  19632. with_single_response(interims + interim + final_response, [](Client &cli) {
  19633. auto res = cli.Get("/");
  19634. ASSERT_FALSE(res);
  19635. EXPECT_EQ(Error::Read, res.error());
  19636. });
  19637. }
  19638. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19639. #ifndef _WIN32
  19640. signal(SIGPIPE, SIG_IGN);
  19641. #endif
  19642. // The server answers the head without asking for the body. Bytes it then
  19643. // reads on the connection would be taken for the body the request declared.
  19644. auto closed_by_client = false;
  19645. std::promise<int> port_promise;
  19646. auto server_thread = serve_single_response(
  19647. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19648. [&](socket_t sock) {
  19649. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19650. char buf[256];
  19651. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19652. });
  19653. Client cli("127.0.0.1", port_promise.get_future().get());
  19654. cli.set_keep_alive(true);
  19655. cli.set_read_timeout(1, 0);
  19656. // Long enough for the client to send Expect: 100-continue.
  19657. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19660. cli.Get("/second");
  19661. server_thread.join();
  19662. EXPECT_TRUE(closed_by_client);
  19663. }
  19664. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19665. // Long enough for the client to send Expect: 100-continue
  19666. with_single_response(
  19667. "HTTP/1.1 103 Early Hints\r\n"
  19668. "Link: </style.css>; rel=preload\r\n"
  19669. "\r\n"
  19670. "HTTP/1.1 401 Unauthorized\r\n"
  19671. "Content-Length: 0\r\n\r\n",
  19672. [](Client &cli) {
  19673. cli.set_read_timeout(2, 0);
  19674. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19676. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19677. });
  19678. }
  19679. #ifdef CPPHTTPLIB_SSL_ENABLED
  19680. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19681. #ifndef _WIN32
  19682. signal(SIGPIPE, SIG_IGN);
  19683. #endif
  19684. auto reused = false;
  19685. std::promise<int> port_promise;
  19686. auto server_thread = serve_single_response(
  19687. port_promise,
  19688. "HTTP/1.1 401 Unauthorized\r\n"
  19689. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19690. "Content-Length: 0\r\n\r\n",
  19691. [&](socket_t sock) {
  19692. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19693. char buf[256];
  19694. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19695. });
  19696. Client cli("127.0.0.1", port_promise.get_future().get());
  19697. cli.set_keep_alive(true);
  19698. cli.set_digest_auth("user", "pass");
  19699. cli.set_read_timeout(1, 0);
  19700. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19701. server_thread.join();
  19702. EXPECT_FALSE(reused);
  19703. }
  19704. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19705. // Any other answer to CONNECT would read as the origin's response.
  19706. struct {
  19707. const char *response;
  19708. bool passed_on;
  19709. } cases[] = {
  19710. {"HTTP/1.1 201 Created\r\n"
  19711. "Set-Cookie: session=from-proxy\r\n"
  19712. "Content-Length: 0\r\n\r\n",
  19713. false},
  19714. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19715. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19716. "Content-Length: 0\r\n\r\n",
  19717. true},
  19718. };
  19719. for (const auto &c : cases) {
  19720. std::promise<int> port_promise;
  19721. auto server_thread = serve_single_response(port_promise, c.response);
  19722. SSLClient cli("example.com", 443);
  19723. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19724. auto res = cli.Get("/");
  19725. server_thread.join();
  19726. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19727. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19728. if (res) {
  19729. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19730. }
  19731. }
  19732. }
  19733. #endif
  19734. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19735. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19736. // the chunked coding and drop Content-Length, so a front-end that trusts
  19737. // Content-Length would disagree about where the body ends (response
  19738. // smuggling). The client must reject such a response.
  19739. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19740. for (const char *te : {"chunked", "gzip, chunked"}) {
  19741. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19742. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19743. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19744. "5\r\nhello\r\n0\r\n\r\n";
  19745. with_single_response(response, [&](Client &cli) {
  19746. auto res = cli.Get("/");
  19747. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19748. EXPECT_EQ(Error::Read, res.error()) << te;
  19749. });
  19750. with_single_response(response, [&](Client &cli) {
  19751. auto handle = cli.open_stream("GET", "/");
  19752. EXPECT_FALSE(handle.is_valid()) << te;
  19753. EXPECT_EQ(Error::Read, handle.error) << te;
  19754. });
  19755. }
  19756. }
  19757. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19758. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19759. // closing the connection (unlike a request, which must be rejected).
  19760. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19761. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19762. "Transfer-Encoding: chunked\r\n"
  19763. "Connection: close\r\n"
  19764. "\r\n"
  19765. "5\r\nhello\r\n0\r\n\r\n",
  19766. "HTTP/1.1 200 OK\r\n"
  19767. "Transfer-Encoding: gzip\r\n"
  19768. "Connection: close\r\n"
  19769. "\r\n"
  19770. "hello"}) {
  19771. with_single_response(response, [&](Client &cli) {
  19772. auto res = cli.Get("/");
  19773. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19774. EXPECT_EQ("hello", res->body);
  19775. });
  19776. with_single_response(response, [&](Client &cli) {
  19777. auto handle = cli.open_stream("GET", "/");
  19778. ASSERT_TRUE(handle.is_valid()) << response;
  19779. EXPECT_EQ("hello", read_all(handle));
  19780. });
  19781. }
  19782. }
  19783. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19784. // framing headers describe nothing to read and must not be rejected.
  19785. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19786. const std::string framing = "Content-Length: 5\r\n"
  19787. "Transfer-Encoding: chunked\r\n"
  19788. "Connection: close\r\n"
  19789. "\r\n";
  19790. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19791. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19792. });
  19793. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19794. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19795. });
  19796. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19797. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19798. with_single_response(response, [&](Client &cli) {
  19799. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19800. });
  19801. with_single_response(response, [&](Client &cli) {
  19802. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19803. });
  19804. }
  19805. }
  19806. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19807. // response, is faulty framing, so the connection is not reused after it.
  19808. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19809. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19810. "Content-Length: 0\r\n"
  19811. "Transfer-Encoding: chunked\r\n"
  19812. "\r\n"
  19813. "5\r\nhello\r\n0\r\n\r\n",
  19814. "HTTP/1.0 200 Connection established\r\n"
  19815. "Connection: keep-alive\r\n"
  19816. "Transfer-Encoding: chunked\r\n"
  19817. "\r\n"
  19818. "5\r\nhello\r\n0\r\n\r\n"}) {
  19819. with_single_response(response, [&](Client &cli) {
  19820. cli.set_keep_alive(true);
  19821. auto res = cli.Get("/");
  19822. ASSERT_TRUE(res) << response;
  19823. EXPECT_EQ("hello", res->body);
  19824. EXPECT_FALSE(cli.is_socket_open()) << response;
  19825. });
  19826. }
  19827. }
  19828. // A payload max length of 0 means no limit, however the body is framed.
  19829. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19830. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19831. "Transfer-Encoding: chunked\r\n"
  19832. "\r\n"
  19833. "5\r\nhello\r\n0\r\n\r\n",
  19834. "HTTP/1.1 200 OK\r\n"
  19835. "Connection: close\r\n"
  19836. "\r\n"
  19837. "hello"}) {
  19838. with_single_response(response, [&](Client &cli) {
  19839. cli.set_payload_max_length(0);
  19840. auto res = cli.Get("/");
  19841. ASSERT_TRUE(res) << response;
  19842. EXPECT_EQ("hello", res->body) << response;
  19843. });
  19844. }
  19845. }
  19846. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19847. Server svr;
  19848. svr.set_payload_max_length(0);
  19849. svr.Post("/echo", [](const Request &req, Response &res) {
  19850. res.set_content(req.body, "text/plain");
  19851. });
  19852. auto port = svr.bind_to_any_port(HOST);
  19853. thread t = thread([&] { svr.listen_after_bind(); });
  19854. auto se = detail::scope_exit([&] {
  19855. svr.stop();
  19856. t.join();
  19857. ASSERT_FALSE(svr.is_running());
  19858. });
  19859. svr.wait_until_ready();
  19860. Client cli(HOST, port);
  19861. auto res = cli.Post(
  19862. "/echo",
  19863. [](size_t /*offset*/, DataSink &sink) {
  19864. sink.write("hello", 5);
  19865. sink.done();
  19866. return true;
  19867. },
  19868. "text/plain");
  19869. ASSERT_TRUE(res);
  19870. EXPECT_EQ(StatusCode::OK_200, res->status);
  19871. EXPECT_EQ("hello", res->body);
  19872. }
  19873. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19874. TEST_F(OpenStreamTest, Gzip) {
  19875. Client cli("127.0.0.1", port_);
  19876. auto handle = cli.open_stream("GET", "/compressible", {},
  19877. {{"Accept-Encoding", "gzip"}});
  19878. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19879. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19880. }
  19881. TEST_F(OpenStreamTest, TrailersWithGzip) {
  19882. Client cli("127.0.0.1", port_);
  19883. auto handle =
  19884. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  19885. {{"Accept-Encoding", "gzip"}});
  19886. ASSERT_TRUE(handle.is_valid());
  19887. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19888. EXPECT_EQ("123456789", read_all(handle));
  19889. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  19890. }
  19891. #endif
  19892. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19893. TEST_F(OpenStreamTest, Brotli) {
  19894. Client cli("127.0.0.1", port_);
  19895. auto handle =
  19896. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19897. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19898. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19899. }
  19900. #endif
  19901. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19902. TEST_F(OpenStreamTest, Zstd) {
  19903. Client cli("127.0.0.1", port_);
  19904. auto handle = cli.open_stream("GET", "/compressible", {},
  19905. {{"Accept-Encoding", "zstd"}});
  19906. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19907. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19908. }
  19909. #endif
  19910. #ifdef CPPHTTPLIB_SSL_ENABLED
  19911. class SSLOpenStreamTest : public ::testing::Test {
  19912. protected:
  19913. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19914. void SetUp() override {
  19915. svr_.Get("/hello", [](const Request &, Response &res) {
  19916. res.set_content("Hello SSL World!", "text/plain");
  19917. });
  19918. svr_.Get("/chunked", [](const Request &, Response &res) {
  19919. res.set_chunked_content_provider("text/plain",
  19920. [](size_t offset, DataSink &sink) {
  19921. if (offset < 15) {
  19922. sink.write("chunk", 5);
  19923. return true;
  19924. }
  19925. sink.done();
  19926. return true;
  19927. });
  19928. });
  19929. svr_.Post("/echo", [](const Request &req, Response &res) {
  19930. res.set_content(req.body, req.get_header_value("Content-Type"));
  19931. });
  19932. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19933. std::string body = req.body;
  19934. res.set_chunked_content_provider(
  19935. "text/plain", [body](size_t offset, DataSink &sink) {
  19936. if (offset < body.size()) {
  19937. sink.write(body.data() + offset, body.size() - offset);
  19938. }
  19939. sink.done();
  19940. return true;
  19941. });
  19942. });
  19943. port_ = svr_.bind_to_any_port("127.0.0.1");
  19944. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19945. svr_.wait_until_ready();
  19946. }
  19947. void TearDown() override {
  19948. svr_.stop();
  19949. if (thread_.joinable()) thread_.join();
  19950. }
  19951. SSLServer svr_;
  19952. std::thread thread_;
  19953. int port_ = 0;
  19954. };
  19955. TEST_F(SSLOpenStreamTest, Basic) {
  19956. SSLClient cli("127.0.0.1", port_);
  19957. cli.enable_server_certificate_verification(false);
  19958. auto handle = cli.open_stream("GET", "/hello");
  19959. ASSERT_TRUE(handle.is_valid());
  19960. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19961. }
  19962. TEST_F(SSLOpenStreamTest, Chunked) {
  19963. SSLClient cli("127.0.0.1", port_);
  19964. cli.enable_server_certificate_verification(false);
  19965. auto handle = cli.open_stream("GET", "/chunked");
  19966. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19967. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19968. "Transfer-Encoding") == "chunked");
  19969. auto body = read_all(handle);
  19970. EXPECT_EQ("chunkchunkchunk", body);
  19971. }
  19972. TEST_F(SSLOpenStreamTest, Post) {
  19973. SSLClient cli("127.0.0.1", port_);
  19974. cli.enable_server_certificate_verification(false);
  19975. auto handle =
  19976. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19977. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19978. EXPECT_EQ(200, handle.response->status);
  19979. auto body = read_all(handle);
  19980. EXPECT_EQ("Hello SSL POST", body);
  19981. }
  19982. TEST_F(SSLOpenStreamTest, PostChunked) {
  19983. SSLClient cli("127.0.0.1", port_);
  19984. cli.enable_server_certificate_verification(false);
  19985. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19986. "Chunked SSL Data", "text/plain");
  19987. ASSERT_TRUE(handle.is_valid());
  19988. EXPECT_EQ(200, handle.response->status);
  19989. auto body = read_all(handle);
  19990. EXPECT_EQ("Chunked SSL Data", body);
  19991. }
  19992. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19993. // Content-Length is terminated by the server closing the connection. When the
  19994. // SSL peer sends a close_notify after the body, the client must treat it as a
  19995. // clean EOF and return a successful response rather than an error.
  19996. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19998. ASSERT_TRUE(svr.is_valid());
  19999. svr.set_keep_alive_max_count(1);
  20000. const std::string expected_body = "Hello from connection-close response!";
  20001. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20002. res.set_content_provider("text/plain",
  20003. [&](size_t offset, DataSink &sink) -> bool {
  20004. if (offset < expected_body.size()) {
  20005. sink.write(expected_body.data() + offset,
  20006. expected_body.size() - offset);
  20007. }
  20008. sink.done();
  20009. return true;
  20010. });
  20011. });
  20012. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20013. auto se = detail::scope_exit([&] {
  20014. svr.stop();
  20015. listen_thread.join();
  20016. ASSERT_FALSE(svr.is_running());
  20017. });
  20018. svr.wait_until_ready();
  20019. SSLClient cli(HOST, PORT);
  20020. cli.enable_server_certificate_verification(false);
  20021. auto res = cli.Get("/no-content-length");
  20022. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20023. EXPECT_EQ(StatusCode::OK_200, res->status);
  20024. EXPECT_EQ(expected_body, res->body);
  20025. }
  20026. #endif // CPPHTTPLIB_SSL_ENABLED
  20027. //==============================================================================
  20028. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20029. // results for various scenarios.
  20030. //==============================================================================
  20031. TEST(ParityTest, GetVsOpenStream) {
  20032. Server svr;
  20033. const std::string path = "/parity";
  20034. const std::string content = "Parity test content: hello world";
  20035. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20036. res.set_content(content, "text/plain");
  20037. });
  20038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20039. auto se = detail::scope_exit([&] {
  20040. svr.stop();
  20041. t.join();
  20042. ASSERT_FALSE(svr.is_running());
  20043. });
  20044. svr.wait_until_ready();
  20045. Client cli(HOST, PORT);
  20046. // Non-stream path
  20047. auto r1 = cli.Get(path);
  20048. ASSERT_TRUE(r1);
  20049. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20050. // Stream path
  20051. auto h = cli.open_stream("GET", path);
  20052. ASSERT_TRUE(h.is_valid());
  20053. EXPECT_EQ(r1->body, read_all(h));
  20054. }
  20055. // Helper to compress data with provided compressor type T
  20056. template <typename Compressor>
  20057. static std::string compress_payload_for_parity(const std::string &in) {
  20058. std::string out;
  20059. Compressor compressor;
  20060. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20061. [&](const char *data, size_t n) {
  20062. out.append(data, n);
  20063. return true;
  20064. });
  20065. EXPECT_TRUE(ok);
  20066. return out;
  20067. }
  20068. // Helper function for compression parity tests
  20069. template <typename Compressor>
  20070. static void test_compression_parity(const std::string &original,
  20071. const std::string &path,
  20072. const std::string &encoding) {
  20073. const std::string compressed =
  20074. compress_payload_for_parity<Compressor>(original);
  20075. Server svr;
  20076. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20077. res.set_content(compressed, "application/octet-stream");
  20078. res.set_header("Content-Encoding", encoding);
  20079. });
  20080. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20081. auto se = detail::scope_exit([&] {
  20082. svr.stop();
  20083. t.join();
  20084. ASSERT_FALSE(svr.is_running());
  20085. });
  20086. svr.wait_until_ready();
  20087. Client cli(HOST, PORT);
  20088. // Non-streaming
  20089. {
  20090. auto res = cli.Get(path);
  20091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20092. EXPECT_EQ(StatusCode::OK_200, res->status);
  20093. EXPECT_EQ(original, res->body);
  20094. }
  20095. // Streaming
  20096. {
  20097. auto h = cli.open_stream("GET", path);
  20098. ASSERT_TRUE(h.is_valid());
  20099. EXPECT_EQ(original, read_all(h));
  20100. }
  20101. }
  20102. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20103. TEST(ParityTest, Gzip) {
  20104. test_compression_parity<detail::gzip_compressor>(
  20105. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20106. }
  20107. #endif
  20108. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20109. TEST(ParityTest, Brotli) {
  20110. test_compression_parity<detail::brotli_compressor>(
  20111. "Hello, brotli parity test payload", "/parity-br", "br");
  20112. }
  20113. #endif
  20114. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20115. TEST(ParityTest, Zstd) {
  20116. test_compression_parity<detail::zstd_compressor>(
  20117. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20118. }
  20119. #endif
  20120. //==============================================================================
  20121. // New Stream API Tests
  20122. //==============================================================================
  20123. inline std::string read_body(httplib::stream::Result &result) {
  20124. std::string body;
  20125. while (result.next()) {
  20126. body.append(result.data(), result.size());
  20127. }
  20128. return body;
  20129. }
  20130. TEST(ClientConnectionTest, Basic) {
  20131. httplib::ClientConnection conn;
  20132. EXPECT_FALSE(conn.is_open());
  20133. conn.sock = 1;
  20134. EXPECT_TRUE(conn.is_open());
  20135. httplib::ClientConnection conn2(std::move(conn));
  20136. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20137. conn2.sock = INVALID_SOCKET;
  20138. }
  20139. // Unified test server for all stream::* tests
  20140. class StreamApiTest : public ::testing::Test {
  20141. protected:
  20142. void SetUp() override {
  20143. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20144. res.set_content("Hello World!", "text/plain");
  20145. });
  20146. svr_.Get("/echo-params",
  20147. [](const httplib::Request &req, httplib::Response &res) {
  20148. std::string r;
  20149. for (const auto &p : req.params) {
  20150. if (!r.empty()) r += "&";
  20151. r += p.first + "=" + p.second;
  20152. }
  20153. res.set_content(r, "text/plain");
  20154. });
  20155. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20156. res.set_content(req.body, req.get_header_value("Content-Type"));
  20157. });
  20158. svr_.Post("/echo-headers",
  20159. [](const httplib::Request &req, httplib::Response &res) {
  20160. std::string r;
  20161. for (const auto &h : req.headers)
  20162. r += h.first + ": " + h.second + "\n";
  20163. res.set_content(r, "text/plain");
  20164. });
  20165. svr_.Post("/echo-params",
  20166. [](const httplib::Request &req, httplib::Response &res) {
  20167. std::string r = "params:";
  20168. for (const auto &p : req.params)
  20169. r += p.first + "=" + p.second + ";";
  20170. res.set_content(r + " body:" + req.body, "text/plain");
  20171. });
  20172. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20173. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20174. });
  20175. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20176. res.set_content("PUT:" + req.body, "text/plain");
  20177. });
  20178. svr_.Patch("/echo",
  20179. [](const httplib::Request &req, httplib::Response &res) {
  20180. res.set_content("PATCH:" + req.body, "text/plain");
  20181. });
  20182. svr_.Delete(
  20183. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20184. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20185. "text/plain");
  20186. });
  20187. svr_.Get("/head-test",
  20188. [](const httplib::Request &, httplib::Response &res) {
  20189. res.set_content("body for HEAD", "text/plain");
  20190. });
  20191. svr_.Options("/options",
  20192. [](const httplib::Request &, httplib::Response &res) {
  20193. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20194. });
  20195. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20196. svr_.wait_until_ready();
  20197. }
  20198. void TearDown() override {
  20199. svr_.stop();
  20200. if (thread_.joinable()) thread_.join();
  20201. }
  20202. httplib::Server svr_;
  20203. std::thread thread_;
  20204. };
  20205. // stream::Get tests
  20206. TEST_F(StreamApiTest, GetBasic) {
  20207. httplib::Client cli(HOST, PORT);
  20208. auto result = httplib::stream::Get(cli, "/hello");
  20209. ASSERT_TRUE(result.is_valid());
  20210. EXPECT_EQ(200, result.status());
  20211. EXPECT_EQ("Hello World!", read_body(result));
  20212. }
  20213. TEST_F(StreamApiTest, GetWithParams) {
  20214. httplib::Client cli(HOST, PORT);
  20215. httplib::Params params{{"foo", "bar"}};
  20216. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20217. ASSERT_TRUE(result.is_valid());
  20218. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20219. }
  20220. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20221. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20222. httplib::Client cli(HOST, PORT);
  20223. cli.set_payload_max_length(0);
  20224. auto result = httplib::stream::Get(cli, "/hello");
  20225. ASSERT_TRUE(result.is_valid());
  20226. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20227. EXPECT_EQ("Hello World!", read_body(result));
  20228. }
  20229. #endif
  20230. TEST_F(StreamApiTest, GetConnectionError) {
  20231. httplib::Client cli(HOST, 9999);
  20232. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20233. }
  20234. TEST_F(StreamApiTest, Get404) {
  20235. httplib::Client cli(HOST, PORT);
  20236. auto result = httplib::stream::Get(cli, "/nonexistent");
  20237. EXPECT_TRUE(result.is_valid());
  20238. EXPECT_EQ(404, result.status());
  20239. }
  20240. // stream::Post tests
  20241. TEST_F(StreamApiTest, PostBasic) {
  20242. httplib::Client cli(HOST, PORT);
  20243. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20244. "application/json");
  20245. ASSERT_TRUE(result.is_valid());
  20246. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20247. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20248. }
  20249. TEST_F(StreamApiTest, PostWithHeaders) {
  20250. httplib::Client cli(HOST, PORT);
  20251. httplib::Headers headers{{"X-Custom", "value"}};
  20252. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20253. "text/plain");
  20254. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20255. }
  20256. TEST_F(StreamApiTest, PostWithParams) {
  20257. httplib::Client cli(HOST, PORT);
  20258. httplib::Params params{{"k", "v"}};
  20259. auto result =
  20260. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20261. auto body = read_body(result);
  20262. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20263. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20264. }
  20265. TEST_F(StreamApiTest, PostLarge) {
  20266. httplib::Client cli(HOST, PORT);
  20267. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20268. size_t total = 0;
  20269. while (result.next()) {
  20270. total += result.size();
  20271. }
  20272. EXPECT_EQ(100u * 1024u, total);
  20273. }
  20274. // stream::Put/Patch tests
  20275. TEST_F(StreamApiTest, PutAndPatch) {
  20276. httplib::Client cli(HOST, PORT);
  20277. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20278. EXPECT_EQ("PUT:test", read_body(put));
  20279. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20280. EXPECT_EQ("PATCH:test", read_body(patch));
  20281. }
  20282. // stream::Delete tests
  20283. TEST_F(StreamApiTest, Delete) {
  20284. httplib::Client cli(HOST, PORT);
  20285. auto del1 = httplib::stream::Delete(cli, "/resource");
  20286. EXPECT_EQ("Deleted", read_body(del1));
  20287. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20288. EXPECT_EQ("Deleted:data", read_body(del2));
  20289. }
  20290. // stream::Head/Options tests
  20291. TEST_F(StreamApiTest, HeadAndOptions) {
  20292. httplib::Client cli(HOST, PORT);
  20293. auto head = httplib::stream::Head(cli, "/head-test");
  20294. EXPECT_TRUE(head.is_valid());
  20295. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20296. auto opts = httplib::stream::Options(cli, "/options");
  20297. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20298. }
  20299. // SSL stream::* tests
  20300. #ifdef CPPHTTPLIB_SSL_ENABLED
  20301. class SSLStreamApiTest : public ::testing::Test {
  20302. protected:
  20303. void SetUp() override {
  20304. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20305. res.set_content("Hello SSL!", "text/plain");
  20306. });
  20307. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20308. res.set_content(req.body, "text/plain");
  20309. });
  20310. port_ = svr_.bind_to_any_port("127.0.0.1");
  20311. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20312. svr_.wait_until_ready();
  20313. }
  20314. void TearDown() override {
  20315. svr_.stop();
  20316. if (thread_.joinable()) thread_.join();
  20317. }
  20318. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20319. std::thread thread_;
  20320. int port_ = 0;
  20321. };
  20322. TEST_F(SSLStreamApiTest, GetAndPost) {
  20323. httplib::SSLClient cli("127.0.0.1", port_);
  20324. cli.enable_server_certificate_verification(false);
  20325. auto get = httplib::stream::Get(cli, "/hello");
  20326. EXPECT_EQ("Hello SSL!", read_body(get));
  20327. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20328. EXPECT_EQ("test", read_body(post));
  20329. }
  20330. #endif
  20331. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20332. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20333. // BodyReader
  20334. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20335. // Test that read timeout during streaming is detected
  20336. // Use a large content-length response where server delays mid-stream
  20337. Server svr;
  20338. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20339. // Send a large response with delay in the middle
  20340. res.set_content_provider(
  20341. 1000, // content_length
  20342. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20343. if (offset < 100) {
  20344. // Send first 100 bytes immediately
  20345. std::string data(100, 'A');
  20346. sink.write(data.c_str(), data.size());
  20347. return true;
  20348. }
  20349. // Then delay longer than client timeout
  20350. std::this_thread::sleep_for(std::chrono::seconds(3));
  20351. std::string data(900, 'B');
  20352. sink.write(data.c_str(), data.size());
  20353. return true;
  20354. });
  20355. });
  20356. auto port = 8091;
  20357. std::thread t([&]() { svr.listen("localhost", port); });
  20358. svr.wait_until_ready();
  20359. Client cli("localhost", port);
  20360. cli.set_read_timeout(1, 0); // 1 second timeout
  20361. auto handle = cli.open_stream("GET", "/slow-stream");
  20362. ASSERT_TRUE(handle.is_valid());
  20363. char buf[256];
  20364. ssize_t total = 0;
  20365. ssize_t n;
  20366. bool got_error = false;
  20367. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20368. total += n;
  20369. }
  20370. if (n < 0) {
  20371. got_error = true;
  20372. // Should be timeout or read error
  20373. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20374. handle.get_read_error() == Error::Read)
  20375. << "Actual error: " << to_string(handle.get_read_error());
  20376. }
  20377. // Either we got an error, or we got less data than expected
  20378. EXPECT_TRUE(got_error || total < 1000)
  20379. << "Expected timeout but got all " << total << " bytes";
  20380. svr.stop();
  20381. t.join();
  20382. }
  20383. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20384. // Test connection closed detection via BodyReader
  20385. Server svr;
  20386. std::atomic<bool> close_now{false};
  20387. svr.Get("/will-close", [&](const Request &, Response &res) {
  20388. res.set_content_provider(
  20389. 10000, // Large content_length that we won't fully send
  20390. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20391. if (offset < 100) {
  20392. std::string data(100, 'X');
  20393. sink.write(data.c_str(), data.size());
  20394. return true;
  20395. }
  20396. // Wait for signal then abort
  20397. while (!close_now) {
  20398. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20399. }
  20400. return false; // Abort - server will close connection
  20401. });
  20402. });
  20403. auto port = 8092;
  20404. std::thread t([&]() { svr.listen("localhost", port); });
  20405. svr.wait_until_ready();
  20406. Client cli("localhost", port);
  20407. auto handle = cli.open_stream("GET", "/will-close");
  20408. ASSERT_TRUE(handle.is_valid());
  20409. char buf[256];
  20410. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20411. EXPECT_GT(n, 0) << "First read should succeed";
  20412. // Signal server to close
  20413. close_now = true;
  20414. // Keep reading until error or EOF
  20415. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20416. // Keep reading
  20417. }
  20418. // Should get an error since content_length wasn't satisfied
  20419. if (n < 0) {
  20420. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20421. handle.get_read_error() == Error::Read)
  20422. << "Actual error: " << to_string(handle.get_read_error());
  20423. }
  20424. svr.stop();
  20425. t.join();
  20426. }
  20427. #ifdef CPPHTTPLIB_SSL_ENABLED
  20428. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20429. // Test that read timeout during SSL streaming is detected
  20430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20431. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20432. res.set_content_provider(
  20433. 1000, "text/plain",
  20434. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20435. if (offset < 100) {
  20436. std::string data(100, 'A');
  20437. sink.write(data.c_str(), data.size());
  20438. return true;
  20439. }
  20440. std::this_thread::sleep_for(std::chrono::seconds(3));
  20441. std::string data(900, 'B');
  20442. sink.write(data.c_str(), data.size());
  20443. return true;
  20444. });
  20445. });
  20446. auto port = 8093;
  20447. std::thread t([&]() { svr.listen("localhost", port); });
  20448. svr.wait_until_ready();
  20449. SSLClient cli("localhost", port);
  20450. cli.enable_server_certificate_verification(false);
  20451. cli.set_read_timeout(1, 0); // 1 second timeout
  20452. auto handle = cli.open_stream("GET", "/slow-stream");
  20453. ASSERT_TRUE(handle.is_valid());
  20454. char buf[256];
  20455. ssize_t total = 0;
  20456. ssize_t n;
  20457. bool got_error = false;
  20458. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20459. total += n;
  20460. }
  20461. if (n < 0) {
  20462. got_error = true;
  20463. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20464. handle.get_read_error() == Error::Read)
  20465. << "Actual error: " << to_string(handle.get_read_error());
  20466. }
  20467. EXPECT_TRUE(got_error || total < 1000)
  20468. << "Expected timeout but got all " << total << " bytes";
  20469. svr.stop();
  20470. t.join();
  20471. }
  20472. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20473. // Test SSL connection closed detection
  20474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20475. std::atomic<bool> close_now{false};
  20476. svr.Get("/will-close", [&](const Request &, Response &res) {
  20477. res.set_content_provider(
  20478. 10000, "text/plain",
  20479. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20480. if (offset < 100) {
  20481. std::string data(100, 'X');
  20482. sink.write(data.c_str(), data.size());
  20483. return true;
  20484. }
  20485. while (!close_now) {
  20486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20487. }
  20488. return false;
  20489. });
  20490. });
  20491. auto port = 8094;
  20492. std::thread t([&]() { svr.listen("localhost", port); });
  20493. svr.wait_until_ready();
  20494. SSLClient cli("localhost", port);
  20495. cli.enable_server_certificate_verification(false);
  20496. auto handle = cli.open_stream("GET", "/will-close");
  20497. ASSERT_TRUE(handle.is_valid());
  20498. char buf[256];
  20499. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20500. EXPECT_GT(n, 0);
  20501. // Signal server to close
  20502. close_now = true;
  20503. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20504. // Keep reading
  20505. }
  20506. if (n < 0) {
  20507. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20508. handle.get_read_error() == Error::Read)
  20509. << "Actual error: " << to_string(handle.get_read_error());
  20510. }
  20511. svr.stop();
  20512. t.join();
  20513. }
  20514. #endif
  20515. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20516. using namespace httplib;
  20517. // Create a test file
  20518. const char *fname = "etag_testfile.txt";
  20519. const char *content = "etag-content";
  20520. {
  20521. std::ofstream ofs(fname);
  20522. ofs << content;
  20523. ASSERT_TRUE(ofs.good());
  20524. }
  20525. Server svr;
  20526. svr.set_mount_point("/static", ".");
  20527. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20528. svr.wait_until_ready();
  20529. Client cli(HOST, PORT);
  20530. // First request: should get 200 with ETag header
  20531. auto res1 = cli.Get("/static/etag_testfile.txt");
  20532. ASSERT_TRUE(res1);
  20533. ASSERT_EQ(200, res1->status);
  20534. ASSERT_TRUE(res1->has_header("ETag"));
  20535. std::string etag = res1->get_header_value("ETag");
  20536. EXPECT_FALSE(etag.empty());
  20537. // Verify ETag format: W/"hex-hex"
  20538. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20539. EXPECT_EQ('W', etag[0]);
  20540. EXPECT_EQ('/', etag[1]);
  20541. EXPECT_EQ('"', etag[2]);
  20542. EXPECT_EQ('"', etag.back());
  20543. // Exact match: expect 304 Not Modified
  20544. Headers h2 = {{"If-None-Match", etag}};
  20545. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20546. ASSERT_TRUE(res2);
  20547. EXPECT_EQ(304, res2->status);
  20548. // Wildcard match: expect 304 Not Modified
  20549. Headers h3 = {{"If-None-Match", "*"}};
  20550. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20551. ASSERT_TRUE(res3);
  20552. EXPECT_EQ(304, res3->status);
  20553. // Non-matching ETag: expect 200
  20554. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20555. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20556. ASSERT_TRUE(res4);
  20557. EXPECT_EQ(200, res4->status);
  20558. // Multiple ETags with one matching: expect 304
  20559. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20560. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20561. ASSERT_TRUE(res5);
  20562. EXPECT_EQ(304, res5->status);
  20563. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20564. // that equivalent to the single comma-separated list above, so the match on
  20565. // the second line must still be found.
  20566. Headers h6;
  20567. h6.emplace("If-None-Match", "W/\"other\"");
  20568. h6.emplace("If-None-Match", etag);
  20569. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20570. ASSERT_TRUE(res6);
  20571. EXPECT_EQ(304, res6->status);
  20572. svr.stop();
  20573. t.join();
  20574. std::remove(fname);
  20575. }
  20576. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20577. using namespace httplib;
  20578. Server svr;
  20579. svr.set_mount_point("/static", ".");
  20580. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20581. svr.wait_until_ready();
  20582. Client cli(HOST, PORT);
  20583. // Send If-None-Match: * to a non-existent file
  20584. Headers h = {{"If-None-Match", "*"}};
  20585. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20587. EXPECT_EQ(404, res->status);
  20588. svr.stop();
  20589. t.join();
  20590. }
  20591. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20592. using namespace httplib;
  20593. // Create a test file
  20594. const char *fname = "etag_boundary_testfile.txt";
  20595. const char *content = "boundary-test";
  20596. {
  20597. std::ofstream ofs(fname);
  20598. ofs << content;
  20599. ASSERT_TRUE(ofs.good());
  20600. }
  20601. Server svr;
  20602. svr.set_mount_point("/static", ".");
  20603. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20604. svr.wait_until_ready();
  20605. Client cli(HOST, PORT);
  20606. // Get the actual ETag
  20607. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20608. ASSERT_TRUE(res1);
  20609. ASSERT_EQ(200, res1->status);
  20610. ASSERT_TRUE(res1->has_header("ETag"));
  20611. std::string etag = res1->get_header_value("ETag");
  20612. // Test 1: Very long ETag value (longer than actual ETag)
  20613. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20614. Headers h1 = {{"If-None-Match", "W/"
  20615. "\"very-long-etag-value-that-is-much-longer-"
  20616. "than-the-actual-etag-value\""}};
  20617. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20618. ASSERT_TRUE(res2);
  20619. EXPECT_EQ(200, res2->status); // Should not match
  20620. // Test 2: Long string followed by wildcard
  20621. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20622. // string)
  20623. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20624. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20625. ASSERT_TRUE(res3);
  20626. EXPECT_EQ(304, res3->status); // Should match on "*"
  20627. // Test 3: Wildcard followed by long string
  20628. // Should match on "*" immediately and return 304
  20629. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20630. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20631. ASSERT_TRUE(res4);
  20632. EXPECT_EQ(304, res4->status); // Should match on "*"
  20633. // Test 4: Multiple long non-matching values
  20634. // Should NOT match and return 200 (test that all comparisons are safe)
  20635. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20636. "W/\"second-long-non-matching-value\", "
  20637. "W/\"third-long-non-matching-value\""}};
  20638. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20639. ASSERT_TRUE(res5);
  20640. EXPECT_EQ(200, res5->status); // Should not match
  20641. // Test 5: Single character that is not "*" (edge case)
  20642. Headers h5 = {{"If-None-Match", "X"}};
  20643. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20644. ASSERT_TRUE(res6);
  20645. EXPECT_EQ(200, res6->status); // Should not match
  20646. svr.stop();
  20647. t.join();
  20648. std::remove(fname);
  20649. }
  20650. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20651. using namespace httplib;
  20652. // Create a test file
  20653. const char *fname = "ims_testfile.txt";
  20654. const char *content = "if-modified-since-test";
  20655. {
  20656. std::ofstream ofs(fname);
  20657. ofs << content;
  20658. ASSERT_TRUE(ofs.good());
  20659. }
  20660. Server svr;
  20661. svr.set_mount_point("/static", ".");
  20662. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20663. svr.wait_until_ready();
  20664. Client cli(HOST, PORT);
  20665. // First request: should get 200 with Last-Modified header
  20666. auto res1 = cli.Get("/static/ims_testfile.txt");
  20667. ASSERT_TRUE(res1);
  20668. ASSERT_EQ(200, res1->status);
  20669. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20670. std::string last_modified = res1->get_header_value("Last-Modified");
  20671. EXPECT_FALSE(last_modified.empty());
  20672. // If-Modified-Since with same time: expect 304
  20673. Headers h2 = {{"If-Modified-Since", last_modified}};
  20674. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20675. ASSERT_TRUE(res2);
  20676. EXPECT_EQ(304, res2->status);
  20677. // If-Modified-Since with future time: expect 304
  20678. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20679. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20680. ASSERT_TRUE(res3);
  20681. EXPECT_EQ(304, res3->status);
  20682. // If-Modified-Since with past time: expect 200
  20683. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20684. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20685. ASSERT_TRUE(res4);
  20686. EXPECT_EQ(200, res4->status);
  20687. // If-None-Match takes precedence over If-Modified-Since
  20688. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20689. ASSERT_TRUE(res1->has_header("ETag"));
  20690. std::string etag = res1->get_header_value("ETag");
  20691. Headers h5 = {{"If-None-Match", etag},
  20692. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20693. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20694. ASSERT_TRUE(res5);
  20695. EXPECT_EQ(304, res5->status);
  20696. svr.stop();
  20697. t.join();
  20698. std::remove(fname);
  20699. }
  20700. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20701. using namespace httplib;
  20702. Server svr;
  20703. // Endpoint that returns compressible content
  20704. svr.Get("/compressible", [](const Request &, Response &res) {
  20705. // Return a large enough body to trigger compression
  20706. std::string body(1000, 'a');
  20707. res.set_content(body, "text/plain");
  20708. });
  20709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20710. svr.wait_until_ready();
  20711. Client cli(HOST, PORT);
  20712. // Request with gzip support: should get Vary header when compressed
  20713. cli.set_compress(true);
  20714. auto res1 = cli.Get("/compressible");
  20715. ASSERT_TRUE(res1);
  20716. EXPECT_EQ(200, res1->status);
  20717. // If Content-Encoding is set, Vary should also be set
  20718. if (res1->has_header("Content-Encoding")) {
  20719. EXPECT_TRUE(res1->has_header("Vary"));
  20720. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20721. }
  20722. // Request without Accept-Encoding header: should not have compression
  20723. Headers h_no_compress;
  20724. auto res2 = cli.Get("/compressible", h_no_compress);
  20725. ASSERT_TRUE(res2);
  20726. EXPECT_EQ(200, res2->status);
  20727. // Verify Vary header is present when compression is applied
  20728. // (the exact behavior depends on server configuration)
  20729. svr.stop();
  20730. t.join();
  20731. }
  20732. TEST(ETagTest, IfRangeWithETag) {
  20733. using namespace httplib;
  20734. // Create a test file with known content
  20735. const char *fname = "if_range_testfile.txt";
  20736. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20737. {
  20738. std::ofstream ofs(fname);
  20739. ofs << content;
  20740. ASSERT_TRUE(ofs.good());
  20741. }
  20742. Server svr;
  20743. svr.set_mount_point("/static", ".");
  20744. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20745. svr.wait_until_ready();
  20746. Client cli(HOST, PORT);
  20747. // First request: get ETag
  20748. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20749. ASSERT_TRUE(res1);
  20750. ASSERT_EQ(200, res1->status);
  20751. ASSERT_TRUE(res1->has_header("ETag"));
  20752. std::string etag = res1->get_header_value("ETag");
  20753. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20754. // Since our server generates weak ETags (W/"..."), If-Range with our
  20755. // ETag should NOT result in partial content - it should return full content.
  20756. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20757. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20758. ASSERT_TRUE(res2);
  20759. // Weak ETag in If-Range -> full content (200), not partial (206)
  20760. EXPECT_EQ(200, res2->status);
  20761. EXPECT_EQ(content, res2->body);
  20762. EXPECT_FALSE(res2->has_header("Content-Range"));
  20763. // Range request with non-matching If-Range (ETag): should get 200 (full
  20764. // content)
  20765. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20766. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20767. ASSERT_TRUE(res3);
  20768. EXPECT_EQ(200, res3->status);
  20769. EXPECT_EQ(content, res3->body);
  20770. EXPECT_FALSE(res3->has_header("Content-Range"));
  20771. // Range request with strong ETag (hypothetical - our server doesn't generate
  20772. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20773. // should return full content)
  20774. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20775. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20776. ASSERT_TRUE(res4);
  20777. EXPECT_EQ(200, res4->status);
  20778. EXPECT_EQ(content, res4->body);
  20779. EXPECT_FALSE(res4->has_header("Content-Range"));
  20780. svr.stop();
  20781. t.join();
  20782. std::remove(fname);
  20783. }
  20784. TEST(ETagTest, IfRangeWithDate) {
  20785. using namespace httplib;
  20786. // Create a test file
  20787. const char *fname = "if_range_date_testfile.txt";
  20788. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20789. {
  20790. std::ofstream ofs(fname);
  20791. ofs << content;
  20792. ASSERT_TRUE(ofs.good());
  20793. }
  20794. Server svr;
  20795. svr.set_mount_point("/static", ".");
  20796. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20797. svr.wait_until_ready();
  20798. Client cli(HOST, PORT);
  20799. // First request: get Last-Modified
  20800. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20801. ASSERT_TRUE(res1);
  20802. ASSERT_EQ(200, res1->status);
  20803. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20804. std::string last_modified = res1->get_header_value("Last-Modified");
  20805. // Range request with matching If-Range (date): should get 206
  20806. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20807. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20808. ASSERT_TRUE(res2);
  20809. EXPECT_EQ(206, res2->status);
  20810. EXPECT_EQ("FGHIJ", res2->body);
  20811. // Range request with old If-Range date: should get 200 (full content)
  20812. Headers h3 = {{"Range", "bytes=5-9"},
  20813. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20814. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20815. ASSERT_TRUE(res3);
  20816. EXPECT_EQ(200, res3->status);
  20817. EXPECT_EQ(content, res3->body);
  20818. // Range request with future If-Range date: should get 206
  20819. Headers h4 = {{"Range", "bytes=0-4"},
  20820. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20821. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20822. ASSERT_TRUE(res4);
  20823. EXPECT_EQ(206, res4->status);
  20824. EXPECT_EQ("ABCDE", res4->body);
  20825. svr.stop();
  20826. t.join();
  20827. std::remove(fname);
  20828. }
  20829. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20830. using namespace httplib;
  20831. const char *fname = "etag_malformed.txt";
  20832. const char *content = "malformed-etag";
  20833. {
  20834. std::ofstream ofs(fname);
  20835. ofs << content;
  20836. ASSERT_TRUE(ofs.good());
  20837. }
  20838. Server svr;
  20839. svr.set_mount_point("/static", ".");
  20840. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20841. svr.wait_until_ready();
  20842. Client cli(HOST, PORT);
  20843. // baseline: should get 200 and an ETag
  20844. auto res1 = cli.Get("/static/etag_malformed.txt");
  20845. ASSERT_TRUE(res1);
  20846. ASSERT_EQ(200, res1->status);
  20847. ASSERT_TRUE(res1->has_header("ETag"));
  20848. // Malformed ETag value (missing quotes) should be treated as non-matching
  20849. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20850. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20851. ASSERT_TRUE(res_bad);
  20852. EXPECT_EQ(200, res_bad->status);
  20853. // Whitespace-only header value should be considered invalid / non-matching
  20854. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20855. "Host: localhost\r\n"
  20856. "If-None-Match: \r\n"
  20857. "Connection: close\r\n"
  20858. "\r\n";
  20859. std::string out;
  20860. ASSERT_TRUE(send_request(5, raw_req, &out));
  20861. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20862. svr.stop();
  20863. t.join();
  20864. std::remove(fname);
  20865. }
  20866. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20867. using namespace httplib;
  20868. const char *fname = "ims_invalid_format.txt";
  20869. const char *content = "ims-bad-format";
  20870. {
  20871. std::ofstream ofs(fname);
  20872. ofs << content;
  20873. ASSERT_TRUE(ofs.good());
  20874. }
  20875. Server svr;
  20876. svr.set_mount_point("/static", ".");
  20877. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20878. svr.wait_until_ready();
  20879. Client cli(HOST, PORT);
  20880. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20881. ASSERT_TRUE(res1);
  20882. ASSERT_EQ(200, res1->status);
  20883. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20884. // If-Modified-Since with invalid format should not result in 304
  20885. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20886. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20887. ASSERT_TRUE(res_bad);
  20888. EXPECT_EQ(200, res_bad->status);
  20889. // If-Range with invalid date format should be treated as mismatch -> full
  20890. // content (200)
  20891. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20892. {"If-Range", "invalid-date"}};
  20893. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20894. ASSERT_TRUE(res_ifrange);
  20895. EXPECT_EQ(200, res_ifrange->status);
  20896. svr.stop();
  20897. t.join();
  20898. std::remove(fname);
  20899. }
  20900. TEST(ETagTest, IfRangeWithMalformedETag) {
  20901. using namespace httplib;
  20902. const char *fname = "ifrange_malformed.txt";
  20903. const std::string content = "0123456789";
  20904. {
  20905. std::ofstream ofs(fname);
  20906. ofs << content;
  20907. ASSERT_TRUE(ofs.good());
  20908. }
  20909. Server svr;
  20910. svr.set_mount_point("/static", ".");
  20911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20912. svr.wait_until_ready();
  20913. Client cli(HOST, PORT);
  20914. // First request: get ETag
  20915. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20916. ASSERT_TRUE(res1);
  20917. ASSERT_EQ(200, res1->status);
  20918. ASSERT_TRUE(res1->has_header("ETag"));
  20919. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20920. // full content (200)
  20921. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20922. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20923. ASSERT_TRUE(res2);
  20924. EXPECT_EQ(200, res2->status);
  20925. EXPECT_EQ(content, res2->body);
  20926. svr.stop();
  20927. t.join();
  20928. std::remove(fname);
  20929. }
  20930. TEST(ETagTest, ExtremeLargeDateValues) {
  20931. using namespace httplib;
  20932. const char *fname = "ims_extreme_date.txt";
  20933. const char *content = "ims-extreme-date";
  20934. {
  20935. std::ofstream ofs(fname);
  20936. ofs << content;
  20937. ASSERT_TRUE(ofs.good());
  20938. }
  20939. Server svr;
  20940. svr.set_mount_point("/static", ".");
  20941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20942. svr.wait_until_ready();
  20943. Client cli(HOST, PORT);
  20944. auto res1 = cli.Get(std::string("/static/") + fname);
  20945. ASSERT_TRUE(res1);
  20946. ASSERT_EQ(200, res1->status);
  20947. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20948. // Extremely large year that may overflow date parsing routines.
  20949. Headers h_large_date = {
  20950. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20951. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20952. ASSERT_TRUE(res_bad);
  20953. // Expect server to treat this as invalid/mismatch and return full content
  20954. EXPECT_EQ(200, res_bad->status);
  20955. // If-Range with extremely large date should be treated as mismatch -> full
  20956. // content (200)
  20957. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20958. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20959. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20960. ASSERT_TRUE(res_ifrange);
  20961. EXPECT_EQ(200, res_ifrange->status);
  20962. svr.stop();
  20963. t.join();
  20964. std::remove(fname);
  20965. }
  20966. TEST(ETagTest, NegativeFileModificationTime) {
  20967. using namespace httplib;
  20968. const char *fname = "ims_negative_mtime.txt";
  20969. const std::string content = "negative-mtime";
  20970. {
  20971. std::ofstream ofs(fname);
  20972. ofs << content;
  20973. ASSERT_TRUE(ofs.good());
  20974. }
  20975. // Try to set file mtime to a negative value. This may fail on some
  20976. // platforms/filesystems; if it fails, the test will still verify server
  20977. // behaves safely by performing a regular conditional request.
  20978. #if defined(__APPLE__) || defined(__linux__)
  20979. bool set_negative = false;
  20980. do {
  20981. struct timeval times[2];
  20982. // access time: now
  20983. times[0].tv_sec = time(nullptr);
  20984. times[0].tv_usec = 0;
  20985. // modification time: negative (e.g., -1)
  20986. times[1].tv_sec = -1;
  20987. times[1].tv_usec = 0;
  20988. if (utimes(fname, times) == 0) { set_negative = true; }
  20989. } while (0);
  20990. #else
  20991. bool set_negative = false;
  20992. #endif
  20993. Server svr;
  20994. svr.set_mount_point("/static", ".");
  20995. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20996. svr.wait_until_ready();
  20997. Client cli(HOST, PORT);
  20998. auto res1 = cli.Get(std::string("/static/") + fname);
  20999. ASSERT_TRUE(res1);
  21000. ASSERT_EQ(200, res1->status);
  21001. bool has_last_modified = res1->has_header("Last-Modified");
  21002. std::string last_modified;
  21003. if (has_last_modified) {
  21004. last_modified = res1->get_header_value("Last-Modified");
  21005. }
  21006. if (set_negative) {
  21007. // If we successfully set a negative mtime, ensure server returns a
  21008. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21009. // with an old date and ensure server handles it without crash.
  21010. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21011. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21012. ASSERT_TRUE(res2);
  21013. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21014. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21015. } else {
  21016. // Could not set negative mtime on this platform; fall back to verifying
  21017. // that normal invalid/malformed dates are treated safely (non-304).
  21018. Headers h_bad_date = {
  21019. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21020. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21021. ASSERT_TRUE(res_bad);
  21022. EXPECT_EQ(200, res_bad->status);
  21023. }
  21024. svr.stop();
  21025. t.join();
  21026. std::remove(fname);
  21027. }
  21028. //==============================================================================
  21029. // Integration Tests with Server
  21030. //==============================================================================
  21031. class SSEIntegrationTest : public ::testing::Test {
  21032. protected:
  21033. void SetUp() override {
  21034. stop_server_.store(false);
  21035. events_.clear();
  21036. server_ = httplib::detail::make_unique<Server>();
  21037. setup_server();
  21038. start_server();
  21039. }
  21040. void TearDown() override {
  21041. stop_server_.store(true);
  21042. event_cv_.notify_all();
  21043. server_->stop();
  21044. if (server_thread_.joinable()) { server_thread_.join(); }
  21045. }
  21046. void setup_server() {
  21047. // Simple SSE endpoint
  21048. server_->Get("/events", [this](const Request &req, Response &res) {
  21049. auto last_id = req.get_header_value("Last-Event-ID");
  21050. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21051. res.set_chunked_content_provider(
  21052. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21053. std::unique_lock<std::mutex> lock(event_mutex_);
  21054. if (event_cv_.wait_for(
  21055. lock, std::chrono::milliseconds(200), [this] {
  21056. return !events_.empty() || stop_server_.load();
  21057. })) {
  21058. if (stop_server_.load()) { return false; }
  21059. if (!events_.empty()) {
  21060. std::string event = events_.front();
  21061. events_.erase(events_.begin());
  21062. sink.write(event.data(), event.size());
  21063. return true;
  21064. }
  21065. }
  21066. return !stop_server_.load();
  21067. });
  21068. });
  21069. // Endpoint that returns error
  21070. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21071. res.status = 500;
  21072. res.set_content("Internal Server Error", "text/plain");
  21073. });
  21074. // Endpoint for custom event types
  21075. server_->Get("/custom-events", [](const Request &, Response &res) {
  21076. res.set_chunked_content_provider(
  21077. "text/event-stream", [](size_t offset, DataSink &sink) {
  21078. if (offset == 0) {
  21079. std::string event = "event: update\ndata: updated\n\n"
  21080. "event: delete\ndata: deleted\n\n";
  21081. sink.write(event.data(), event.size());
  21082. }
  21083. return false; // End stream after sending
  21084. });
  21085. });
  21086. }
  21087. void start_server() {
  21088. port_ = server_->bind_to_any_port(HOST);
  21089. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21090. // Wait for server to start
  21091. while (!server_->is_running()) {
  21092. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21093. }
  21094. }
  21095. int get_port() const { return port_; }
  21096. void send_event(const std::string &event) {
  21097. std::lock_guard<std::mutex> lock(event_mutex_);
  21098. events_.push_back(event);
  21099. event_cv_.notify_all();
  21100. }
  21101. std::unique_ptr<Server> server_;
  21102. std::thread server_thread_;
  21103. std::mutex event_mutex_;
  21104. std::condition_variable event_cv_;
  21105. std::vector<std::string> events_;
  21106. std::atomic<bool> stop_server_{false};
  21107. std::string last_received_event_id_;
  21108. int port_ = 0;
  21109. };
  21110. //==============================================================================
  21111. // SSE Parsing Tests
  21112. //==============================================================================
  21113. class SSEParsingTest : public SSEIntegrationTest {
  21114. protected:
  21115. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21116. // A trailing sentinel event tells when the whole stream has been parsed.
  21117. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21118. auto body = stream + "event: end\ndata: end\n\n";
  21119. server_->Get("/parse", [body](const Request &, Response &res) {
  21120. res.set_content(body, "text/event-stream");
  21121. });
  21122. return collect("/parse");
  21123. }
  21124. // Runs SSEClient against path until an "end" event arrives and returns the
  21125. // messages dispatched before it
  21126. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21127. Client client(HOST, get_port());
  21128. sse::SSEClient sse(client, path);
  21129. std::mutex mutex;
  21130. std::condition_variable cv;
  21131. std::vector<sse::SSEMessage> messages;
  21132. auto done = false;
  21133. sse.on_message([&](const sse::SSEMessage &msg) {
  21134. std::lock_guard<std::mutex> lock(mutex);
  21135. // Ignore a replay from a reconnect that races with stop()
  21136. if (!done) { messages.push_back(msg); }
  21137. });
  21138. sse.on_event("end", [&](const sse::SSEMessage &) {
  21139. std::lock_guard<std::mutex> lock(mutex);
  21140. done = true;
  21141. cv.notify_all();
  21142. });
  21143. sse.set_reconnect_interval(100);
  21144. sse.start_async();
  21145. {
  21146. std::unique_lock<std::mutex> lock(mutex);
  21147. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21148. }
  21149. sse.stop();
  21150. EXPECT_TRUE(done);
  21151. return messages;
  21152. }
  21153. };
  21154. TEST_F(SSEParsingTest, SingleLineData) {
  21155. auto msgs = parse("data: hello\n\n");
  21156. ASSERT_EQ(msgs.size(), 1u);
  21157. EXPECT_EQ(msgs[0].data, "hello");
  21158. EXPECT_EQ(msgs[0].event, "message");
  21159. }
  21160. TEST_F(SSEParsingTest, MultiLineData) {
  21161. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21162. ASSERT_EQ(msgs.size(), 1u);
  21163. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21164. }
  21165. TEST_F(SSEParsingTest, CustomEventType) {
  21166. auto msgs = parse("event: update\ndata: payload\n\n");
  21167. ASSERT_EQ(msgs.size(), 1u);
  21168. EXPECT_EQ(msgs[0].event, "update");
  21169. EXPECT_EQ(msgs[0].data, "payload");
  21170. }
  21171. TEST_F(SSEParsingTest, EventIdHandling) {
  21172. auto msgs = parse("id: 12345\ndata: test\n\n");
  21173. ASSERT_EQ(msgs.size(), 1u);
  21174. EXPECT_EQ(msgs[0].id, "12345");
  21175. }
  21176. TEST_F(SSEParsingTest, EmptyEventId) {
  21177. auto msgs = parse("id:\ndata: test\n\n");
  21178. ASSERT_EQ(msgs.size(), 1u);
  21179. EXPECT_EQ(msgs[0].id, "");
  21180. }
  21181. TEST_F(SSEParsingTest, CommentsIgnored) {
  21182. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21183. ASSERT_EQ(msgs.size(), 1u);
  21184. EXPECT_EQ(msgs[0].data, "hello");
  21185. EXPECT_EQ(msgs[0].event, "message");
  21186. }
  21187. TEST_F(SSEParsingTest, ColonInValue) {
  21188. auto msgs = parse("data: hello:world:test\n\n");
  21189. ASSERT_EQ(msgs.size(), 1u);
  21190. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21191. }
  21192. TEST_F(SSEParsingTest, FieldNameOnly) {
  21193. // A line without a colon is a field name with an empty value
  21194. auto msgs = parse("data\n\n");
  21195. ASSERT_EQ(msgs.size(), 1u);
  21196. EXPECT_EQ(msgs[0].data, "");
  21197. }
  21198. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21199. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21200. ASSERT_EQ(msgs.size(), 1u);
  21201. EXPECT_EQ(msgs[0].event, "update");
  21202. EXPECT_EQ(msgs[0].data, "hello");
  21203. }
  21204. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21205. auto msgs = parse("data\r\n\r\n");
  21206. ASSERT_EQ(msgs.size(), 1u);
  21207. EXPECT_EQ(msgs[0].data, "");
  21208. }
  21209. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21210. auto msgs = parse("event: update\rdata: hello\r\r");
  21211. ASSERT_EQ(msgs.size(), 1u);
  21212. EXPECT_EQ(msgs[0].event, "update");
  21213. EXPECT_EQ(msgs[0].data, "hello");
  21214. }
  21215. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21216. // Chunk boundaries fall inside every \r\n and right before the first one
  21217. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21218. "\n\r", "\nevent: end\ndata: end\n\n"};
  21219. server_->Get("/split", [chunks](const Request &, Response &res) {
  21220. auto i = std::make_shared<size_t>(0);
  21221. res.set_chunked_content_provider(
  21222. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21223. if (*i == chunks.size()) {
  21224. sink.done();
  21225. } else {
  21226. sink.write(chunks[*i].data(), chunks[*i].size());
  21227. (*i)++;
  21228. }
  21229. return true;
  21230. });
  21231. });
  21232. auto msgs = collect("/split");
  21233. ASSERT_EQ(msgs.size(), 1u);
  21234. EXPECT_EQ(msgs[0].event, "update");
  21235. EXPECT_EQ(msgs[0].data, "hello");
  21236. }
  21237. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21238. // Only a BOM at the start of the stream is ignored
  21239. auto msgs = parse("\xEF\xBB\xBF"
  21240. "data: first\n\n"
  21241. "\xEF\xBB\xBF"
  21242. "data: second\n\n");
  21243. ASSERT_EQ(msgs.size(), 1u);
  21244. EXPECT_EQ(msgs[0].data, "first");
  21245. }
  21246. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21247. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21248. ASSERT_EQ(msgs.size(), 1u);
  21249. EXPECT_EQ(msgs[0].data, "hello");
  21250. EXPECT_EQ(msgs[0].event, "message");
  21251. }
  21252. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21253. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21254. ASSERT_EQ(msgs.size(), 2u);
  21255. EXPECT_EQ(msgs[0].data, "hello");
  21256. EXPECT_EQ(msgs[1].data, "hello");
  21257. }
  21258. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21259. // An event without data is not dispatched, and its type must not leak
  21260. // into the next event
  21261. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21262. ASSERT_EQ(msgs.size(), 1u);
  21263. EXPECT_EQ(msgs[0].event, "message");
  21264. EXPECT_EQ(msgs[0].data, "hello");
  21265. }
  21266. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21267. // Also when the empty field replaces an earlier type
  21268. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21269. ASSERT_EQ(msgs.size(), 2u);
  21270. EXPECT_EQ(msgs[0].event, "message");
  21271. EXPECT_EQ(msgs[1].event, "message");
  21272. }
  21273. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21274. // The first connection sends only an id; the second echoes back the
  21275. // Last-Event-ID it was reconnected with
  21276. std::atomic<int> connection_count{0};
  21277. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21278. if (connection_count++ == 0) {
  21279. res.set_content("id: 42\n\n", "text/event-stream");
  21280. } else {
  21281. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21282. "\n\nevent: end\ndata: end\n\n",
  21283. "text/event-stream");
  21284. }
  21285. });
  21286. auto msgs = collect("/id-only");
  21287. ASSERT_EQ(msgs.size(), 1u);
  21288. EXPECT_EQ(msgs[0].data, "42");
  21289. }
  21290. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21291. // The first connection sets an id and then clears it with an empty one; the
  21292. // second reports whether it was reconnected with a Last-Event-ID
  21293. std::atomic<int> connection_count{0};
  21294. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21295. if (connection_count++ == 0) {
  21296. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21297. "text/event-stream");
  21298. } else {
  21299. res.set_content(
  21300. std::string("data: ") +
  21301. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21302. "\n\nevent: end\ndata: end\n\n",
  21303. "text/event-stream");
  21304. }
  21305. });
  21306. auto msgs = collect("/id-clear");
  21307. ASSERT_EQ(msgs.size(), 3u);
  21308. EXPECT_EQ(msgs[0].id, "1");
  21309. EXPECT_EQ(msgs[1].id, "");
  21310. EXPECT_EQ(msgs[2].data, "not sent");
  21311. }
  21312. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21313. // The first connection sets an id and then sends ids that cannot be carried
  21314. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21315. // with
  21316. std::atomic<int> connection_count{0};
  21317. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21318. if (connection_count++ == 0) {
  21319. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21320. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21321. "text/event-stream");
  21322. } else {
  21323. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21324. "\n\nevent: end\ndata: end\n\n",
  21325. "text/event-stream");
  21326. }
  21327. });
  21328. auto msgs = collect("/id-unsendable");
  21329. ASSERT_EQ(msgs.size(), 1u);
  21330. EXPECT_EQ(msgs[0].data, "42");
  21331. }
  21332. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21333. auto msgs = parse("event: notification\nid: evt-42\n"
  21334. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21335. ASSERT_EQ(msgs.size(), 1u);
  21336. EXPECT_EQ(msgs[0].event, "notification");
  21337. EXPECT_EQ(msgs[0].id, "evt-42");
  21338. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21339. }
  21340. TEST(SSEMessageTest, Clear) {
  21341. sse::SSEMessage msg;
  21342. msg.event = "custom";
  21343. msg.data = "some data";
  21344. msg.id = "123";
  21345. msg.clear();
  21346. EXPECT_EQ(msg.event, "message");
  21347. EXPECT_EQ(msg.data, "");
  21348. EXPECT_EQ(msg.id, "");
  21349. }
  21350. //==============================================================================
  21351. // SSE Integration Tests
  21352. //==============================================================================
  21353. // Test: Successful connection and on_open callback
  21354. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21355. // Add a simple endpoint that sends one event and closes
  21356. server_->Get("/simple-event", [](const Request &, Response &res) {
  21357. res.set_chunked_content_provider(
  21358. "text/event-stream", [](size_t offset, DataSink &sink) {
  21359. if (offset == 0) {
  21360. std::string event = "data: hello\n\n";
  21361. sink.write(event.data(), event.size());
  21362. }
  21363. return false; // Close stream after sending
  21364. });
  21365. });
  21366. Client client("localhost", get_port());
  21367. sse::SSEClient sse(client, "/simple-event");
  21368. std::atomic<bool> open_called{false};
  21369. std::atomic<bool> message_received{false};
  21370. sse.on_open([&open_called]() { open_called.store(true); });
  21371. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21372. if (msg.data == "hello") { message_received.store(true); }
  21373. });
  21374. sse.set_reconnect_interval(100);
  21375. sse.set_max_reconnect_attempts(1);
  21376. // Start async
  21377. sse.start_async();
  21378. // Wait for message to be processed
  21379. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21380. sse.stop();
  21381. EXPECT_TRUE(open_called.load());
  21382. EXPECT_TRUE(message_received.load());
  21383. }
  21384. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21385. // A data line that never ends.
  21386. server_->Get("/endless-line", [](const Request &, Response &res) {
  21387. res.set_chunked_content_provider(
  21388. "text/event-stream", [](size_t offset, DataSink &sink) {
  21389. if (offset == 0) { sink.write("data: ", 6); }
  21390. std::string chunk(64 * 1024, 'A');
  21391. return sink.write(chunk.data(), chunk.size());
  21392. });
  21393. });
  21394. Client client("localhost", get_port());
  21395. sse::SSEClient sse(client, "/endless-line");
  21396. std::atomic<bool> too_long{false};
  21397. sse.on_error([&](Error err) {
  21398. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21399. });
  21400. sse.set_max_reconnect_attempts(1);
  21401. sse.start_async();
  21402. for (int i = 0; i < 500 && !too_long; i++) {
  21403. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21404. }
  21405. sse.stop();
  21406. EXPECT_TRUE(too_long);
  21407. }
  21408. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21409. // Far more in all than the client's payload limit below.
  21410. server_->Get("/many-events", [](const Request &, Response &res) {
  21411. res.set_chunked_content_provider(
  21412. "text/event-stream", [](size_t offset, DataSink &sink) {
  21413. if (offset == 0) {
  21414. std::string events;
  21415. for (int i = 0; i < 1000; i++) {
  21416. events += "data: message\n\n";
  21417. }
  21418. sink.write(events.data(), events.size());
  21419. }
  21420. return false;
  21421. });
  21422. });
  21423. Client client("localhost", get_port());
  21424. client.set_payload_max_length(1024);
  21425. sse::SSEClient sse(client, "/many-events");
  21426. std::atomic<int> messages{0};
  21427. std::atomic<bool> too_large{false};
  21428. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21429. sse.on_error([&](Error err) {
  21430. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21431. });
  21432. sse.set_max_reconnect_attempts(1);
  21433. sse.start_async();
  21434. for (int i = 0; i < 500 && messages < 1000; i++) {
  21435. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21436. }
  21437. sse.stop();
  21438. EXPECT_GE(messages.load(), 1000);
  21439. EXPECT_FALSE(too_large);
  21440. }
  21441. // Test: on_message callback
  21442. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21443. // Endpoint that sends multiple events then closes
  21444. server_->Get("/multi-event", [](const Request &, Response &res) {
  21445. res.set_chunked_content_provider(
  21446. "text/event-stream", [](size_t offset, DataSink &sink) {
  21447. if (offset == 0) {
  21448. std::string events = "data: message1\n\ndata: message2\n\n";
  21449. sink.write(events.data(), events.size());
  21450. }
  21451. return false;
  21452. });
  21453. });
  21454. Client client("localhost", get_port());
  21455. sse::SSEClient sse(client, "/multi-event");
  21456. std::vector<std::string> received_messages;
  21457. std::mutex messages_mutex;
  21458. sse.on_message([&](const sse::SSEMessage &msg) {
  21459. std::lock_guard<std::mutex> lock(messages_mutex);
  21460. received_messages.push_back(msg.data);
  21461. });
  21462. sse.set_reconnect_interval(100);
  21463. sse.set_max_reconnect_attempts(1);
  21464. sse.start_async();
  21465. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21466. sse.stop();
  21467. std::lock_guard<std::mutex> lock(messages_mutex);
  21468. EXPECT_GE(received_messages.size(), 2u);
  21469. if (received_messages.size() >= 2) {
  21470. EXPECT_EQ(received_messages[0], "message1");
  21471. EXPECT_EQ(received_messages[1], "message2");
  21472. }
  21473. }
  21474. // Test: on_event for specific types
  21475. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21476. Client client("localhost", get_port());
  21477. sse::SSEClient sse(client, "/custom-events");
  21478. std::atomic<bool> update_received{false};
  21479. std::atomic<bool> delete_received{false};
  21480. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21481. if (msg.data == "updated") { update_received.store(true); }
  21482. });
  21483. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21484. if (msg.data == "deleted") { delete_received.store(true); }
  21485. });
  21486. sse.set_max_reconnect_attempts(1);
  21487. sse.start_async();
  21488. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21489. sse.stop();
  21490. EXPECT_TRUE(update_received.load());
  21491. EXPECT_TRUE(delete_received.load());
  21492. }
  21493. // Test: on_error callback on connection failure
  21494. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21495. // Connect to a non-existent port
  21496. Client client("localhost", 59999);
  21497. sse::SSEClient sse(client, "/events");
  21498. std::atomic<bool> error_called{false};
  21499. Error received_error = Error::Success;
  21500. sse.on_error([&](Error err) {
  21501. error_called.store(true);
  21502. received_error = err;
  21503. });
  21504. sse.set_reconnect_interval(50);
  21505. sse.set_max_reconnect_attempts(1);
  21506. sse.start_async();
  21507. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21508. sse.stop();
  21509. EXPECT_TRUE(error_called.load());
  21510. EXPECT_NE(received_error, Error::Success);
  21511. }
  21512. // Test: Last-Event-ID header sent on reconnect
  21513. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21514. // Endpoint that sends event with ID
  21515. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21516. res.set_chunked_content_provider(
  21517. "text/event-stream", [](size_t offset, DataSink &sink) {
  21518. if (offset == 0) {
  21519. std::string event = "id: evt-123\ndata: test\n\n";
  21520. sink.write(event.data(), event.size());
  21521. }
  21522. return false;
  21523. });
  21524. });
  21525. Client client("localhost", get_port());
  21526. sse::SSEClient sse(client, "/event-with-id");
  21527. std::atomic<bool> id_received{false};
  21528. sse.on_message([&](const sse::SSEMessage &msg) {
  21529. if (!msg.id.empty()) { id_received.store(true); }
  21530. });
  21531. sse.set_reconnect_interval(100);
  21532. sse.set_max_reconnect_attempts(1);
  21533. sse.start_async();
  21534. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21535. sse.stop();
  21536. EXPECT_TRUE(id_received.load());
  21537. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21538. }
  21539. // Test: Manual stop
  21540. TEST_F(SSEIntegrationTest, ManualStop) {
  21541. // Endpoint that sends one event and stays open briefly. The server outlives
  21542. // this test body, so the provider uses the fixture's flag, not a local.
  21543. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21544. res.set_chunked_content_provider(
  21545. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21546. if (offset == 0) {
  21547. std::string event = "data: connected\n\n";
  21548. sink.write(event.data(), event.size());
  21549. }
  21550. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21551. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21552. }
  21553. return false;
  21554. });
  21555. });
  21556. Client client("localhost", get_port());
  21557. sse::SSEClient sse(client, "/stay-open");
  21558. std::atomic<bool> connected{false};
  21559. sse.on_open([&connected]() { connected.store(true); });
  21560. sse.set_reconnect_interval(100);
  21561. sse.set_max_reconnect_attempts(1);
  21562. sse.start_async();
  21563. // Wait for connection to establish
  21564. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21565. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21566. }
  21567. EXPECT_TRUE(connected.load());
  21568. EXPECT_TRUE(sse.is_connected());
  21569. // Signal handler to stop
  21570. stop_server_.store(true);
  21571. // Stop SSE client
  21572. sse.stop();
  21573. EXPECT_FALSE(sse.is_connected());
  21574. }
  21575. // Sends one event, then nothing until stop is set
  21576. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21577. return [&stop](const Request &, Response &res) {
  21578. res.set_chunked_content_provider(
  21579. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21580. if (offset == 0) {
  21581. std::string event = "data: hello\n\n";
  21582. sink.write(event.data(), event.size());
  21583. }
  21584. while (!stop.load()) {
  21585. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21586. }
  21587. return false;
  21588. });
  21589. };
  21590. }
  21591. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21592. static void check_stop_interrupts_blocked_read(Client &client) {
  21593. client.set_read_timeout(30, 0);
  21594. for (auto by_destructor : {false, true}) {
  21595. std::atomic<bool> received{false};
  21596. std::chrono::steady_clock::time_point start;
  21597. {
  21598. sse::SSEClient sse(client, "/idle-stream");
  21599. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21600. sse.start_async();
  21601. for (int i = 0; i < 500 && !received.load(); ++i) {
  21602. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21603. }
  21604. ASSERT_TRUE(received.load());
  21605. // Let the client block in the next read
  21606. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  21607. start = std::chrono::steady_clock::now();
  21608. if (!by_destructor) { sse.stop(); }
  21609. }
  21610. EXPECT_LT(std::chrono::steady_clock::now() - start,
  21611. std::chrono::seconds(2));
  21612. }
  21613. }
  21614. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  21615. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  21616. Client client("localhost", get_port());
  21617. check_stop_interrupts_blocked_read(client);
  21618. }
  21619. #ifdef CPPHTTPLIB_SSL_ENABLED
  21620. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  21621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21622. std::atomic<bool> done{false};
  21623. svr.Get("/idle-stream", idle_event_stream(done));
  21624. auto port = svr.bind_to_any_port(HOST);
  21625. std::thread t([&] { svr.listen_after_bind(); });
  21626. auto se = detail::scope_exit([&] {
  21627. done.store(true);
  21628. svr.stop();
  21629. t.join();
  21630. });
  21631. svr.wait_until_ready();
  21632. Client client("https://localhost:" + std::to_string(port));
  21633. client.enable_server_certificate_verification(false);
  21634. check_stop_interrupts_blocked_read(client);
  21635. }
  21636. #endif
  21637. // Test: SSEClient with custom headers
  21638. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21639. // Setup a server endpoint that checks for custom header
  21640. std::atomic<bool> header_received{false};
  21641. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21642. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21643. header_received.store(true);
  21644. }
  21645. res.set_chunked_content_provider("text/event-stream",
  21646. [](size_t, DataSink &) { return false; });
  21647. });
  21648. Client client("localhost", get_port());
  21649. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21650. sse::SSEClient sse(client, "/header-check", headers);
  21651. sse.set_max_reconnect_attempts(1);
  21652. sse.start_async();
  21653. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21654. sse.stop();
  21655. EXPECT_TRUE(header_received.load());
  21656. }
  21657. // Test: Reconnect interval configuration
  21658. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21659. Client client("localhost", get_port());
  21660. sse::SSEClient sse(client, "/events");
  21661. auto &result = sse.set_reconnect_interval(500);
  21662. // Builder pattern should return reference to self
  21663. EXPECT_EQ(&result, &sse);
  21664. }
  21665. // Test: Max reconnect attempts
  21666. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21667. // Connect to non-existent port to force reconnects
  21668. Client client("localhost", 59998);
  21669. sse::SSEClient sse(client, "/events");
  21670. std::atomic<int> error_count{0};
  21671. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21672. sse.set_reconnect_interval(50);
  21673. sse.set_max_reconnect_attempts(2);
  21674. auto start = std::chrono::steady_clock::now();
  21675. sse.start(); // Blocking call
  21676. auto end = std::chrono::steady_clock::now();
  21677. // Should have stopped after 2 failed attempts
  21678. EXPECT_GE(error_count.load(), 2);
  21679. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21680. auto duration =
  21681. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21682. #ifdef _WIN32
  21683. // Windows is much slower for socket connection failures
  21684. EXPECT_LT(duration.count(), 7000);
  21685. #else
  21686. EXPECT_LT(duration.count(), 1000);
  21687. #endif
  21688. }
  21689. // Test: Multi-line data in integration
  21690. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21691. // Endpoint with multi-line data
  21692. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21693. res.set_chunked_content_provider(
  21694. "text/event-stream", [](size_t offset, DataSink &sink) {
  21695. if (offset == 0) {
  21696. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21697. sink.write(event.data(), event.size());
  21698. }
  21699. return false;
  21700. });
  21701. });
  21702. Client client("localhost", get_port());
  21703. sse::SSEClient sse(client, "/multiline-data");
  21704. std::string received_data;
  21705. std::mutex data_mutex;
  21706. sse.on_message([&](const sse::SSEMessage &msg) {
  21707. std::lock_guard<std::mutex> lock(data_mutex);
  21708. received_data = msg.data;
  21709. });
  21710. sse.set_reconnect_interval(100);
  21711. sse.set_max_reconnect_attempts(1);
  21712. sse.start_async();
  21713. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21714. sse.stop();
  21715. std::lock_guard<std::mutex> lock(data_mutex);
  21716. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21717. }
  21718. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21719. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21720. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21721. DataSink &sink) {
  21722. if (offset == 0) {
  21723. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21724. sink.write(events.data(), events.size());
  21725. }
  21726. return false;
  21727. });
  21728. });
  21729. Client client("localhost", get_port());
  21730. sse::SSEClient sse(client, "/empty-data-lines");
  21731. std::mutex mutex;
  21732. std::condition_variable cv;
  21733. std::vector<std::string> received;
  21734. sse.on_message([&](const sse::SSEMessage &msg) {
  21735. std::lock_guard<std::mutex> lock(mutex);
  21736. received.push_back(msg.data);
  21737. cv.notify_all();
  21738. });
  21739. sse.set_max_reconnect_attempts(1);
  21740. sse.start_async();
  21741. {
  21742. std::unique_lock<std::mutex> lock(mutex);
  21743. cv.wait_for(lock, std::chrono::seconds(2),
  21744. [&] { return received.size() >= 3; });
  21745. }
  21746. sse.stop();
  21747. ASSERT_GE(received.size(), 3u);
  21748. EXPECT_EQ(received[0], "");
  21749. EXPECT_EQ(received[1], "\nhello");
  21750. EXPECT_EQ(received[2], "");
  21751. }
  21752. // Test: Auto-reconnect after server disconnection
  21753. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21754. std::atomic<int> connection_count{0};
  21755. std::atomic<int> message_count{0};
  21756. // Endpoint that sends one event and closes, forcing reconnect
  21757. server_->Get("/reconnect-test",
  21758. [&connection_count](const Request &, Response &res) {
  21759. connection_count.fetch_add(1);
  21760. res.set_chunked_content_provider(
  21761. "text/event-stream", [](size_t offset, DataSink &sink) {
  21762. if (offset == 0) {
  21763. std::string event = "data: hello\n\n";
  21764. sink.write(event.data(), event.size());
  21765. }
  21766. return false; // Close connection after sending
  21767. });
  21768. });
  21769. Client client("localhost", get_port());
  21770. sse::SSEClient sse(client, "/reconnect-test");
  21771. sse.on_message([&message_count](const sse::SSEMessage &) {
  21772. message_count.fetch_add(1);
  21773. });
  21774. sse.set_reconnect_interval(100);
  21775. sse.set_max_reconnect_attempts(3);
  21776. sse.start_async();
  21777. // Wait long enough for multiple reconnects
  21778. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21779. sse.stop();
  21780. // Should have connected multiple times (initial + reconnects)
  21781. EXPECT_GE(connection_count.load(), 2);
  21782. // Should have received messages from multiple connections
  21783. EXPECT_GE(message_count.load(), 2);
  21784. }
  21785. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  21786. std::atomic<int> connection_count{0};
  21787. // Neither Content-Length nor chunked: the close ends the stream
  21788. server_->Get("/close-delimited",
  21789. [&connection_count](const Request &, Response &res) {
  21790. connection_count.fetch_add(1);
  21791. res.set_content_provider(
  21792. "text/event-stream", [](size_t offset, DataSink &sink) {
  21793. if (offset == 0) {
  21794. std::string event = "data: hello\n\n";
  21795. sink.write(event.data(), event.size());
  21796. } else {
  21797. sink.done();
  21798. }
  21799. return true;
  21800. });
  21801. });
  21802. Client client("localhost", get_port());
  21803. sse::SSEClient sse(client, "/close-delimited");
  21804. std::atomic<int> error_count{0};
  21805. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  21806. sse.set_reconnect_interval(100);
  21807. sse.start_async();
  21808. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  21809. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21810. }
  21811. sse.stop();
  21812. // Reconnects as after any end of the stream, but reports no error
  21813. EXPECT_GE(connection_count.load(), 2);
  21814. EXPECT_EQ(0, error_count.load());
  21815. }
  21816. // Test: A retry field that is not all ASCII digits is ignored
  21817. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21818. std::atomic<int> connection_count{0};
  21819. server_->Get("/bad-retry",
  21820. [&connection_count](const Request &, Response &res) {
  21821. connection_count.fetch_add(1);
  21822. res.set_chunked_content_provider(
  21823. "text/event-stream", [](size_t offset, DataSink &sink) {
  21824. if (offset == 0) {
  21825. std::string event = "retry: -1\ndata: hello\n\n";
  21826. sink.write(event.data(), event.size());
  21827. }
  21828. return false;
  21829. });
  21830. });
  21831. Client client("localhost", get_port());
  21832. sse::SSEClient sse(client, "/bad-retry");
  21833. sse.set_reconnect_interval(10000);
  21834. sse.start_async();
  21835. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21836. sse.stop();
  21837. EXPECT_EQ(connection_count.load(), 1);
  21838. }
  21839. // Test: A retry field of all ASCII digits sets the reconnection time
  21840. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21841. std::mutex mutex;
  21842. std::condition_variable cv;
  21843. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21844. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21845. {
  21846. std::lock_guard<std::mutex> lock(mutex);
  21847. connected_at.push_back(std::chrono::steady_clock::now());
  21848. cv.notify_all();
  21849. }
  21850. res.set_chunked_content_provider(
  21851. "text/event-stream", [](size_t offset, DataSink &sink) {
  21852. if (offset == 0) {
  21853. std::string event = "retry: 0\ndata: hello\n\n";
  21854. sink.write(event.data(), event.size());
  21855. }
  21856. return false;
  21857. });
  21858. });
  21859. Client client("localhost", get_port());
  21860. sse::SSEClient sse(client, "/zero-retry");
  21861. sse.set_reconnect_interval(10000);
  21862. sse.start_async();
  21863. {
  21864. std::unique_lock<std::mutex> lock(mutex);
  21865. cv.wait_for(lock, std::chrono::seconds(5),
  21866. [&] { return connected_at.size() >= 2; });
  21867. }
  21868. sse.stop();
  21869. // The server-supplied interval is applied, but never below 100ms, so
  21870. // "retry: 0" does not cause a busy reconnect loop
  21871. std::lock_guard<std::mutex> lock(mutex);
  21872. ASSERT_GE(connected_at.size(), 2u);
  21873. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21874. connected_at[1] - connected_at[0])
  21875. .count();
  21876. EXPECT_GE(interval_ms, 100);
  21877. }
  21878. // Test: Last-Event-ID sent on reconnect
  21879. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21880. std::atomic<int> connection_count{0};
  21881. std::vector<std::string> received_last_event_ids;
  21882. std::mutex id_mutex;
  21883. // Endpoint that checks Last-Event-ID header and sends event with ID
  21884. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21885. int conn = connection_count.fetch_add(1);
  21886. // Capture the Last-Event-ID header from each connection
  21887. {
  21888. std::lock_guard<std::mutex> lock(id_mutex);
  21889. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21890. }
  21891. res.set_chunked_content_provider(
  21892. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21893. if (offset == 0) {
  21894. std::string event =
  21895. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21896. sink.write(event.data(), event.size());
  21897. }
  21898. return false;
  21899. });
  21900. });
  21901. Client client("localhost", get_port());
  21902. sse::SSEClient sse(client, "/reconnect-with-id");
  21903. sse.set_reconnect_interval(100);
  21904. sse.set_max_reconnect_attempts(3);
  21905. sse.start_async();
  21906. // Wait for at least 2 connections
  21907. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21908. sse.stop();
  21909. // Verify behavior
  21910. std::lock_guard<std::mutex> lock(id_mutex);
  21911. EXPECT_GE(received_last_event_ids.size(), 2u);
  21912. // First connection should have no Last-Event-ID
  21913. if (!received_last_event_ids.empty()) {
  21914. EXPECT_EQ(received_last_event_ids[0], "");
  21915. }
  21916. // Second connection should have Last-Event-ID from first connection
  21917. if (received_last_event_ids.size() >= 2) {
  21918. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21919. }
  21920. }
  21921. // Test: set_headers updates headers used on reconnect
  21922. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21923. std::vector<std::string> received_tokens;
  21924. std::mutex token_mutex;
  21925. // Endpoint that captures Authorization header
  21926. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21927. {
  21928. std::lock_guard<std::mutex> lock(token_mutex);
  21929. received_tokens.push_back(req.get_header_value("Authorization"));
  21930. }
  21931. res.set_chunked_content_provider(
  21932. "text/event-stream", [](size_t offset, DataSink &sink) {
  21933. if (offset == 0) {
  21934. std::string event = "data: hello\n\n";
  21935. sink.write(event.data(), event.size());
  21936. }
  21937. return false; // Close connection to trigger reconnect
  21938. });
  21939. });
  21940. Client client("localhost", get_port());
  21941. Headers headers = {{"Authorization", "Bearer old-token"}};
  21942. sse::SSEClient sse(client, "/auth-check", headers);
  21943. // Update headers on each successful connection
  21944. sse.on_open(
  21945. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21946. sse.set_reconnect_interval(100);
  21947. sse.set_max_reconnect_attempts(3);
  21948. sse.start_async();
  21949. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21950. sse.stop();
  21951. std::lock_guard<std::mutex> lock(token_mutex);
  21952. ASSERT_GE(received_tokens.size(), 2u);
  21953. // First connection uses original header
  21954. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21955. // Second connection uses updated header from set_headers
  21956. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21957. }
  21958. // Test: 401 allows reconnection (so on_error can refresh headers)
  21959. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21960. std::atomic<int> connection_count{0};
  21961. // Endpoint: returns 401 on first attempt, 200 on second
  21962. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21963. int conn = connection_count.fetch_add(1);
  21964. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21965. res.status = StatusCode::Unauthorized_401;
  21966. res.set_content("Unauthorized", "text/plain");
  21967. return;
  21968. }
  21969. res.set_chunked_content_provider(
  21970. "text/event-stream", [](size_t offset, DataSink &sink) {
  21971. if (offset == 0) {
  21972. std::string event = "data: authenticated\n\n";
  21973. sink.write(event.data(), event.size());
  21974. }
  21975. return false;
  21976. });
  21977. });
  21978. Client client("localhost", get_port());
  21979. Headers headers = {{"Authorization", "Bearer expired"}};
  21980. sse::SSEClient sse(client, "/auth-retry", headers);
  21981. std::atomic<bool> message_received{false};
  21982. // Refresh token on error
  21983. sse.on_error(
  21984. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21985. sse.on_message([&](const sse::SSEMessage &msg) {
  21986. if (msg.data == "authenticated") { message_received.store(true); }
  21987. });
  21988. sse.set_reconnect_interval(100);
  21989. sse.set_max_reconnect_attempts(3);
  21990. sse.start_async();
  21991. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21992. sse.stop();
  21993. // Should have reconnected after 401 and succeeded with new token
  21994. EXPECT_GE(connection_count.load(), 2);
  21995. EXPECT_TRUE(message_received.load());
  21996. }
  21997. TEST(Issue2318Test, EmptyHostString) {
  21998. {
  21999. httplib::Client cli_empty("", PORT);
  22000. auto res = cli_empty.Get("/");
  22001. ASSERT_FALSE(res);
  22002. EXPECT_EQ(httplib::Error::Connection, res.error());
  22003. }
  22004. {
  22005. httplib::Client cli(" ", PORT);
  22006. auto res = cli.Get("/");
  22007. ASSERT_FALSE(res);
  22008. EXPECT_EQ(httplib::Error::Connection, res.error());
  22009. }
  22010. }
  22011. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22012. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22013. Server svr;
  22014. // Set a small payload limit (1KB)
  22015. svr.set_payload_max_length(1024);
  22016. svr.Post("/test", [&](const Request &req, Response &res) {
  22017. res.set_content("Body size: " + std::to_string(req.body.size()),
  22018. "text/plain");
  22019. });
  22020. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22021. auto se = detail::scope_exit([&] {
  22022. svr.stop();
  22023. listen_thread.join();
  22024. });
  22025. svr.wait_until_ready();
  22026. // Create data that compresses well but exceeds limit when decompressed
  22027. // 8KB of repeated null bytes compresses to a very small size
  22028. std::string original_data(8 * 1024, '\0');
  22029. // Compress the data using gzip
  22030. std::string compressed_data;
  22031. detail::gzip_compressor compressor;
  22032. compressor.compress(original_data.data(), original_data.size(), true,
  22033. [&](const char *data, size_t size) {
  22034. compressed_data.append(data, size);
  22035. return true;
  22036. });
  22037. // Verify compression worked (compressed should be much smaller)
  22038. ASSERT_LT(compressed_data.size(), original_data.size());
  22039. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22040. // Send compressed data with Content-Encoding: gzip
  22041. Client cli(HOST, PORT);
  22042. Headers headers = {{"Content-Encoding", "gzip"}};
  22043. auto res =
  22044. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22045. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22047. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22048. }
  22049. #endif
  22050. // ============================================================================
  22051. // OpenSSL-Specific Tests
  22052. // ============================================================================
  22053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22054. X509 *readCertificate(const std::string &strFileName) {
  22055. std::ifstream inStream(strFileName);
  22056. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22057. std::istreambuf_iterator<char>());
  22058. if (strCertPEM.empty()) return (nullptr);
  22059. BIO *pbCert = BIO_new(BIO_s_mem());
  22060. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22061. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22062. BIO_free(pbCert);
  22063. return (pCert);
  22064. }
  22065. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22066. std::ifstream inStream(strFileName);
  22067. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22068. std::istreambuf_iterator<char>());
  22069. if (strPrivateKeyPEM.empty()) return (nullptr);
  22070. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22071. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22072. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22073. BIO_free(pbPrivKey);
  22074. return (pPrivateKey);
  22075. }
  22076. TEST(BindServerTest, UpdateCerts) {
  22077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22078. int port = svr.bind_to_any_port("0.0.0.0");
  22079. ASSERT_TRUE(svr.is_valid());
  22080. ASSERT_TRUE(port > 0);
  22081. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22082. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22083. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22084. ASSERT_TRUE(cert != nullptr);
  22085. ASSERT_TRUE(ca_cert != nullptr);
  22086. ASSERT_TRUE(key != nullptr);
  22087. X509_STORE *cert_store = X509_STORE_new();
  22088. X509_STORE_add_cert(cert_store, ca_cert);
  22089. // svr.update_certs(cert, key, cert_store); // deprecated
  22090. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22091. CLIENT_CA_CERT_FILE);
  22092. ASSERT_TRUE(svr.is_valid());
  22093. svr.stop();
  22094. X509_STORE_free(cert_store);
  22095. X509_free(cert);
  22096. X509_free(ca_cert);
  22097. EVP_PKEY_free(key);
  22098. }
  22099. // Test that update_certs() updates client CA list correctly
  22100. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22101. // Start with file-based constructor
  22102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22103. ASSERT_TRUE(svr.is_valid());
  22104. // Initially no client CA list should be set
  22105. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22106. ASSERT_TRUE(ssl_ctx != nullptr);
  22107. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22108. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22109. // Now update with client CA (PEM string)
  22110. std::string cert_pem, key_pem, ca_pem;
  22111. read_file(SERVER_CERT_FILE, cert_pem);
  22112. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22113. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22114. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22115. ASSERT_TRUE(svr.is_valid());
  22116. // Now client CA list should be set
  22117. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22118. ASSERT_TRUE(ca_list_after != nullptr);
  22119. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22120. }
  22121. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22122. // Test that the file-path SSLServer constructor properly sets the client CA
  22123. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22125. ASSERT_TRUE(svr.is_valid());
  22126. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22127. ASSERT_TRUE(ssl_ctx != nullptr);
  22128. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22129. ASSERT_TRUE(ca_list != nullptr);
  22130. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22131. }
  22132. #endif
  22133. // ============================================================================
  22134. // MbedTLS-Specific Tests
  22135. // ============================================================================
  22136. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22137. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22138. using namespace httplib::tls;
  22139. // Track if callback was invoked
  22140. bool callback_invoked = false;
  22141. // The callback receives void* ctx which is actually MbedTlsContext*
  22142. // We can access the mbedtls_ssl_config via the context
  22143. auto setup_callback = [&callback_invoked](void *ctx) {
  22144. callback_invoked = true;
  22145. // Cast to MbedTlsContext* to access the ssl config
  22146. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22147. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22148. // Use static variables to hold certificate data (simplified for test)
  22149. static mbedtls_x509_crt own_cert;
  22150. static mbedtls_pk_context own_key;
  22151. static mbedtls_x509_crt ca_chain;
  22152. static bool initialized = false;
  22153. if (!initialized) {
  22154. mbedtls_x509_crt_init(&own_cert);
  22155. mbedtls_pk_init(&own_key);
  22156. mbedtls_x509_crt_init(&ca_chain);
  22157. // Load server certificate
  22158. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22159. return false;
  22160. }
  22161. // Load server private key.
  22162. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22163. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22164. #if MBEDTLS_VERSION_MAJOR == 3
  22165. ,
  22166. mbedtls_ctr_drbg_random, nullptr
  22167. #endif
  22168. ) != 0) {
  22169. return false;
  22170. }
  22171. // Load CA chain for client verification
  22172. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22173. return false;
  22174. }
  22175. initialized = true;
  22176. }
  22177. // Configure the SSL config
  22178. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22179. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22180. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22181. // Set minimum TLS version using mbedTLS native API
  22182. #if MBEDTLS_VERSION_MAJOR >= 3
  22183. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22184. #else
  22185. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22186. MBEDTLS_SSL_MINOR_VERSION_3);
  22187. #endif
  22188. return true;
  22189. };
  22190. SSLServer svr(setup_callback);
  22191. ASSERT_TRUE(svr.is_valid());
  22192. ASSERT_TRUE(callback_invoked);
  22193. svr.Get("/test", [&](const Request &req, Response &res) {
  22194. res.set_content("test", "text/plain");
  22195. auto cert = req.peer_cert();
  22196. ASSERT_TRUE(static_cast<bool>(cert));
  22197. auto common_name = cert.subject_cn();
  22198. EXPECT_EQ("Common Name", common_name);
  22199. });
  22200. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22201. auto se = detail::scope_exit([&] {
  22202. svr.stop();
  22203. t.join();
  22204. ASSERT_FALSE(svr.is_running());
  22205. });
  22206. svr.wait_until_ready();
  22207. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22208. cli.enable_server_certificate_verification(false);
  22209. cli.set_connection_timeout(30);
  22210. auto res = cli.Get("/test");
  22211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22212. ASSERT_EQ(StatusCode::OK_200, res->status);
  22213. }
  22214. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22215. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22216. // keep-alive SSL session, which reads through that config in
  22217. // mbedtls_ssl_close_notify.
  22218. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22220. ASSERT_TRUE(svr.is_valid());
  22221. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22222. res.set_content("test", "text/plain");
  22223. });
  22224. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22225. auto se = detail::scope_exit([&] {
  22226. svr.stop();
  22227. t.join();
  22228. ASSERT_FALSE(svr.is_running());
  22229. });
  22230. svr.wait_until_ready();
  22231. {
  22232. SSLClient cli(HOST, PORT);
  22233. cli.enable_server_certificate_verification(false);
  22234. cli.set_keep_alive(true);
  22235. auto res = cli.Get("/test");
  22236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22237. ASSERT_EQ(StatusCode::OK_200, res->status);
  22238. // cli is destructed here with the keep-alive SSL session still open.
  22239. }
  22240. }
  22241. #endif
  22242. // WebSocket Tests
  22243. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22244. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22245. // defining the meaning of these bits has been negotiated.
  22246. auto make_frame = [](uint8_t first_byte) {
  22247. std::string frame;
  22248. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22249. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22250. frame += "Hello";
  22251. return frame;
  22252. };
  22253. // RSV1 set (0x40)
  22254. {
  22255. detail::BufferStream strm;
  22256. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22257. ws::Opcode opcode;
  22258. std::string payload;
  22259. bool fin;
  22260. EXPECT_EQ(
  22261. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22262. ws::impl::FrameRead::Fail);
  22263. }
  22264. // RSV2 set (0x20)
  22265. {
  22266. detail::BufferStream strm;
  22267. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22268. ws::Opcode opcode;
  22269. std::string payload;
  22270. bool fin;
  22271. EXPECT_EQ(
  22272. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22273. ws::impl::FrameRead::Fail);
  22274. }
  22275. // RSV3 set (0x10)
  22276. {
  22277. detail::BufferStream strm;
  22278. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22279. ws::Opcode opcode;
  22280. std::string payload;
  22281. bool fin;
  22282. EXPECT_EQ(
  22283. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22284. ws::impl::FrameRead::Fail);
  22285. }
  22286. // No RSV bits set - should succeed
  22287. {
  22288. detail::BufferStream strm;
  22289. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22290. ws::Opcode opcode;
  22291. std::string payload;
  22292. bool fin;
  22293. EXPECT_EQ(
  22294. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22295. ws::impl::FrameRead::Ok);
  22296. EXPECT_EQ(ws::Opcode::Text, opcode);
  22297. EXPECT_EQ("Hello", payload);
  22298. EXPECT_TRUE(fin);
  22299. }
  22300. }
  22301. TEST(WebSocketTest, ControlFrameValidation) {
  22302. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22303. // payload length <= 125.
  22304. // Ping with FIN=0 - must be rejected
  22305. {
  22306. detail::BufferStream strm;
  22307. std::string frame;
  22308. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22309. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22310. strm.write(frame.data(), frame.size());
  22311. ws::Opcode opcode;
  22312. std::string payload;
  22313. bool fin;
  22314. EXPECT_EQ(
  22315. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22316. ws::impl::FrameRead::Fail);
  22317. }
  22318. // Close with FIN=0 - must be rejected
  22319. {
  22320. detail::BufferStream strm;
  22321. std::string frame;
  22322. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22323. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22324. strm.write(frame.data(), frame.size());
  22325. ws::Opcode opcode;
  22326. std::string payload;
  22327. bool fin;
  22328. EXPECT_EQ(
  22329. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22330. ws::impl::FrameRead::Fail);
  22331. }
  22332. // Ping with payload_len=126 (extended length) - must be rejected
  22333. {
  22334. detail::BufferStream strm;
  22335. std::string frame;
  22336. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22337. frame += static_cast<char>(126); // payload_len=126 (>125)
  22338. frame += static_cast<char>(0x00); // extended length high byte
  22339. frame += static_cast<char>(126); // extended length low byte
  22340. frame += std::string(126, 'x');
  22341. strm.write(frame.data(), frame.size());
  22342. ws::Opcode opcode;
  22343. std::string payload;
  22344. bool fin;
  22345. EXPECT_EQ(
  22346. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22347. ws::impl::FrameRead::Fail);
  22348. }
  22349. // Ping with FIN=1 and payload_len=125 - should succeed
  22350. {
  22351. detail::BufferStream strm;
  22352. std::string frame;
  22353. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22354. frame += static_cast<char>(125); // payload_len=125
  22355. frame += std::string(125, 'x');
  22356. strm.write(frame.data(), frame.size());
  22357. ws::Opcode opcode;
  22358. std::string payload;
  22359. bool fin;
  22360. EXPECT_EQ(
  22361. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22362. ws::impl::FrameRead::Ok);
  22363. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22364. EXPECT_EQ(125u, payload.size());
  22365. EXPECT_TRUE(fin);
  22366. }
  22367. }
  22368. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22369. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22370. // length MUST be 0.
  22371. // MSB set - must be rejected
  22372. {
  22373. detail::BufferStream strm;
  22374. std::string frame;
  22375. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22376. frame += static_cast<char>(127); // 64-bit extended length
  22377. frame += static_cast<char>(0x80); // MSB set (invalid)
  22378. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22379. strm.write(frame.data(), frame.size());
  22380. ws::Opcode opcode;
  22381. std::string payload;
  22382. bool fin;
  22383. EXPECT_EQ(
  22384. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22385. ws::impl::FrameRead::Fail);
  22386. }
  22387. // MSB clear - should pass length parsing (will be rejected by max_len,
  22388. // but that's a different check; use a small length to verify)
  22389. {
  22390. detail::BufferStream strm;
  22391. std::string frame;
  22392. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22393. frame += static_cast<char>(127); // 64-bit extended length
  22394. frame += std::string(7, '\0'); // high bytes = 0
  22395. frame += static_cast<char>(0x03); // length = 3
  22396. frame += "abc";
  22397. strm.write(frame.data(), frame.size());
  22398. ws::Opcode opcode;
  22399. std::string payload;
  22400. bool fin;
  22401. EXPECT_EQ(
  22402. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22403. ws::impl::FrameRead::Ok);
  22404. EXPECT_EQ(ws::Opcode::Text, opcode);
  22405. EXPECT_EQ("abc", payload);
  22406. }
  22407. }
  22408. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22409. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22410. // Valid UTF-8
  22411. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22412. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22413. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22414. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22415. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22416. // Invalid UTF-8
  22417. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22418. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22419. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22420. EXPECT_FALSE(
  22421. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22422. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22423. }
  22424. TEST(WebSocketTest, ConnectAndDisconnect) {
  22425. Server svr;
  22426. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22427. std::string msg;
  22428. while (ws.read(msg)) {}
  22429. });
  22430. auto port = svr.bind_to_any_port(HOST);
  22431. std::thread t([&]() { svr.listen_after_bind(); });
  22432. svr.wait_until_ready();
  22433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22434. auto res = client.connect();
  22435. ASSERT_TRUE(res);
  22436. EXPECT_EQ(Error::Success, res.error());
  22437. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22438. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22439. EXPECT_TRUE(client.is_open());
  22440. client.close();
  22441. EXPECT_FALSE(client.is_open());
  22442. svr.stop();
  22443. t.join();
  22444. }
  22445. TEST(WebSocketTest, ValidURL) {
  22446. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22447. EXPECT_TRUE(ws1.is_valid());
  22448. ws::WebSocketClient ws2("ws://example.com/path");
  22449. EXPECT_TRUE(ws2.is_valid());
  22450. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22451. EXPECT_TRUE(ws3.is_valid());
  22452. #ifdef CPPHTTPLIB_SSL_ENABLED
  22453. ws::WebSocketClient wss1("wss://example.com/path");
  22454. EXPECT_TRUE(wss1.is_valid());
  22455. ws::WebSocketClient wss2("wss://example.com:443/path");
  22456. EXPECT_TRUE(wss2.is_valid());
  22457. #endif
  22458. }
  22459. TEST(WebSocketTest, InvalidURL) {
  22460. // No scheme
  22461. ws::WebSocketClient ws1("localhost:8080/path");
  22462. EXPECT_FALSE(ws1.is_valid());
  22463. // No path
  22464. ws::WebSocketClient ws2("ws://localhost:8080");
  22465. EXPECT_FALSE(ws2.is_valid());
  22466. // Empty string
  22467. ws::WebSocketClient ws3("");
  22468. EXPECT_FALSE(ws3.is_valid());
  22469. // Missing host
  22470. ws::WebSocketClient ws4("ws://:8080/path");
  22471. EXPECT_FALSE(ws4.is_valid());
  22472. // Port number overflow — should not crash
  22473. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22474. EXPECT_FALSE(ws5.is_valid());
  22475. // Port out of range
  22476. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22477. EXPECT_FALSE(ws6.is_valid());
  22478. }
  22479. TEST(WebSocketTest, UnsupportedScheme) {
  22480. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22481. ws::WebSocketClient ws1("http://localhost:8080/path");
  22482. EXPECT_FALSE(ws1.is_valid());
  22483. ws::WebSocketClient ws2("https://localhost:8080/path");
  22484. EXPECT_FALSE(ws2.is_valid());
  22485. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22486. EXPECT_FALSE(ws3.is_valid());
  22487. #else
  22488. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22489. std::invalid_argument);
  22490. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22491. std::invalid_argument);
  22492. #endif
  22493. }
  22494. TEST(WebSocketTest, ConnectWhenInvalid) {
  22495. ws::WebSocketClient ws("not a valid url");
  22496. EXPECT_FALSE(ws.is_valid());
  22497. auto res = ws.connect();
  22498. EXPECT_FALSE(res);
  22499. EXPECT_EQ(Error::Connection, res.error());
  22500. EXPECT_EQ(-1, res.status());
  22501. }
  22502. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22503. // Grab a port that is free, then close it again so nothing listens there
  22504. Server svr;
  22505. auto port = svr.bind_to_any_port(HOST);
  22506. svr.stop();
  22507. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22508. auto res = client.connect();
  22509. ASSERT_FALSE(res);
  22510. EXPECT_EQ(Error::Connection, res.error());
  22511. EXPECT_EQ(-1, res.status());
  22512. }
  22513. TEST(WebSocketTest, DefaultPort) {
  22514. ws::WebSocketClient ws1("ws://example.com/path");
  22515. EXPECT_TRUE(ws1.is_valid());
  22516. // ws:// defaults to port 80 (verified by successful parse)
  22517. #ifdef CPPHTTPLIB_SSL_ENABLED
  22518. ws::WebSocketClient ws2("wss://example.com/path");
  22519. EXPECT_TRUE(ws2.is_valid());
  22520. // wss:// defaults to port 443 (verified by successful parse)
  22521. #endif
  22522. }
  22523. TEST(WebSocketTest, IPv6LiteralAddress) {
  22524. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22525. EXPECT_TRUE(ws1.is_valid());
  22526. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22527. EXPECT_TRUE(ws2.is_valid());
  22528. }
  22529. TEST(WebSocketTest, ComplexPath) {
  22530. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22531. EXPECT_TRUE(ws1.is_valid());
  22532. ws::WebSocketClient ws2("ws://localhost:8080/");
  22533. EXPECT_TRUE(ws2.is_valid());
  22534. }
  22535. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22536. Server svr;
  22537. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22538. std::string msg;
  22539. while (ws.read(msg)) {}
  22540. });
  22541. auto port = svr.bind_to_any_port(HOST);
  22542. std::thread t([&]() { svr.listen_after_bind(); });
  22543. svr.wait_until_ready();
  22544. auto another_host = "example.com";
  22545. auto wrong_ip = "192.0.2.1";
  22546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22547. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22548. ASSERT_TRUE(client.connect());
  22549. EXPECT_TRUE(client.is_open());
  22550. client.close();
  22551. svr.stop();
  22552. t.join();
  22553. }
  22554. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22555. Server svr;
  22556. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22557. std::string msg;
  22558. while (ws.read(msg)) {}
  22559. });
  22560. auto port = svr.bind_to_any_port(HOST);
  22561. std::thread t([&]() { svr.listen_after_bind(); });
  22562. svr.wait_until_ready();
  22563. auto wrong_ip = "192.0.2.1";
  22564. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22565. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22566. client.set_connection_timeout(1);
  22567. client.set_read_timeout(1);
  22568. client.set_write_timeout(1);
  22569. EXPECT_FALSE(client.connect());
  22570. EXPECT_FALSE(client.is_open());
  22571. svr.stop();
  22572. t.join();
  22573. }
  22574. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22575. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22576. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22577. // (RFC 6761) is only a map key and the Host header value.
  22578. auto host = "target.invalid";
  22579. Server svr;
  22580. std::string received_host;
  22581. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22582. received_host = req.get_header_value("Host");
  22583. std::string msg;
  22584. while (ws.read(msg)) {}
  22585. });
  22586. auto port = svr.bind_to_any_port(HOST);
  22587. std::thread t([&]() { svr.listen_after_bind(); });
  22588. // ASSERT_* below returns from the test body, which would leave t joinable
  22589. // and make ~thread call std::terminate.
  22590. auto se = detail::scope_exit([&] {
  22591. svr.stop();
  22592. if (t.joinable()) { t.join(); }
  22593. });
  22594. svr.wait_until_ready();
  22595. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22596. std::to_string(port) + "/ws");
  22597. client.set_hostname_addr_map({{host, HOST}});
  22598. ASSERT_TRUE(client.connect());
  22599. EXPECT_TRUE(client.is_open());
  22600. client.close();
  22601. svr.stop();
  22602. t.join();
  22603. // The mapping only redirects the connection; the identity stays host_.
  22604. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22605. }
  22606. class WebSocketIntegrationTest : public ::testing::Test {
  22607. protected:
  22608. void SetUp() override {
  22609. server_ = httplib::detail::make_unique<Server>();
  22610. setup_server();
  22611. start_server();
  22612. }
  22613. void TearDown() override {
  22614. server_->stop();
  22615. if (server_thread_.joinable()) { server_thread_.join(); }
  22616. }
  22617. void setup_server() {
  22618. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22619. std::string msg;
  22620. ws::ReadResult ret;
  22621. while ((ret = ws.read(msg))) {
  22622. if (ret == ws::Binary) {
  22623. ws.send(msg.data(), msg.size());
  22624. } else {
  22625. ws.send(msg);
  22626. }
  22627. }
  22628. });
  22629. server_->WebSocket("/ws-echo-string",
  22630. [](const Request &, ws::WebSocket &ws) {
  22631. std::string msg;
  22632. while (ws.read(msg)) {
  22633. ws.send("echo: " + msg);
  22634. }
  22635. });
  22636. server_->WebSocket(
  22637. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22638. // Echo back request metadata
  22639. ws.send("path:" + req.path);
  22640. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22641. std::string msg;
  22642. while (ws.read(msg)) {}
  22643. });
  22644. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22645. std::string msg;
  22646. ws.read(msg); // wait for a message
  22647. ws.close();
  22648. });
  22649. server_->WebSocket("/ws-close-status",
  22650. [](const Request &, ws::WebSocket &ws) {
  22651. std::string msg;
  22652. ws.read(msg); // wait for a message
  22653. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22654. });
  22655. server_->WebSocket(
  22656. "/ws-subprotocol",
  22657. [](const Request &, ws::WebSocket &ws) {
  22658. std::string msg;
  22659. while (ws.read(msg)) {
  22660. ws.send(msg);
  22661. }
  22662. },
  22663. [](const std::vector<std::string> &protocols) -> std::string {
  22664. for (const auto &p : protocols) {
  22665. if (p == "graphql-ws") { return p; }
  22666. }
  22667. return "";
  22668. });
  22669. server_->WebSocket(
  22670. "/ws-subprotocol-unoffered",
  22671. [](const Request &, ws::WebSocket &ws) {
  22672. std::string msg;
  22673. while (ws.read(msg)) {
  22674. ws.send(msg);
  22675. }
  22676. },
  22677. [](const std::vector<std::string> &) -> std::string {
  22678. return "admin";
  22679. });
  22680. }
  22681. void start_server() {
  22682. port_ = server_->bind_to_any_port(HOST);
  22683. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22684. server_->wait_until_ready();
  22685. }
  22686. std::unique_ptr<Server> server_;
  22687. std::thread server_thread_;
  22688. int port_ = 0;
  22689. };
  22690. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22691. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22692. "/ws-echo");
  22693. ASSERT_TRUE(client.connect());
  22694. ASSERT_TRUE(client.is_open());
  22695. ASSERT_TRUE(client.send("Hello WebSocket"));
  22696. std::string msg;
  22697. EXPECT_EQ(ws::Text, client.read(msg));
  22698. EXPECT_EQ("Hello WebSocket", msg);
  22699. client.close();
  22700. }
  22701. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22703. "/ws-echo");
  22704. ASSERT_TRUE(client.connect());
  22705. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22706. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22707. std::string msg;
  22708. EXPECT_EQ(ws::Binary, client.read(msg));
  22709. EXPECT_EQ(binary_data, msg);
  22710. client.close();
  22711. }
  22712. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22714. "/ws-echo");
  22715. ASSERT_TRUE(client.connect());
  22716. for (int i = 0; i < 10; i++) {
  22717. auto text = "message " + std::to_string(i);
  22718. ASSERT_TRUE(client.send(text));
  22719. std::string msg;
  22720. ASSERT_TRUE(client.read(msg));
  22721. EXPECT_EQ(text, msg);
  22722. }
  22723. client.close();
  22724. }
  22725. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22727. "/ws-close");
  22728. ASSERT_TRUE(client.connect());
  22729. // Send a message to trigger the server to close
  22730. ASSERT_TRUE(client.send("trigger close"));
  22731. // The server will close, so read should return false
  22732. std::string msg;
  22733. EXPECT_FALSE(client.read(msg));
  22734. EXPECT_FALSE(client.is_open());
  22735. }
  22736. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22737. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22738. "/ws-echo");
  22739. ASSERT_TRUE(client.connect());
  22740. // 128KB message
  22741. std::string large_data(128 * 1024, 'X');
  22742. ASSERT_TRUE(client.send(large_data));
  22743. std::string msg;
  22744. ASSERT_TRUE(client.read(msg));
  22745. EXPECT_EQ(large_data, msg);
  22746. client.close();
  22747. }
  22748. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22750. "/ws-echo");
  22751. ASSERT_TRUE(client.connect());
  22752. const int num_threads = 4;
  22753. std::vector<std::thread> threads;
  22754. std::atomic<int> send_count{0};
  22755. for (int t = 0; t < num_threads; t++) {
  22756. threads.emplace_back([&client, &send_count, t]() {
  22757. for (int i = 0; i < 5; i++) {
  22758. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22759. if (client.send(text)) { send_count++; }
  22760. }
  22761. });
  22762. }
  22763. for (auto &th : threads) {
  22764. th.join();
  22765. }
  22766. int received = 0;
  22767. std::string msg;
  22768. while (received < send_count.load()) {
  22769. if (!client.read(msg)) { break; }
  22770. received++;
  22771. }
  22772. EXPECT_EQ(send_count.load(), received);
  22773. client.close();
  22774. }
  22775. TEST_F(WebSocketIntegrationTest, ReadString) {
  22776. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22777. "/ws-echo-string");
  22778. ASSERT_TRUE(client.connect());
  22779. ASSERT_TRUE(client.send("hello"));
  22780. std::string msg;
  22781. ASSERT_TRUE(client.read(msg));
  22782. EXPECT_EQ("echo: hello", msg);
  22783. ASSERT_TRUE(client.send("world"));
  22784. ASSERT_TRUE(client.read(msg));
  22785. EXPECT_EQ("echo: world", msg);
  22786. client.close();
  22787. }
  22788. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22789. Headers headers = {{"X-Test-Header", "test-value"}};
  22790. ws::WebSocketClient client(
  22791. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22792. ASSERT_TRUE(client.connect());
  22793. std::string msg;
  22794. ASSERT_TRUE(client.read(msg));
  22795. EXPECT_EQ("path:/ws-request-info", msg);
  22796. ASSERT_TRUE(client.read(msg));
  22797. EXPECT_EQ("header:test-value", msg);
  22798. client.close();
  22799. }
  22800. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22801. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22802. "/ws-echo");
  22803. client.set_read_timeout(1, 0); // 1 second
  22804. ASSERT_TRUE(client.connect());
  22805. // Don't send anything — server echo handler waits for a message, so read()
  22806. // should time out. The connection survives it: nothing was consumed.
  22807. std::string msg;
  22808. EXPECT_EQ(client.read(msg), ws::Timeout);
  22809. EXPECT_TRUE(client.is_open());
  22810. // And it is still usable afterwards.
  22811. EXPECT_TRUE(client.send("after timeout"));
  22812. EXPECT_EQ(client.read(msg), ws::Text);
  22813. EXPECT_EQ(msg, "after timeout");
  22814. }
  22815. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22816. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22817. "/ws-echo");
  22818. client.set_read_timeout(1, 0);
  22819. ASSERT_TRUE(client.connect());
  22820. ASSERT_TRUE(client.send("first"));
  22821. std::string msg;
  22822. ASSERT_EQ(client.read(msg), ws::Text);
  22823. ASSERT_EQ(msg, "first");
  22824. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22825. // not be used with a read timeout: it would reprocess the previous message.
  22826. EXPECT_EQ(client.read(msg), ws::Timeout);
  22827. EXPECT_EQ(msg, "first");
  22828. }
  22829. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22830. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22831. "/ws-echo");
  22832. ASSERT_TRUE(client.connect());
  22833. // Setting it once the connection is open reaches the live stream, not just
  22834. // the seed for the next connect().
  22835. client.set_read_timeout(1, 0);
  22836. std::string msg;
  22837. EXPECT_EQ(client.read(msg), ws::Timeout);
  22838. EXPECT_TRUE(client.is_open());
  22839. }
  22840. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22841. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22842. "/ws-echo");
  22843. client.set_read_timeout(5, 0);
  22844. ASSERT_TRUE(client.connect());
  22845. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22846. // The server should reject it and close the connection.
  22847. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22848. client.send(oversized);
  22849. // The server's read() should have failed due to payload limit,
  22850. // so our read() should return false (connection closed).
  22851. std::string msg;
  22852. EXPECT_FALSE(client.read(msg));
  22853. }
  22854. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22855. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22856. "/ws-echo");
  22857. client.set_read_timeout(10, 0);
  22858. ASSERT_TRUE(client.connect());
  22859. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22860. // This should succeed.
  22861. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22862. ASSERT_TRUE(client.send(at_limit));
  22863. std::string msg;
  22864. ASSERT_TRUE(client.read(msg));
  22865. EXPECT_EQ(at_limit.size(), msg.size());
  22866. client.close();
  22867. }
  22868. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22870. "/nonexistent");
  22871. auto res = client.connect();
  22872. EXPECT_FALSE(res);
  22873. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22874. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22875. EXPECT_FALSE(client.is_open());
  22876. }
  22877. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22878. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22879. "/ws-echo");
  22880. ASSERT_TRUE(client.connect());
  22881. ASSERT_TRUE(client.send(""));
  22882. std::string msg;
  22883. EXPECT_EQ(ws::Text, client.read(msg));
  22884. EXPECT_EQ("", msg);
  22885. client.close();
  22886. }
  22887. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22889. "/ws-echo");
  22890. // First connection
  22891. ASSERT_TRUE(client.connect());
  22892. ASSERT_TRUE(client.send("first"));
  22893. std::string msg;
  22894. ASSERT_TRUE(client.read(msg));
  22895. EXPECT_EQ("first", msg);
  22896. client.close();
  22897. EXPECT_FALSE(client.is_open());
  22898. // Reconnect using the same client object
  22899. ASSERT_TRUE(client.connect());
  22900. ASSERT_TRUE(client.is_open());
  22901. ASSERT_TRUE(client.send("second"));
  22902. ASSERT_TRUE(client.read(msg));
  22903. EXPECT_EQ("second", msg);
  22904. client.close();
  22905. }
  22906. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22907. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22908. "/ws-close-status");
  22909. ASSERT_TRUE(client.connect());
  22910. // Trigger the server to close with GoingAway status
  22911. ASSERT_TRUE(client.send("trigger"));
  22912. // read() should return false after receiving the close frame
  22913. std::string msg;
  22914. EXPECT_FALSE(client.read(msg));
  22915. EXPECT_FALSE(client.is_open());
  22916. }
  22917. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22918. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22919. "/ws-echo");
  22920. ASSERT_TRUE(client.connect());
  22921. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22922. EXPECT_FALSE(client.is_open());
  22923. }
  22924. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22925. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22926. ws::WebSocketClient client(
  22927. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22928. ASSERT_TRUE(client.connect());
  22929. // Server should have selected graphql-ws
  22930. EXPECT_EQ("graphql-ws", client.subprotocol());
  22931. client.close();
  22932. }
  22933. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22934. Headers headers;
  22935. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22936. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22937. ws::WebSocketClient client(
  22938. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22939. ASSERT_TRUE(client.connect());
  22940. // The offer on the second field line counts too, so graphql-ws is selected
  22941. EXPECT_EQ("graphql-ws", client.subprotocol());
  22942. client.close();
  22943. }
  22944. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22945. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22946. ws::WebSocketClient client(
  22947. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22948. ASSERT_TRUE(client.connect());
  22949. // Server should not have selected any subprotocol
  22950. EXPECT_TRUE(client.subprotocol().empty());
  22951. client.close();
  22952. }
  22953. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22954. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22955. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22956. "/ws-subprotocol-unoffered",
  22957. headers);
  22958. ASSERT_TRUE(client.connect());
  22959. EXPECT_TRUE(client.subprotocol().empty());
  22960. client.close();
  22961. }
  22962. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22963. // Connect without requesting any subprotocol
  22964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22965. "/ws-subprotocol");
  22966. ASSERT_TRUE(client.connect());
  22967. EXPECT_TRUE(client.subprotocol().empty());
  22968. client.close();
  22969. }
  22970. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22972. "/ws-echo");
  22973. client.set_tcp_nodelay(true);
  22974. client.set_connection_timeout(3, 0);
  22975. bool socket_options_called = false;
  22976. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22977. ASSERT_TRUE(client.connect());
  22978. ASSERT_TRUE(client.is_open());
  22979. EXPECT_TRUE(socket_options_called);
  22980. ASSERT_TRUE(client.send("hello"));
  22981. std::string msg;
  22982. auto result = client.read(msg);
  22983. EXPECT_EQ(result, ws::ReadResult::Text);
  22984. EXPECT_EQ(msg, "hello");
  22985. client.close();
  22986. }
  22987. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22989. "/ws-echo");
  22990. client.set_connection_timeout(std::chrono::seconds(3));
  22991. client.set_write_timeout(std::chrono::seconds(3));
  22992. // A sub-second remainder exercises the seconds/microseconds split.
  22993. client.set_read_timeout(std::chrono::milliseconds(1500));
  22994. ASSERT_TRUE(client.connect());
  22995. auto start = std::chrono::steady_clock::now();
  22996. std::string msg;
  22997. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22998. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22999. std::chrono::steady_clock::now() - start)
  23000. .count();
  23001. // Above 1s so that dropping the microseconds half of the split fails here.
  23002. // Ignoring the setter altogether would not reach this line at all: a client
  23003. // waits forever by default.
  23004. EXPECT_GE(elapsed, 1400);
  23005. EXPECT_LT(elapsed, 30000);
  23006. }
  23007. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23008. Server svr;
  23009. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23010. if (!req.has_header("Authorization")) {
  23011. res.status = StatusCode::Unauthorized_401;
  23012. res.set_content("Unauthorized", "text/plain");
  23013. return Server::HandlerResponse::Handled;
  23014. }
  23015. return Server::HandlerResponse::Unhandled;
  23016. });
  23017. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23018. std::string msg;
  23019. while (ws.read(msg)) {
  23020. ws.send(msg);
  23021. }
  23022. });
  23023. auto port = svr.bind_to_any_port("localhost");
  23024. std::thread t([&]() { svr.listen_after_bind(); });
  23025. svr.wait_until_ready();
  23026. // Without Authorization header - should be rejected before upgrade
  23027. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23028. EXPECT_FALSE(client1.connect());
  23029. // The rejection is framed like any other HTTP response
  23030. {
  23031. Client cli("localhost", port);
  23032. Headers headers = {{"Upgrade", "websocket"},
  23033. {"Connection", "Upgrade"},
  23034. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23035. {"Sec-WebSocket-Version", "13"}};
  23036. auto res = cli.Get("/ws", headers);
  23037. ASSERT_TRUE(res);
  23038. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23039. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23040. EXPECT_EQ("Unauthorized", res->body);
  23041. }
  23042. // With Authorization header - should succeed
  23043. Headers headers = {{"Authorization", "Bearer token123"}};
  23044. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23045. headers);
  23046. ASSERT_TRUE(client2.connect());
  23047. ASSERT_TRUE(client2.send("hello"));
  23048. std::string msg;
  23049. ASSERT_TRUE(client2.read(msg));
  23050. EXPECT_EQ("hello", msg);
  23051. client2.close();
  23052. svr.stop();
  23053. t.join();
  23054. }
  23055. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23056. Server svr;
  23057. std::atomic<int> pre_routing_calls{0};
  23058. std::atomic<int> pre_request_calls{0};
  23059. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23060. pre_routing_calls++;
  23061. if (req.path == "/handled") {
  23062. res.set_content("handled", "text/plain");
  23063. return Server::HandlerResponse::Handled;
  23064. }
  23065. return Server::HandlerResponse::Unhandled;
  23066. });
  23067. svr.set_pre_request_handler([&](const Request &, Response &) {
  23068. pre_request_calls++;
  23069. return Server::HandlerResponse::Unhandled;
  23070. });
  23071. svr.Get("/http", [](const Request &, Response &res) {
  23072. res.set_content("http", "text/plain");
  23073. });
  23074. svr.WebSocket("/ws",
  23075. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23076. auto port = svr.bind_to_any_port("localhost");
  23077. std::thread t([&]() { svr.listen_after_bind(); });
  23078. auto se = detail::scope_exit([&] {
  23079. svr.stop();
  23080. t.join();
  23081. });
  23082. svr.wait_until_ready();
  23083. Headers upgrade = {{"Upgrade", "websocket"},
  23084. {"Connection", "Upgrade"},
  23085. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23086. {"Sec-WebSocket-Version", "13"}};
  23087. auto get = [&](const char *path) {
  23088. pre_routing_calls = 0;
  23089. return Client("localhost", port).Get(path, upgrade);
  23090. };
  23091. // No WebSocket route, but an HTTP one
  23092. auto res = get("/http");
  23093. ASSERT_TRUE(res);
  23094. EXPECT_EQ(StatusCode::OK_200, res->status);
  23095. EXPECT_EQ("http", res->body);
  23096. EXPECT_EQ(1, pre_routing_calls);
  23097. EXPECT_EQ(1, pre_request_calls);
  23098. // No route at all
  23099. res = get("/none");
  23100. ASSERT_TRUE(res);
  23101. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23102. EXPECT_EQ(1, pre_routing_calls);
  23103. // Answered by the pre-routing handler
  23104. res = get("/handled");
  23105. ASSERT_TRUE(res);
  23106. EXPECT_EQ(StatusCode::OK_200, res->status);
  23107. EXPECT_EQ("handled", res->body);
  23108. EXPECT_EQ(1, pre_routing_calls);
  23109. // A WebSocket route
  23110. pre_routing_calls = 0;
  23111. pre_request_calls = 0;
  23112. {
  23113. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23114. "/ws");
  23115. ASSERT_TRUE(client.connect());
  23116. std::string msg;
  23117. ASSERT_TRUE(client.read(msg));
  23118. EXPECT_EQ("ws", msg);
  23119. client.close();
  23120. }
  23121. EXPECT_EQ(1, pre_routing_calls);
  23122. EXPECT_EQ(1, pre_request_calls);
  23123. }
  23124. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23125. Server svr;
  23126. std::atomic<int> pre_request_calls{0};
  23127. std::atomic<bool> route_matched{false};
  23128. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23129. pre_request_calls++;
  23130. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23131. if (req.get_header_value("Authorization") != "Bearer token123") {
  23132. res.status = StatusCode::Unauthorized_401;
  23133. res.set_content("Unauthorized", "text/plain");
  23134. return Server::HandlerResponse::Handled;
  23135. }
  23136. return Server::HandlerResponse::Unhandled;
  23137. });
  23138. std::atomic<bool> handler_called{false};
  23139. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23140. handler_called = true;
  23141. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23142. });
  23143. auto port = svr.bind_to_any_port("localhost");
  23144. std::thread t([&]() { svr.listen_after_bind(); });
  23145. svr.wait_until_ready();
  23146. // Without Authorization header - should be rejected before upgrade
  23147. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23148. "/ws/1");
  23149. EXPECT_FALSE(client1.connect());
  23150. EXPECT_FALSE(handler_called);
  23151. EXPECT_EQ(1, pre_request_calls);
  23152. EXPECT_TRUE(route_matched);
  23153. // The rejection is an ordinary HTTP response, not a protocol switch
  23154. {
  23155. Client cli("localhost", port);
  23156. Headers headers = {{"Upgrade", "websocket"},
  23157. {"Connection", "Upgrade"},
  23158. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23159. {"Sec-WebSocket-Version", "13"}};
  23160. auto res = cli.Get("/ws/1", headers);
  23161. ASSERT_TRUE(res);
  23162. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23163. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23164. EXPECT_EQ("Unauthorized", res->body);
  23165. }
  23166. EXPECT_FALSE(handler_called);
  23167. // With Authorization header - should succeed
  23168. Headers headers = {{"Authorization", "Bearer token123"}};
  23169. ws::WebSocketClient client2(
  23170. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23171. ASSERT_TRUE(client2.connect());
  23172. std::string msg;
  23173. ASSERT_TRUE(client2.read(msg));
  23174. EXPECT_EQ("/ws/:id 2", msg);
  23175. EXPECT_TRUE(handler_called);
  23176. client2.close();
  23177. svr.stop();
  23178. t.join();
  23179. }
  23180. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23181. Server svr;
  23182. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23183. // A read timeout is how a handler gets control back. Without it, a handler
  23184. // parked in read() can never write on the connection it is reading.
  23185. ws.set_read_timeout(std::chrono::milliseconds(100));
  23186. std::string msg;
  23187. while (ws.is_open()) {
  23188. auto r = ws.read(msg);
  23189. if (r == httplib::ws::Timeout) {
  23190. ws.send("tick");
  23191. continue;
  23192. }
  23193. if (r == httplib::ws::Fail) { break; }
  23194. ws.send(msg);
  23195. }
  23196. });
  23197. auto port = svr.bind_to_any_port("localhost");
  23198. std::thread t([&]() { svr.listen_after_bind(); });
  23199. svr.wait_until_ready();
  23200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23201. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23202. ASSERT_TRUE(client.connect());
  23203. // The client sends nothing, so anything it receives came out of the
  23204. // handler's timeout path.
  23205. std::string msg;
  23206. ASSERT_EQ(client.read(msg), ws::Text);
  23207. EXPECT_EQ("tick", msg);
  23208. client.close();
  23209. svr.stop();
  23210. t.join();
  23211. }
  23212. // Stream::read may return fewer bytes than asked for. This is that contract at
  23213. // its worst -- one byte per call -- which is what a frame header straddling a
  23214. // read buffer's boundary looks like to the frame parser.
  23215. class WsByteAtATimeStream : public Stream {
  23216. public:
  23217. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23218. bool is_readable() const override { return true; }
  23219. bool wait_readable() const override { return true; }
  23220. bool wait_writable() const override { return true; }
  23221. ssize_t read(char *ptr, size_t size) override {
  23222. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23223. *ptr = data_[pos_++];
  23224. return 1;
  23225. }
  23226. ssize_t write(const char *, size_t size) override {
  23227. return static_cast<ssize_t>(size);
  23228. }
  23229. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23230. ip = "127.0.0.1";
  23231. port = 0;
  23232. }
  23233. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23234. ip = "127.0.0.1";
  23235. port = 0;
  23236. }
  23237. socket_t socket() const override { return INVALID_SOCKET; }
  23238. time_t duration() const override { return 0; }
  23239. private:
  23240. std::string data_;
  23241. size_t pos_ = 0;
  23242. };
  23243. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23244. // The payload uses the 16-bit extended length, so the header, the length
  23245. // and the mask key are all multi-byte fields here. Each used to be read
  23246. // with a single read() call, which fails as soon as one is split. The
  23247. // payload is also a little over one read chunk, so it is read in two.
  23248. std::string body;
  23249. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23250. body += static_cast<char>(i % 251);
  23251. }
  23252. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23253. std::string frame;
  23254. frame += static_cast<char>(0x81); // FIN + Text
  23255. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23256. frame += static_cast<char>(body.size() >> 8);
  23257. frame += static_cast<char>(body.size() & 0xff);
  23258. for (size_t i = 0; i < 4; i++) {
  23259. frame += static_cast<char>(mask[i]);
  23260. }
  23261. for (size_t i = 0; i < body.size(); i++) {
  23262. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23263. }
  23264. WsByteAtATimeStream strm(frame);
  23265. ws::Opcode opcode;
  23266. std::string payload;
  23267. bool fin = false;
  23268. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23269. /*expect_masked=*/true, body.size()),
  23270. ws::impl::FrameRead::Ok);
  23271. EXPECT_TRUE(fin);
  23272. EXPECT_EQ(opcode, ws::Opcode::Text);
  23273. EXPECT_EQ(payload, body);
  23274. }
  23275. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23276. std::string body(2000, 'x');
  23277. std::string frame;
  23278. frame += static_cast<char>(0x82); // FIN + Binary
  23279. frame += static_cast<char>(126); // 16-bit length follows
  23280. frame += static_cast<char>(body.size() >> 8);
  23281. frame += static_cast<char>(body.size() & 0xff);
  23282. frame += body;
  23283. detail::BufferStream strm;
  23284. strm.write(frame.data(), frame.size());
  23285. ws::Opcode opcode;
  23286. std::string payload;
  23287. bool fin;
  23288. EXPECT_EQ(
  23289. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23290. ws::impl::FrameRead::Ok);
  23291. EXPECT_EQ(body, payload);
  23292. }
  23293. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23294. // The header announces the largest payload allowed, and only 3 bytes of it
  23295. // ever arrive.
  23296. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23297. std::string frame;
  23298. frame += static_cast<char>(0x82); // FIN + Binary
  23299. frame += static_cast<char>(127); // 64-bit length follows
  23300. for (int shift = 56; shift >= 0; shift -= 8) {
  23301. frame += static_cast<char>((len >> shift) & 0xff);
  23302. }
  23303. frame += "abc";
  23304. detail::BufferStream strm;
  23305. strm.write(frame.data(), frame.size());
  23306. ws::Opcode opcode;
  23307. std::string payload;
  23308. bool fin;
  23309. EXPECT_EQ(
  23310. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23311. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23312. ws::impl::FrameRead::Fail);
  23313. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23314. }
  23315. TEST(WebSocketTest, QueryStringInHandshake) {
  23316. Server svr;
  23317. std::mutex mtx;
  23318. std::string received_target;
  23319. std::string received_token;
  23320. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23321. {
  23322. std::lock_guard<std::mutex> lock(mtx);
  23323. received_target = req.target;
  23324. if (req.has_param("token")) {
  23325. received_token = req.get_param_value("token");
  23326. }
  23327. }
  23328. std::string msg;
  23329. while (ws.read(msg)) {
  23330. ws.send(msg);
  23331. }
  23332. });
  23333. auto port = svr.bind_to_any_port("localhost");
  23334. std::thread t([&]() { svr.listen_after_bind(); });
  23335. svr.wait_until_ready();
  23336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23337. "/ws?token=ABC&session=123");
  23338. ASSERT_TRUE(client.connect());
  23339. // Round-trip ensures the handler has run and captured the request.
  23340. ASSERT_TRUE(client.send("hello"));
  23341. std::string msg;
  23342. ASSERT_TRUE(client.read(msg));
  23343. EXPECT_EQ("hello", msg);
  23344. client.close();
  23345. {
  23346. std::lock_guard<std::mutex> lock(mtx);
  23347. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23348. EXPECT_EQ("ABC", received_token);
  23349. }
  23350. svr.stop();
  23351. t.join();
  23352. }
  23353. // Run a handshake against a throwaway server and hand the request the server
  23354. // received back to the caller, so tests can assert on the headers the client
  23355. // actually put on the wire.
  23356. static void capture_websocket_handshake_request(
  23357. const Headers &client_headers,
  23358. std::function<void(const Request &, int port)> verify) {
  23359. Server svr;
  23360. std::mutex mtx;
  23361. Request received;
  23362. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23363. {
  23364. std::lock_guard<std::mutex> lock(mtx);
  23365. received = req;
  23366. }
  23367. std::string msg;
  23368. while (ws.read(msg)) {
  23369. ws.send(msg);
  23370. }
  23371. });
  23372. auto port = svr.bind_to_any_port("localhost");
  23373. std::thread t([&]() { svr.listen_after_bind(); });
  23374. auto se = detail::scope_exit([&] {
  23375. svr.stop();
  23376. t.join();
  23377. });
  23378. svr.wait_until_ready();
  23379. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23380. client_headers);
  23381. ASSERT_TRUE(client.connect());
  23382. ASSERT_TRUE(client.send("hello"));
  23383. std::string msg;
  23384. ASSERT_TRUE(client.read(msg));
  23385. client.close();
  23386. {
  23387. std::lock_guard<std::mutex> lock(mtx);
  23388. verify(received, port);
  23389. }
  23390. }
  23391. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23392. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23393. // Non-default port must be present in the Host header. Default ports
  23394. // (80/443) are omitted; that logic is covered by
  23395. // MakeHostAndPortStringTest.
  23396. EXPECT_EQ("localhost:" + std::to_string(port),
  23397. req.get_header_value("Host"));
  23398. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23399. req.get_header_value("User-Agent"));
  23400. EXPECT_FALSE(req.has_header("Accept"));
  23401. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23402. EXPECT_FALSE(req.has_header("Content-Length"));
  23403. });
  23404. }
  23405. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23406. capture_websocket_handshake_request(
  23407. {{"Host", "example.com"},
  23408. {"User-Agent", "custom-agent"},
  23409. {"X-Custom", "value"}},
  23410. [](const Request &req, int) {
  23411. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23412. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23413. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23414. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23415. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23416. });
  23417. }
  23418. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23419. capture_websocket_handshake_request(
  23420. {{"Upgrade", "bogus"},
  23421. {"Connection", "close"},
  23422. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23423. {"Sec-WebSocket-Version", "8"}},
  23424. [](const Request &req, int) {
  23425. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23426. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23427. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23428. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23429. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23430. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23431. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23432. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23433. req.get_header_value("Sec-WebSocket-Key"));
  23434. });
  23435. }
  23436. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23437. // A header the client refuses to send must abort the handshake before any
  23438. // part of it reaches the wire; a lone request line would otherwise sit in
  23439. // the peer's buffer as a truncated request.
  23440. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23441. ASSERT_NE(INVALID_SOCKET, srv);
  23442. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23443. sockaddr_in addr{};
  23444. addr.sin_family = AF_INET;
  23445. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23447. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23448. ASSERT_EQ(0, ::listen(srv, 1));
  23449. sockaddr_in bound{};
  23450. socklen_t bound_len = sizeof(bound);
  23451. ASSERT_EQ(
  23452. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23453. auto port = ntohs(bound.sin_port);
  23454. ssize_t received = -1;
  23455. std::thread t([&] {
  23456. // Bound every blocking call so a regression fails the test with a bad
  23457. // value instead of hanging the suite.
  23458. fd_set rfds;
  23459. FD_ZERO(&rfds);
  23460. FD_SET(srv, &rfds);
  23461. timeval tv{5, 0};
  23462. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23463. 0) {
  23464. return;
  23465. }
  23466. sockaddr_in cli_addr{};
  23467. socklen_t cli_len = sizeof(cli_addr);
  23468. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23469. if (cli == INVALID_SOCKET) { return; }
  23470. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23471. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23472. char buf[4096];
  23473. received = ::recv(cli, buf, sizeof(buf), 0);
  23474. });
  23475. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23476. // connect() has already shut the socket down by the time it returns false,
  23477. // so the peer sees EOF without waiting for the client to be destroyed.
  23478. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23479. {{"X-Bad", "a\r\nInjected: 1"}});
  23480. EXPECT_FALSE(client.connect());
  23481. t.join();
  23482. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23483. EXPECT_EQ(0, received);
  23484. }
  23485. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23486. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23487. // contains "upgrade" as a substring is a different token and must not
  23488. // start a WebSocket handshake.
  23489. auto make_request = [](const std::vector<std::string> &connection_values) {
  23490. Request req;
  23491. req.method = "GET";
  23492. req.headers.emplace("Upgrade", "websocket");
  23493. for (const auto &value : connection_values) {
  23494. req.headers.emplace("Connection", value);
  23495. }
  23496. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23497. req.headers.emplace("Sec-WebSocket-Version", "13");
  23498. return req;
  23499. };
  23500. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23501. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23502. EXPECT_TRUE(
  23503. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23504. EXPECT_TRUE(
  23505. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23506. EXPECT_TRUE(
  23507. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23508. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23509. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23510. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23511. EXPECT_FALSE(
  23512. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23513. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23514. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23515. }
  23516. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23517. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23518. // asks recipients to match each protocol-name case-insensitively, and RFC
  23519. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23520. // client naming websocket alongside another protocol, or on a second field
  23521. // line, is offering websocket; a value that merely contains "websocket" as a
  23522. // substring is a different protocol name and is not.
  23523. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23524. Request req;
  23525. req.method = "GET";
  23526. for (const auto &value : upgrade_values) {
  23527. req.headers.emplace("Upgrade", value);
  23528. }
  23529. req.headers.emplace("Connection", "Upgrade");
  23530. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23531. req.headers.emplace("Sec-WebSocket-Version", "13");
  23532. return req;
  23533. };
  23534. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23535. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23536. EXPECT_TRUE(
  23537. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23538. EXPECT_TRUE(
  23539. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23540. EXPECT_TRUE(
  23541. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23542. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23543. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23544. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23545. EXPECT_FALSE(
  23546. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23547. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23548. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23549. }
  23550. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23551. Server svr;
  23552. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23553. auto port = svr.bind_to_any_port("localhost");
  23554. std::thread t([&]() { svr.listen_after_bind(); });
  23555. auto se = detail::scope_exit([&] {
  23556. svr.stop();
  23557. t.join();
  23558. });
  23559. svr.wait_until_ready();
  23560. Headers headers = {{"Upgrade", "websocket"},
  23561. {"Connection", "notupgrade"},
  23562. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23563. {"Sec-WebSocket-Version", "13"}};
  23564. Client cli("localhost", port);
  23565. auto res = cli.Get("/ws", headers);
  23566. // The route exists only as a WebSocket route, so a request that fails the
  23567. // handshake check falls through to ordinary routing.
  23568. ASSERT_TRUE(res);
  23569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23570. }
  23571. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23572. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23573. // Connection value is the only thing left for the client to reject.
  23574. Server svr;
  23575. svr.Get("/ws", [](const Request &req, Response &res) {
  23576. res.status = StatusCode::SwitchingProtocol_101;
  23577. res.set_header("Upgrade", "websocket");
  23578. res.set_header("Connection", "notupgrade");
  23579. res.set_header("Sec-WebSocket-Accept",
  23580. detail::websocket_accept_key(
  23581. req.get_header_value("Sec-WebSocket-Key")));
  23582. });
  23583. auto port = svr.bind_to_any_port("localhost");
  23584. std::thread t([&]() { svr.listen_after_bind(); });
  23585. auto se = detail::scope_exit([&] {
  23586. svr.stop();
  23587. t.join();
  23588. });
  23589. svr.wait_until_ready();
  23590. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23591. auto res = client.connect();
  23592. EXPECT_FALSE(res);
  23593. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23594. EXPECT_FALSE(client.is_open());
  23595. }
  23596. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23597. Server svr;
  23598. svr.Get("/ws", [](const Request &req, Response &res) {
  23599. res.status = StatusCode::SwitchingProtocol_101;
  23600. res.set_header("Upgrade", "websocket");
  23601. res.set_header("Connection", "Upgrade");
  23602. res.set_header("Sec-WebSocket-Accept",
  23603. detail::websocket_accept_key(
  23604. req.get_header_value("Sec-WebSocket-Key")));
  23605. res.set_header("Sec-WebSocket-Protocol", "admin");
  23606. });
  23607. auto port = svr.bind_to_any_port("localhost");
  23608. std::thread t([&]() { svr.listen_after_bind(); });
  23609. auto se = detail::scope_exit([&] {
  23610. svr.stop();
  23611. t.join();
  23612. });
  23613. svr.wait_until_ready();
  23614. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23615. // Server selects a subprotocol the client never offered
  23616. {
  23617. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23618. ws::WebSocketClient client(url, headers);
  23619. auto res = client.connect();
  23620. EXPECT_FALSE(res);
  23621. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23622. EXPECT_FALSE(client.is_open());
  23623. EXPECT_TRUE(client.subprotocol().empty());
  23624. }
  23625. // Client offered none but the server named one anyway
  23626. {
  23627. ws::WebSocketClient client(url);
  23628. auto res = client.connect();
  23629. EXPECT_FALSE(res);
  23630. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23631. EXPECT_FALSE(client.is_open());
  23632. EXPECT_TRUE(client.subprotocol().empty());
  23633. }
  23634. }
  23635. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23636. // The socket path doubles as the URL host, so it must not contain '/'.
  23637. const char *shard = getenv("GTEST_SHARD_INDEX");
  23638. const std::string sock_path =
  23639. shard ? std::string("httplib-ws-") + shard + ".sock"
  23640. : std::string("httplib-ws.sock");
  23641. std::remove(sock_path.c_str());
  23642. Server svr;
  23643. std::mutex mtx;
  23644. std::string received_host;
  23645. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23646. {
  23647. std::lock_guard<std::mutex> lock(mtx);
  23648. received_host = req.get_header_value("Host");
  23649. }
  23650. std::string msg;
  23651. while (ws.read(msg)) {
  23652. ws.send(msg);
  23653. }
  23654. });
  23655. svr.set_address_family(AF_UNIX);
  23656. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23657. auto se = detail::scope_exit([&] {
  23658. svr.stop();
  23659. t.join();
  23660. std::remove(sock_path.c_str());
  23661. });
  23662. svr.wait_until_ready();
  23663. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23664. client.set_address_family(AF_UNIX);
  23665. ASSERT_TRUE(client.connect());
  23666. ASSERT_TRUE(client.send("hello"));
  23667. std::string msg;
  23668. ASSERT_TRUE(client.read(msg));
  23669. client.close();
  23670. {
  23671. std::lock_guard<std::mutex> lock(mtx);
  23672. // There is no host:port for a Unix socket, so the same "localhost"
  23673. // placeholder the HTTP client uses is expected.
  23674. EXPECT_EQ("localhost", received_host);
  23675. }
  23676. }
  23677. // Two threads must never parse WebSocket frames from the same stream.
  23678. // close() used to read the peer's Close reply with its own frame read, so it
  23679. // raced a reader thread that was in the middle of a payload: the payload loop
  23680. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23681. // so bytes taken by close() were replaced with bytes from further along the
  23682. // stream. The message kept its length and silently changed content.
  23683. //
  23684. // The raw peer below sends a frame header plus part of the payload, waits for
  23685. // the handler to call close(), and only then sends the rest. Whichever thread
  23686. // would win the race for those bytes, the message must arrive intact, because
  23687. // close() must not touch the stream while read() owns it.
  23688. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23689. #ifndef _WIN32
  23690. signal(SIGPIPE, SIG_IGN);
  23691. #endif
  23692. const size_t payload_len = 120; // fits the 7-bit length field
  23693. const size_t prefix_len = 8;
  23694. const int attempts = 8;
  23695. std::string expected(payload_len, '\0');
  23696. for (size_t i = 0; i < payload_len; i++) {
  23697. expected[i] = static_cast<char>('a' + i % 26);
  23698. }
  23699. std::atomic<bool> peer_stalled{false};
  23700. std::atomic<bool> handler_done{false};
  23701. std::mutex received_mutex;
  23702. std::vector<std::string> received;
  23703. // Bound every wait, so a regression fails the test instead of hanging the
  23704. // suite.
  23705. auto wait_for = [](const std::atomic<bool> &flag) {
  23706. for (int i = 0; i < 500 && !flag; i++) {
  23707. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23708. }
  23709. };
  23710. Server svr;
  23711. svr.set_websocket_ping_interval(0);
  23712. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23713. std::thread reader([&]() {
  23714. std::string msg;
  23715. while (ws.read(msg)) {
  23716. std::lock_guard<std::mutex> guard(received_mutex);
  23717. received.push_back(msg);
  23718. }
  23719. });
  23720. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23721. // inside read_websocket_frame() when close() runs.
  23722. wait_for(peer_stalled);
  23723. ws.close();
  23724. reader.join();
  23725. handler_done = true;
  23726. });
  23727. auto port = svr.bind_to_any_port("127.0.0.1");
  23728. std::thread t([&]() { svr.listen_after_bind(); });
  23729. auto se = detail::scope_exit([&] {
  23730. svr.stop();
  23731. t.join();
  23732. });
  23733. svr.wait_until_ready();
  23734. auto send_bytes = [](socket_t s, const std::string &data) {
  23735. #ifdef _WIN32
  23736. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23737. #else
  23738. auto n = ::send(s, data.data(), data.size(), 0);
  23739. #endif
  23740. return n == static_cast<decltype(n)>(data.size());
  23741. };
  23742. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23743. // Every length used here fits the 7-bit length field.
  23744. auto masked_header = [](uint8_t first_byte, size_t len) {
  23745. std::string h;
  23746. h += static_cast<char>(first_byte);
  23747. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23748. h.append(4, '\0'); // mask key
  23749. return h;
  23750. };
  23751. for (int attempt = 0; attempt < attempts; attempt++) {
  23752. peer_stalled = false;
  23753. handler_done = false;
  23754. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23755. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23756. auto se_sock = detail::scope_exit([&] {
  23757. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23758. });
  23759. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23760. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23761. sockaddr_in addr{};
  23762. addr.sin_family = AF_INET;
  23763. addr.sin_port = htons(static_cast<uint16_t>(port));
  23764. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23765. ASSERT_EQ(
  23766. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23767. << "attempt " << attempt;
  23768. ASSERT_TRUE(send_bytes(sock,
  23769. "GET /ws HTTP/1.1\r\n"
  23770. "Host: 127.0.0.1\r\n"
  23771. "Upgrade: websocket\r\n"
  23772. "Connection: Upgrade\r\n"
  23773. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23774. "Sec-WebSocket-Version: 13\r\n"
  23775. "\r\n"))
  23776. << "attempt " << attempt;
  23777. std::string response;
  23778. while (response.find("\r\n\r\n") == std::string::npos) {
  23779. char buf[512];
  23780. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23781. if (n <= 0) { break; }
  23782. response.append(buf, static_cast<size_t>(n));
  23783. }
  23784. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23785. << "attempt " << attempt;
  23786. // Send the header of a Binary message but only the first prefix_len bytes
  23787. // of its payload, leaving the reader thread stalled inside the payload.
  23788. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23789. expected.substr(0, prefix_len)))
  23790. << "attempt " << attempt;
  23791. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23792. peer_stalled = true;
  23793. // Let close() send its Close frame and park in its own read before the
  23794. // rest of the payload arrives, so both threads are waiting for it.
  23795. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23796. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23797. close_frame += static_cast<char>(0x03); // status 1000
  23798. close_frame += static_cast<char>(0xE8);
  23799. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23800. << "attempt " << attempt;
  23801. // Closing the peer releases the reader thread even on the buggy path,
  23802. // where it waits for bytes another thread already consumed.
  23803. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23804. detail::close_socket(sock);
  23805. sock = INVALID_SOCKET;
  23806. wait_for(handler_done);
  23807. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23808. }
  23809. std::lock_guard<std::mutex> guard(received_mutex);
  23810. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23811. << "a message in flight when close() ran was dropped";
  23812. for (size_t i = 0; i < received.size(); i++) {
  23813. EXPECT_EQ(expected, received[i]) << "message " << i;
  23814. }
  23815. }
  23816. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23817. // returning the socket, or INVALID_SOCKET.
  23818. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23819. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23820. if (sock == INVALID_SOCKET) { return sock; }
  23821. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23822. sockaddr_in addr{};
  23823. addr.sin_family = AF_INET;
  23824. addr.sin_port = htons(static_cast<uint16_t>(port));
  23825. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23826. std::string req = "GET " + path +
  23827. " HTTP/1.1\r\n"
  23828. "Host: 127.0.0.1\r\n"
  23829. "Upgrade: websocket\r\n"
  23830. "Connection: Upgrade\r\n"
  23831. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23832. "Sec-WebSocket-Version: 13\r\n"
  23833. "\r\n";
  23834. std::string res;
  23835. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23836. detail::send_socket(sock, req.data(), req.size(), 0) ==
  23837. static_cast<ssize_t>(req.size())) {
  23838. char c;
  23839. while (res.find("\r\n\r\n") == std::string::npos &&
  23840. ::recv(sock, &c, 1, 0) == 1) {
  23841. res += c;
  23842. }
  23843. }
  23844. if (res.find(" 101 ") == std::string::npos) {
  23845. detail::close_socket(sock);
  23846. return INVALID_SOCKET;
  23847. }
  23848. return sock;
  23849. }
  23850. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23851. // The payload must fit the 7-bit length field.
  23852. static std::string masked_frame(uint8_t first_byte,
  23853. const std::string &payload) {
  23854. std::string f;
  23855. f += static_cast<char>(first_byte);
  23856. f += static_cast<char>(0x80 | payload.size());
  23857. f.append(4, '\0');
  23858. return f + payload;
  23859. }
  23860. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23861. std::atomic<bool> done{false};
  23862. std::string received;
  23863. Server svr;
  23864. svr.set_websocket_ping_interval(0);
  23865. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23866. std::string msg;
  23867. if (ws.read(msg) == ws::Binary) { received = msg; }
  23868. done = true;
  23869. });
  23870. auto port = svr.bind_to_any_port("127.0.0.1");
  23871. std::thread t([&]() { svr.listen_after_bind(); });
  23872. auto se = detail::scope_exit([&] {
  23873. svr.stop();
  23874. t.join();
  23875. });
  23876. svr.wait_until_ready();
  23877. auto sock = connect_raw_websocket(port, "/ws");
  23878. ASSERT_NE(INVALID_SOCKET, sock);
  23879. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23880. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23881. masked_frame(0x89, "p") + // FIN + Ping
  23882. masked_frame(0x80, "lo"); // FIN + Continuation
  23883. detail::send_socket(sock, frames.data(), frames.size(), 0);
  23884. for (int i = 0; i < 500 && !done; i++) {
  23885. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23886. }
  23887. ASSERT_TRUE(done);
  23888. EXPECT_EQ("Hello", received);
  23889. // The Ping between the fragments is answered with a Pong.
  23890. char pong[3];
  23891. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23892. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23893. }
  23894. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23895. Server svr;
  23896. svr.set_websocket_ping_interval(-1);
  23897. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23898. std::string msg;
  23899. while (ws.read(msg)) {}
  23900. });
  23901. auto port = svr.bind_to_any_port("127.0.0.1");
  23902. std::thread t([&]() { svr.listen_after_bind(); });
  23903. auto se = detail::scope_exit([&] {
  23904. svr.stop();
  23905. t.join();
  23906. });
  23907. svr.wait_until_ready();
  23908. auto sock = connect_raw_websocket(port, "/ws");
  23909. ASSERT_NE(INVALID_SOCKET, sock);
  23910. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23911. // Nothing comes while the client stays quiet.
  23912. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23913. char c;
  23914. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23915. }
  23916. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23917. Server svr;
  23918. svr.set_websocket_ping_interval(0);
  23919. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23920. std::string msg;
  23921. while (ws.read(msg)) {}
  23922. });
  23923. auto port = svr.bind_to_any_port("127.0.0.1");
  23924. std::thread t([&]() { svr.listen_after_bind(); });
  23925. auto se = detail::scope_exit([&] {
  23926. svr.stop();
  23927. t.join();
  23928. });
  23929. svr.wait_until_ready();
  23930. // Each Close payload and the reply it should get: an echo when valid, 1002
  23931. // otherwise.
  23932. std::vector<std::pair<std::string, std::string>> cases = {
  23933. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23934. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23935. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23936. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23937. };
  23938. // Also between the fragments of a message.
  23939. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23940. for (const auto &c : cases) {
  23941. auto sock = connect_raw_websocket(port, "/ws");
  23942. ASSERT_NE(INVALID_SOCKET, sock);
  23943. auto frames = prefix + masked_frame(0x88, c.first);
  23944. detail::send_socket(sock, frames.data(), frames.size(), 0);
  23945. std::string reply;
  23946. char buf[256];
  23947. while (reply.size() < 2 + c.second.size()) {
  23948. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23949. if (n <= 0) { break; }
  23950. reply.append(buf, static_cast<size_t>(n));
  23951. }
  23952. detail::close_socket(sock);
  23953. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23954. c.second,
  23955. reply);
  23956. }
  23957. }
  23958. }
  23959. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23960. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23961. protected:
  23962. void SetUp() override {
  23963. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23964. SERVER_PRIVATE_KEY_FILE);
  23965. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23966. std::string msg;
  23967. ws::ReadResult ret;
  23968. while ((ret = ws.read(msg))) {
  23969. if (ret == ws::Binary) {
  23970. ws.send(msg.data(), msg.size());
  23971. } else {
  23972. ws.send(msg);
  23973. }
  23974. }
  23975. });
  23976. port_ = server_->bind_to_any_port(HOST);
  23977. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23978. server_->wait_until_ready();
  23979. }
  23980. void TearDown() override {
  23981. server_->stop();
  23982. if (server_thread_.joinable()) { server_thread_.join(); }
  23983. }
  23984. std::unique_ptr<SSLServer> server_;
  23985. std::thread server_thread_;
  23986. int port_ = 0;
  23987. };
  23988. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23989. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23990. {
  23991. ws::WebSocketClient client(url);
  23992. client.enable_server_certificate_verification(false);
  23993. auto calls = 0;
  23994. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23995. calls++;
  23996. return false;
  23997. });
  23998. EXPECT_FALSE(client.connect());
  23999. EXPECT_GT(calls, 0);
  24000. }
  24001. {
  24002. ws::WebSocketClient client(url);
  24003. client.enable_server_certificate_verification(false);
  24004. client.set_session_verifier([](tls::session_t) {
  24005. return SSLVerifierResponse::CertificateRejected;
  24006. });
  24007. EXPECT_FALSE(client.connect());
  24008. }
  24009. {
  24010. ws::WebSocketClient client(url);
  24011. client.enable_server_certificate_verification(false);
  24012. client.set_session_verifier([](tls::session_t) {
  24013. return SSLVerifierResponse::CertificateAccepted;
  24014. });
  24015. EXPECT_TRUE(client.connect());
  24016. }
  24017. }
  24018. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24019. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24020. "/ws-echo");
  24021. client.enable_server_certificate_verification(false);
  24022. ASSERT_TRUE(client.connect());
  24023. ASSERT_TRUE(client.is_open());
  24024. ASSERT_TRUE(client.send("Hello WSS"));
  24025. std::string msg;
  24026. EXPECT_EQ(ws::Text, client.read(msg));
  24027. EXPECT_EQ("Hello WSS", msg);
  24028. client.close();
  24029. }
  24030. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24031. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24032. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24033. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24034. // client (without calling close() first) is the only path that runs
  24035. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24036. // bug exactly.
  24037. //
  24038. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24039. // when linked against an instrumented libssl; run under Valgrind to catch it
  24040. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24041. // suite (the freed session otherwise stalls on the close handshake) — this test
  24042. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24043. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24044. {
  24045. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24046. "/ws-echo");
  24047. client.enable_server_certificate_verification(false);
  24048. client.set_read_timeout(2, 0);
  24049. client.set_write_timeout(2, 0);
  24050. ASSERT_TRUE(client.connect());
  24051. ASSERT_TRUE(client.is_open());
  24052. ASSERT_TRUE(client.send("still open"));
  24053. // Intentionally do NOT call client.close(): leaving scope runs
  24054. // shutdown_and_close() with the WebSocket still open, which must send the
  24055. // close frame while the TLS session is still alive.
  24056. }
  24057. }
  24058. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24059. // shutdown_and_close() at the start of connect(), reproducing the same
  24060. // use-after-free within the test body rather than at scope exit. The second
  24061. // connect must succeed and echo, proving the close handshake ran over a live
  24062. // session. See the note above about memory-tool requirements.
  24063. TEST_F(WebSocketSSLIntegrationTest,
  24064. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24065. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24066. "/ws-echo");
  24067. client.enable_server_certificate_verification(false);
  24068. client.set_read_timeout(2, 0);
  24069. client.set_write_timeout(2, 0);
  24070. ASSERT_TRUE(client.connect());
  24071. ASSERT_TRUE(client.is_open());
  24072. ASSERT_TRUE(client.send("still open"));
  24073. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24074. // the still-open connection, which must not touch a freed TLS session.
  24075. ASSERT_TRUE(client.connect());
  24076. ASSERT_TRUE(client.is_open());
  24077. ASSERT_TRUE(client.send("after reconnect"));
  24078. std::string msg;
  24079. EXPECT_EQ(ws::Text, client.read(msg));
  24080. EXPECT_EQ("after reconnect", msg);
  24081. client.close();
  24082. }
  24083. #endif
  24084. #ifdef CPPHTTPLIB_SSL_ENABLED
  24085. class WebSocketSSLCATest : public ::testing::Test {
  24086. protected:
  24087. void SetUp() override {
  24088. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24089. SERVER_PRIVATE_KEY_FILE);
  24090. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24091. std::string msg;
  24092. while (ws.read(msg)) {
  24093. ws.send(msg);
  24094. }
  24095. });
  24096. port_ = server_->bind_to_any_port("127.0.0.1");
  24097. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24098. server_->wait_until_ready();
  24099. }
  24100. void TearDown() override {
  24101. server_->stop();
  24102. if (server_thread_.joinable()) { server_thread_.join(); }
  24103. }
  24104. std::string url() const {
  24105. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24106. }
  24107. std::unique_ptr<SSLServer> server_;
  24108. std::thread server_thread_;
  24109. int port_ = 0;
  24110. };
  24111. // A custom CA loaded as PEM verifies the server with full certificate
  24112. // verification enabled
  24113. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24114. ws::WebSocketClient client(url());
  24115. std::string cert;
  24116. read_file(SERVER_CERT2_FILE, cert);
  24117. client.load_ca_cert_store(cert.c_str(), cert.size());
  24118. ASSERT_TRUE(client.connect());
  24119. ASSERT_TRUE(client.send("hello"));
  24120. std::string msg;
  24121. EXPECT_EQ(ws::Text, client.read(msg));
  24122. EXPECT_EQ("hello", msg);
  24123. client.close();
  24124. }
  24125. // A custom CA that does not cover the server must fail verification (the
  24126. // custom CA is exclusive; system certs are not loaded alongside it)
  24127. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24128. ws::WebSocketClient client(url());
  24129. std::string cert;
  24130. read_file(CLIENT_CA_CERT_FILE, cert);
  24131. client.load_ca_cert_store(cert.c_str(), cert.size());
  24132. auto res = client.connect();
  24133. ASSERT_FALSE(res);
  24134. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24135. EXPECT_EQ(-1, res.status());
  24136. EXPECT_NE(0u, res.ssl_backend_error());
  24137. }
  24138. // The same CA as a file path rather than PEM in memory
  24139. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24140. ws::WebSocketClient client(url());
  24141. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24142. ASSERT_TRUE(client.connect());
  24143. ASSERT_TRUE(client.send("hello"));
  24144. std::string msg;
  24145. EXPECT_EQ(ws::Text, client.read(msg));
  24146. EXPECT_EQ("hello", msg);
  24147. client.close();
  24148. }
  24149. // ...and a CA file that does not cover the server still fails, so it is the
  24150. // path above that decides the outcome
  24151. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24152. ws::WebSocketClient client(url());
  24153. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24154. ASSERT_FALSE(client.connect());
  24155. }
  24156. // Regression test: reconnecting with a native custom CA store used to reuse
  24157. // a store handle the previous TLS context had already freed (use-after-free
  24158. // under the OpenSSL backend). The context now lives as long as the client.
  24159. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24160. ws::WebSocketClient client(url());
  24161. std::string cert;
  24162. read_file(SERVER_CERT2_FILE, cert);
  24163. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24164. ASSERT_TRUE(client.connect());
  24165. client.close();
  24166. ASSERT_TRUE(client.connect());
  24167. ASSERT_TRUE(client.send("again"));
  24168. std::string msg;
  24169. EXPECT_EQ(ws::Text, client.read(msg));
  24170. EXPECT_EQ("again", msg);
  24171. client.close();
  24172. }
  24173. // Regression test: a certificate with a trusted chain but no identity match
  24174. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24175. // verification entirely for IP hosts, so this connection succeeded there.
  24176. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24177. // chain verification while the identity check must still fail.
  24178. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24179. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24180. ASSERT_TRUE(svr.is_valid());
  24181. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24182. std::string msg;
  24183. while (ws.read(msg)) {
  24184. ws.send(msg);
  24185. }
  24186. });
  24187. auto port = svr.bind_to_any_port("127.0.0.1");
  24188. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24189. auto se = detail::scope_exit([&] {
  24190. svr.stop();
  24191. t.join();
  24192. });
  24193. svr.wait_until_ready();
  24194. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24195. "/echo");
  24196. std::string cert;
  24197. read_file(SERVER_CERT_FILE, cert);
  24198. client.load_ca_cert_store(cert.c_str(), cert.size());
  24199. ASSERT_FALSE(client.connect());
  24200. }
  24201. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24202. // SNI, so nothing binds the host name to the TLS session. These bind the
  24203. // server to "localhost" instead, the only shape that exercises the SNI and
  24204. // hostname-verification path with certificate verification left enabled.
  24205. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24206. protected:
  24207. void Start(const char *cert_file) {
  24208. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24209. SERVER_PRIVATE_KEY_FILE);
  24210. ASSERT_TRUE(server_->is_valid());
  24211. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24212. std::string msg;
  24213. while (ws.read(msg)) {
  24214. ws.send(msg);
  24215. }
  24216. });
  24217. port_ = server_->bind_to_any_port("localhost");
  24218. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24219. server_->wait_until_ready();
  24220. }
  24221. void TearDown() override {
  24222. if (server_) { server_->stop(); }
  24223. if (server_thread_.joinable()) { server_thread_.join(); }
  24224. }
  24225. std::string url() const {
  24226. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24227. }
  24228. std::unique_ptr<SSLServer> server_;
  24229. std::thread server_thread_;
  24230. int port_ = 0;
  24231. };
  24232. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24233. // out and the connection is usable
  24234. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24235. Start(SERVER_CERT2_FILE);
  24236. ws::WebSocketClient client(url());
  24237. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24238. ASSERT_TRUE(client.connect());
  24239. ASSERT_TRUE(client.send("hello"));
  24240. std::string msg;
  24241. EXPECT_EQ(ws::Text, client.read(msg));
  24242. EXPECT_EQ("hello", msg);
  24243. client.close();
  24244. }
  24245. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24246. // while the identity check must still reject "localhost"
  24247. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24248. Start(SERVER_CERT_FILE);
  24249. ws::WebSocketClient client(url());
  24250. client.set_ca_cert_path(SERVER_CERT_FILE);
  24251. auto res = client.connect();
  24252. ASSERT_FALSE(res);
  24253. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24254. EXPECT_EQ(-1, res.status());
  24255. }
  24256. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24257. // disabled: the chain is still checked, only the identity check is skipped
  24258. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24259. Start(SERVER_CERT_FILE);
  24260. ws::WebSocketClient client(url());
  24261. client.set_ca_cert_path(SERVER_CERT_FILE);
  24262. client.enable_server_hostname_verification(false);
  24263. ASSERT_TRUE(client.connect());
  24264. ASSERT_TRUE(client.send("hello"));
  24265. std::string msg;
  24266. EXPECT_EQ(ws::Text, client.read(msg));
  24267. EXPECT_EQ("hello", msg);
  24268. client.close();
  24269. }
  24270. // A CA that did not sign the server certificate fails the chain, even though
  24271. // the name would match
  24272. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24273. Start(SERVER_CERT2_FILE);
  24274. ws::WebSocketClient client(url());
  24275. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24276. ASSERT_FALSE(client.connect());
  24277. }
  24278. // With verification disabled, neither the chain nor the name is checked
  24279. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24280. Start(SERVER_CERT_FILE);
  24281. ws::WebSocketClient client(url());
  24282. client.enable_server_certificate_verification(false);
  24283. ASSERT_TRUE(client.connect());
  24284. ASSERT_TRUE(client.send("hello"));
  24285. std::string msg;
  24286. EXPECT_EQ(ws::Text, client.read(msg));
  24287. EXPECT_EQ("hello", msg);
  24288. client.close();
  24289. }
  24290. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24291. protected:
  24292. void SetUp() override {
  24293. server_ = httplib::detail::make_unique<SSLServer>(
  24294. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24295. ASSERT_TRUE(server_->is_valid());
  24296. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24297. std::string msg;
  24298. while (ws.read(msg)) {
  24299. ws.send(msg);
  24300. }
  24301. });
  24302. port_ = server_->bind_to_any_port("localhost");
  24303. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24304. server_->wait_until_ready();
  24305. }
  24306. void TearDown() override {
  24307. server_->stop();
  24308. if (server_thread_.joinable()) { server_thread_.join(); }
  24309. }
  24310. std::string url() const {
  24311. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24312. }
  24313. void ConnectWithClientCert(const std::string &client_cert_file,
  24314. const std::string &client_private_key_file,
  24315. const char *private_key_password) {
  24316. std::string cert_pem, key_pem;
  24317. read_file(client_cert_file, cert_pem);
  24318. read_file(client_private_key_file, key_pem);
  24319. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24320. key_pem.c_str(), key_pem.size(),
  24321. private_key_password};
  24322. ConnectWithPem(pem);
  24323. }
  24324. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24325. ws::WebSocketClient client(url(), pem);
  24326. ASSERT_TRUE(client.is_valid());
  24327. client.enable_server_certificate_verification(false);
  24328. ASSERT_TRUE(client.connect());
  24329. ASSERT_TRUE(client.send("hello"));
  24330. std::string msg;
  24331. EXPECT_EQ(ws::Text, client.read(msg));
  24332. EXPECT_EQ("hello", msg);
  24333. client.close();
  24334. }
  24335. std::unique_ptr<SSLServer> server_;
  24336. std::thread server_thread_;
  24337. int port_ = 0;
  24338. };
  24339. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24340. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24341. }
  24342. // Control for the tests above: the fixture's server really does require a
  24343. // client certificate, so it is the PEM the constructor installed that decides
  24344. // the outcome.
  24345. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24346. ws::WebSocketClient client(url());
  24347. ASSERT_TRUE(client.is_valid());
  24348. client.enable_server_certificate_verification(false);
  24349. EXPECT_FALSE(client.connect());
  24350. }
  24351. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24352. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24353. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24354. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24355. }
  24356. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24357. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24358. std::string cert_pem, key_pem;
  24359. read_file(CLIENT_CERT_FILE, cert_pem);
  24360. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24361. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24362. std::vector<char> key(key_pem.begin(), key_pem.end());
  24363. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24364. key.size(), nullptr};
  24365. ConnectWithPem(pem);
  24366. }
  24367. #endif
  24368. #if !defined(_WIN32)
  24369. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24370. auto secret_dir = std::string("./symlink_test_secret");
  24371. auto served_dir = std::string("./symlink_test_served");
  24372. auto secret_file = secret_dir + "/secret.txt";
  24373. auto symlink_path = served_dir + "/escape";
  24374. // Setup: create directories and files
  24375. mkdir(secret_dir.c_str(), 0755);
  24376. mkdir(served_dir.c_str(), 0755);
  24377. {
  24378. std::ofstream ofs(secret_file);
  24379. ofs << "SECRET_DATA";
  24380. }
  24381. // Create symlink using absolute path so it resolves correctly
  24382. #ifdef PATH_MAX
  24383. char abs_secret[PATH_MAX];
  24384. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24385. #else
  24386. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24387. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24388. ASSERT_NE(nullptr, abs_secret);
  24389. #endif
  24390. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24391. auto se = detail::scope_exit([&] {
  24392. unlink(symlink_path.c_str());
  24393. unlink(secret_file.c_str());
  24394. rmdir(served_dir.c_str());
  24395. rmdir(secret_dir.c_str());
  24396. });
  24397. Server svr;
  24398. svr.set_mount_point("/", served_dir);
  24399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24400. auto se2 = detail::scope_exit([&] {
  24401. svr.stop();
  24402. listen_thread.join();
  24403. });
  24404. svr.wait_until_ready();
  24405. Client cli("localhost", PORT);
  24406. // Symlink pointing outside base dir should be blocked
  24407. auto res = cli.Get("/escape/secret.txt");
  24408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24409. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24410. }
  24411. #endif
  24412. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24413. // "GET /smuggled" request), reads the first response, and only then sends the
  24414. // embedded request as the body. Returns how many times /smuggled ran.
  24415. //
  24416. // The body is sent AFTER receiving the first response (as in the original
  24417. // PoC) so that the stream_line_reader cannot buffer it together with the
  24418. // headers of the first request.
  24419. static int count_smuggled_requests(const std::string &outer_head,
  24420. std::string &first_response) {
  24421. Server svr;
  24422. svr.set_mount_point("/", "./www");
  24423. std::atomic<int> smuggled_count(0);
  24424. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24425. smuggled_count++;
  24426. res.set_content("oops", "text/plain");
  24427. });
  24428. svr.Post("/post", [&](const Request &req, Response &res) {
  24429. res.set_content(req.body, "text/plain");
  24430. });
  24431. auto port = svr.bind_to_any_port("localhost");
  24432. thread t = thread([&] { svr.listen_after_bind(); });
  24433. auto se = detail::scope_exit([&] {
  24434. svr.stop();
  24435. t.join();
  24436. });
  24437. svr.wait_until_ready();
  24438. auto error = Error::Success;
  24439. auto sock = detail::create_client_socket(
  24440. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24441. /*connection_timeout_sec=*/2, 0,
  24442. /*read_timeout_sec=*/2, 0,
  24443. /*write_timeout_sec=*/2, 0, std::string(), error);
  24444. EXPECT_NE(INVALID_SOCKET, sock);
  24445. if (sock == INVALID_SOCKET) { return -1; }
  24446. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24447. // The "smuggled" request will be sent as the body of the outer request
  24448. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24449. "Host: localhost\r\n"
  24450. "Connection: close\r\n"
  24451. "\r\n";
  24452. auto head = outer_head;
  24453. auto len = std::to_string(smuggled.size());
  24454. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24455. pos = head.find("{len}", pos + len.size())) {
  24456. head.replace(pos, 5, len);
  24457. }
  24458. // Step 1: Send only the outer request headers (no body yet)
  24459. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24460. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24461. // Step 2: Read the first response
  24462. char buf[4096];
  24463. for (;;) {
  24464. auto n = recv(sock, buf, sizeof(buf), 0);
  24465. if (n <= 0) break;
  24466. first_response.append(buf, static_cast<size_t>(n));
  24467. // Stop once we have a complete response (headers + body)
  24468. auto hdr_end = first_response.find("\r\n\r\n");
  24469. if (hdr_end != std::string::npos) {
  24470. // Check for Content-Length to know when the body is complete
  24471. auto cl_pos = first_response.find("Content-Length:");
  24472. if (cl_pos != std::string::npos) {
  24473. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24474. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24475. auto cl = std::stoul(
  24476. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24477. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24478. } else {
  24479. break; // No Content-Length, assume headers-only response
  24480. }
  24481. }
  24482. }
  24483. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24484. // vulnerable server the keep-alive loop reads this as a second request. The
  24485. // server may already have closed the connection, so the result is ignored.
  24486. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24487. // Half-close so that a server which drained the body sees EOF and closes,
  24488. // instead of the read below waiting for the read timeout.
  24489. #ifdef _WIN32
  24490. ::shutdown(sock, SD_SEND);
  24491. #else
  24492. ::shutdown(sock, SHUT_WR);
  24493. #endif
  24494. // Step 4: Read until the server closes the connection
  24495. for (;;) {
  24496. auto n = recv(sock, buf, sizeof(buf), 0);
  24497. if (n <= 0) break;
  24498. }
  24499. return smuggled_count.load();
  24500. }
  24501. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24502. // A GET request with Content-Length to a static file handler must have its
  24503. // body drained before the keep-alive connection is reused. Otherwise the
  24504. // unread body bytes are interpreted as the next HTTP request.
  24505. std::string first_response;
  24506. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24507. "Host: localhost\r\n"
  24508. "Content-Length: {len}\r\n"
  24509. "\r\n",
  24510. first_response));
  24511. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24512. }
  24513. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24514. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24515. // be answered with 400 and the connection closed. Treating it as "no body"
  24516. // leaves the body to be parsed as the next request.
  24517. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24518. const char *targets[] = {
  24519. "GET /file", // handler that never reads the body
  24520. "GET /not-found", // no handler matches (404)
  24521. "POST /post", // handler that reads the body
  24522. };
  24523. for (auto target : targets) {
  24524. for (auto value : values) {
  24525. std::string first_response;
  24526. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24527. " HTTP/1.1\r\n"
  24528. "Host: localhost\r\n"
  24529. "Content-Length: " +
  24530. value + "\r\n\r\n",
  24531. first_response))
  24532. << target << " with Content-Length: " << value;
  24533. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24534. << target << " with Content-Length: " << value;
  24535. }
  24536. }
  24537. }
  24538. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24539. // A 400 for an unparseable request line leaves the rest of the message
  24540. // unread, so the connection must be closed rather than reused.
  24541. std::string first_response;
  24542. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24543. "Host: localhost\r\n"
  24544. "Content-Length: {len}\r\n"
  24545. "\r\n",
  24546. first_response));
  24547. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24548. }
  24549. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24550. // Same as above for a header block that fails to parse.
  24551. std::string first_response;
  24552. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24553. "Host: localhost\r\n"
  24554. "Bad Header\r\n"
  24555. "Content-Length: {len}\r\n"
  24556. "\r\n",
  24557. first_response));
  24558. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24559. }
  24560. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24561. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24562. // server must not read another request on that connection, even when the
  24563. // request had no body to drain.
  24564. std::string first_response;
  24565. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24566. "Host: localhost\r\n"
  24567. "\r\n",
  24568. first_response));
  24569. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24570. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24571. }
  24572. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24573. // A content reader that stops early leaves the stream inside the body.
  24574. // Draining the whole Content-Length from there, or reading the body again,
  24575. // reads into the next request, and whatever follows is parsed as a request
  24576. // of its own.
  24577. Server svr;
  24578. std::atomic<int> smuggled_count(0);
  24579. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24580. svr.Post("/upload", [](const Request &req, Response &res,
  24581. const ContentReader &content_reader) {
  24582. // Stop at the last chunk, so the whole body has been read however it
  24583. // arrives.
  24584. auto length = req.get_header_value_u64("Content-Length");
  24585. size_t total = 0;
  24586. auto consumed = content_reader([&](const char *, size_t n) {
  24587. total += n;
  24588. return total < length;
  24589. });
  24590. EXPECT_FALSE(consumed);
  24591. if (req.has_param("retry")) {
  24592. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24593. }
  24594. // Replace the 400 the aborted read set, which would close the connection.
  24595. res.set_redirect("/done");
  24596. });
  24597. auto port = svr.bind_to_any_port(HOST);
  24598. thread t = thread([&] { svr.listen_after_bind(); });
  24599. auto se = detail::scope_exit([&] {
  24600. svr.stop();
  24601. t.join();
  24602. });
  24603. svr.wait_until_ready();
  24604. // A front end sees the second request as a POST whose body is the GET. The
  24605. // first body is as long as the POST's headers, so draining it again reads
  24606. // exactly those and leaves the GET to be parsed next.
  24607. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24608. "Host: localhost\r\n"
  24609. "\r\n";
  24610. std::string second_head = "POST /post HTTP/1.1\r\n"
  24611. "Host: localhost\r\n"
  24612. "Content-Length: " +
  24613. std::to_string(inner.size()) +
  24614. "\r\n"
  24615. "\r\n";
  24616. for (auto target : {"/upload", "/upload?retry"}) {
  24617. smuggled_count = 0;
  24618. std::string request = "POST " + std::string(target) +
  24619. " HTTP/1.1\r\n"
  24620. "Host: localhost\r\n"
  24621. "Content-Length: " +
  24622. std::to_string(second_head.size()) +
  24623. "\r\n"
  24624. "\r\n" +
  24625. std::string(second_head.size(), 'A') + second_head +
  24626. inner;
  24627. std::string response;
  24628. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24629. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24630. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24631. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24632. EXPECT_EQ(0, smuggled_count.load()) << target;
  24633. }
  24634. }
  24635. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24636. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24637. // must be rejected with 400 Bad Request.
  24638. Server svr;
  24639. svr.Post("/test", [&](const Request &, Response &res) {
  24640. res.set_content("ok", "text/plain");
  24641. });
  24642. thread t = thread([&] { svr.listen(HOST, PORT); });
  24643. auto se = detail::scope_exit([&] {
  24644. svr.stop();
  24645. t.join();
  24646. ASSERT_FALSE(svr.is_running());
  24647. });
  24648. svr.wait_until_ready();
  24649. // Exact "chunked"
  24650. {
  24651. auto req = "POST /test HTTP/1.1\r\n"
  24652. "Host: localhost\r\n"
  24653. "Content-Length: 5\r\n"
  24654. "Transfer-Encoding: chunked\r\n"
  24655. "Connection: close\r\n"
  24656. "\r\n"
  24657. "hello";
  24658. std::string response;
  24659. ASSERT_TRUE(send_request(1, req, &response));
  24660. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24661. response.substr(0, response.find("\r\n")));
  24662. }
  24663. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24664. {
  24665. auto req = "POST /test HTTP/1.1\r\n"
  24666. "Host: localhost\r\n"
  24667. "Content-Length: 5\r\n"
  24668. "Transfer-Encoding: gzip, chunked\r\n"
  24669. "Connection: close\r\n"
  24670. "\r\n"
  24671. "hello";
  24672. std::string response;
  24673. ASSERT_TRUE(send_request(1, req, &response));
  24674. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24675. response.substr(0, response.find("\r\n")));
  24676. }
  24677. }
  24678. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24679. Server svr;
  24680. svr.Post("/test", [&](const Request &, Response &res) {
  24681. res.set_content("ok", "text/plain");
  24682. });
  24683. thread t = thread([&] { svr.listen(HOST, PORT); });
  24684. auto se = detail::scope_exit([&] {
  24685. svr.stop();
  24686. t.join();
  24687. ASSERT_FALSE(svr.is_running());
  24688. });
  24689. svr.wait_until_ready();
  24690. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24691. // length cannot be determined, so the server must answer 400 and close
  24692. // rather than treat the request as bodyless and leave the body in the
  24693. // socket for the next request to pick up.
  24694. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24695. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24696. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24697. std::string response;
  24698. ASSERT_TRUE(send_request(1, req, &response));
  24699. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24700. response.substr(0, response.find("\r\n")))
  24701. << transfer_encoding;
  24702. }
  24703. // RFC 9110 5.3: the codings may also be split across several
  24704. // Transfer-Encoding lines, which combine in the order they were received.
  24705. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24706. // just like the single-line "chunked, gzip" above.
  24707. {
  24708. auto req = "POST /test HTTP/1.1\r\n"
  24709. "Host: localhost\r\n"
  24710. "Transfer-Encoding: chunked\r\n"
  24711. "Transfer-Encoding: gzip\r\n"
  24712. "\r\n"
  24713. "0\r\n\r\n";
  24714. std::string response;
  24715. ASSERT_TRUE(send_request(1, req, &response));
  24716. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24717. response.substr(0, response.find("\r\n")));
  24718. }
  24719. // A sequence ending in chunked stays valid.
  24720. auto req = "POST /test HTTP/1.1\r\n"
  24721. "Host: localhost\r\n"
  24722. "Transfer-Encoding: gzip, chunked\r\n"
  24723. "Connection: close\r\n"
  24724. "\r\n"
  24725. "0\r\n\r\n";
  24726. std::string response;
  24727. ASSERT_TRUE(send_request(1, req, &response));
  24728. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24729. // ...including when it is spread over several lines.
  24730. auto split_req = "POST /test HTTP/1.1\r\n"
  24731. "Host: localhost\r\n"
  24732. "Transfer-Encoding: gzip\r\n"
  24733. "Transfer-Encoding: chunked\r\n"
  24734. "Connection: close\r\n"
  24735. "\r\n"
  24736. "0\r\n\r\n";
  24737. std::string split_response;
  24738. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24739. EXPECT_EQ("HTTP/1.1 200 OK",
  24740. split_response.substr(0, split_response.find("\r\n")));
  24741. }
  24742. // Regression for issue #2450: a DELETE without Content-Length on a
  24743. // keep-alive connection must not let the post-response drain consume the
  24744. // next request's bytes.
  24745. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24746. Server svr;
  24747. std::atomic<int> delete_count(0);
  24748. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24749. delete_count++;
  24750. res.status = StatusCode::NoContent_204;
  24751. });
  24752. auto port = svr.bind_to_any_port(HOST);
  24753. thread t = thread([&] { svr.listen_after_bind(); });
  24754. auto se = detail::scope_exit([&] {
  24755. svr.stop();
  24756. t.join();
  24757. });
  24758. svr.wait_until_ready();
  24759. auto error = Error::Success;
  24760. auto sock = detail::create_client_socket(
  24761. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24762. /*connection_timeout_sec=*/2, 0,
  24763. /*read_timeout_sec=*/2, 0,
  24764. /*write_timeout_sec=*/2, 0, std::string(), error);
  24765. ASSERT_NE(INVALID_SOCKET, sock);
  24766. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24767. auto send_request_and_read_response = [&](const std::string &req,
  24768. std::string &out) -> bool {
  24769. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  24770. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24771. char buf[4096];
  24772. for (;;) {
  24773. auto n = recv(sock, buf, sizeof(buf), 0);
  24774. if (n <= 0) { return !out.empty(); }
  24775. out.append(buf, static_cast<size_t>(n));
  24776. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24777. }
  24778. };
  24779. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24780. "Host: localhost\r\n"
  24781. "\r\n";
  24782. std::string resp1;
  24783. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24784. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24785. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24786. "Host: localhost\r\n"
  24787. "Connection: close\r\n"
  24788. "\r\n";
  24789. std::string resp2;
  24790. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24791. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24792. EXPECT_EQ(2, delete_count.load());
  24793. }
  24794. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24795. Server svr;
  24796. svr.Post("/ingest", [&](const Request &, Response &res,
  24797. const ContentReader &content_reader) {
  24798. auto consumed = content_reader([](const char *, size_t) { return false; });
  24799. EXPECT_FALSE(consumed);
  24800. res.status = StatusCode::Conflict_409;
  24801. res.set_header("Connection", "close");
  24802. });
  24803. auto port = svr.bind_to_any_port(HOST);
  24804. thread t = thread([&] { svr.listen_after_bind(); });
  24805. auto se = detail::scope_exit([&] {
  24806. svr.stop();
  24807. t.join();
  24808. });
  24809. svr.wait_until_ready();
  24810. auto error = Error::Success;
  24811. auto sock = detail::create_client_socket(
  24812. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24813. /*connection_timeout_sec=*/2, 0,
  24814. /*read_timeout_sec=*/1, 0,
  24815. /*write_timeout_sec=*/2, 0, std::string(), error);
  24816. ASSERT_NE(INVALID_SOCKET, sock);
  24817. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24818. std::string request = "POST /ingest HTTP/1.1\r\n"
  24819. "Host: localhost\r\n"
  24820. "Transfer-Encoding: chunked\r\n"
  24821. "\r\n"
  24822. "4\r\n"
  24823. "data\r\n";
  24824. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  24825. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24826. std::string response;
  24827. ssize_t received = 0;
  24828. do {
  24829. char buf[4096];
  24830. received = recv(sock, buf, sizeof(buf), 0);
  24831. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24832. } while (received > 0);
  24833. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24834. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24835. EXPECT_EQ(0, received);
  24836. }
  24837. namespace no_proxy_test {
  24838. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24839. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24840. // calling listen().
  24841. class ScopedServer {
  24842. public:
  24843. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24844. ~ScopedServer() {
  24845. svr_.stop();
  24846. if (th_.joinable()) { th_.join(); }
  24847. }
  24848. Server &svr() { return svr_; }
  24849. int port() const { return port_; }
  24850. void listen() {
  24851. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24852. svr_.wait_until_ready();
  24853. }
  24854. private:
  24855. Server svr_;
  24856. std::thread th_;
  24857. int port_ = 0;
  24858. };
  24859. class ProxyAndTargetServers {
  24860. public:
  24861. ProxyAndTargetServers() {
  24862. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24863. proxy_hits_++;
  24864. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24865. res.set_content("via-proxy", "text/plain");
  24866. });
  24867. target_.Get(".*", [this](const Request &req, Response &res) {
  24868. target_hits_++;
  24869. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24870. res.set_content("direct", "text/plain");
  24871. });
  24872. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24873. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24874. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24875. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24876. proxy_mock_.wait_until_ready();
  24877. target_.wait_until_ready();
  24878. }
  24879. ~ProxyAndTargetServers() {
  24880. proxy_mock_.stop();
  24881. target_.stop();
  24882. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24883. if (target_thread_.joinable()) { target_thread_.join(); }
  24884. }
  24885. Server &proxy_mock() { return proxy_mock_; }
  24886. Server &target() { return target_; }
  24887. int proxy_port() const { return proxy_port_; }
  24888. int target_port() const { return target_port_; }
  24889. int proxy_hits() const { return proxy_hits_.load(); }
  24890. int target_hits() const { return target_hits_.load(); }
  24891. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24892. void reset_counters() {
  24893. proxy_hits_ = 0;
  24894. target_hits_ = 0;
  24895. last_had_proxy_authz_ = false;
  24896. }
  24897. private:
  24898. Server proxy_mock_;
  24899. Server target_;
  24900. std::thread proxy_thread_;
  24901. std::thread target_thread_;
  24902. int proxy_port_ = 0;
  24903. int target_port_ = 0;
  24904. std::atomic<int> proxy_hits_{0};
  24905. std::atomic<int> target_hits_{0};
  24906. std::atomic<bool> last_had_proxy_authz_{false};
  24907. };
  24908. inline std::unique_ptr<Client> make_client(const std::string &host,
  24909. ProxyAndTargetServers &s) {
  24910. auto cli = detail::make_unique<Client>(host, s.target_port());
  24911. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24912. cli->set_proxy("127.0.0.1", s.proxy_port());
  24913. return cli;
  24914. }
  24915. } // namespace no_proxy_test
  24916. using no_proxy_test::make_client;
  24917. using no_proxy_test::ProxyAndTargetServers;
  24918. TEST(NoProxyTest, ExactHostnameBypasses) {
  24919. ProxyAndTargetServers s;
  24920. auto cli = make_client("example.com", s);
  24921. cli->set_no_proxy({"example.com"});
  24922. auto res = cli->Get("/");
  24923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24924. EXPECT_EQ(0, s.proxy_hits());
  24925. EXPECT_EQ(1, s.target_hits());
  24926. }
  24927. TEST(NoProxyTest, SubdomainBypasses) {
  24928. ProxyAndTargetServers s;
  24929. auto cli = make_client("foo.example.com", s);
  24930. cli->set_no_proxy({"example.com"});
  24931. auto res = cli->Get("/");
  24932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24933. EXPECT_EQ(0, s.proxy_hits());
  24934. EXPECT_EQ(1, s.target_hits());
  24935. }
  24936. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24937. // Regression guard: "evilexample.com" must not be considered a subdomain
  24938. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24939. // check would let traffic bypass the proxy and leak credentials direct
  24940. // to the attacker host.
  24941. ProxyAndTargetServers s;
  24942. auto cli = make_client("evilexample.com", s);
  24943. cli->set_no_proxy({"example.com"});
  24944. auto res = cli->Get("/");
  24945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24946. EXPECT_GE(s.proxy_hits(), 1);
  24947. EXPECT_EQ(0, s.target_hits());
  24948. }
  24949. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24950. ProxyAndTargetServers s;
  24951. auto cli = make_client("example.com.evil.com", s);
  24952. cli->set_no_proxy({"example.com"});
  24953. auto res = cli->Get("/");
  24954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24955. EXPECT_GE(s.proxy_hits(), 1);
  24956. EXPECT_EQ(0, s.target_hits());
  24957. }
  24958. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24959. ProxyAndTargetServers s;
  24960. auto cli = make_client("example.com", s);
  24961. cli->set_no_proxy({".example.com"});
  24962. auto res = cli->Get("/");
  24963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24964. EXPECT_EQ(0, s.proxy_hits());
  24965. EXPECT_EQ(1, s.target_hits());
  24966. }
  24967. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24968. ProxyAndTargetServers s;
  24969. auto cli = make_client("Example.COM", s);
  24970. cli->set_no_proxy({"EXAMPLE.com"});
  24971. auto res = cli->Get("/");
  24972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24973. EXPECT_EQ(0, s.proxy_hits());
  24974. EXPECT_EQ(1, s.target_hits());
  24975. }
  24976. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24977. ProxyAndTargetServers s;
  24978. auto cli = make_client("example.com.", s);
  24979. cli->set_no_proxy({"example.com"});
  24980. auto res = cli->Get("/");
  24981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24982. EXPECT_EQ(0, s.proxy_hits());
  24983. EXPECT_EQ(1, s.target_hits());
  24984. }
  24985. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24986. // Trailing dots must be normalized on BOTH sides — host and entry.
  24987. // An implementation that only strips the host-side trailing dot would
  24988. // fail to match host "example.com" against entry "example.com." because
  24989. // a literal substring search would compare 11 chars against 12.
  24990. ProxyAndTargetServers s;
  24991. auto cli = make_client("example.com", s);
  24992. cli->set_no_proxy({"example.com."});
  24993. auto res = cli->Get("/");
  24994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24995. EXPECT_EQ(0, s.proxy_hits());
  24996. EXPECT_EQ(1, s.target_hits());
  24997. }
  24998. TEST(NoProxyTest, WildcardBypassesEverything) {
  24999. ProxyAndTargetServers s;
  25000. auto cli = make_client("anything.invalid.test", s);
  25001. cli->set_no_proxy({"*"});
  25002. auto res = cli->Get("/");
  25003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25004. EXPECT_EQ(0, s.proxy_hits());
  25005. EXPECT_EQ(1, s.target_hits());
  25006. }
  25007. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25008. ProxyAndTargetServers s;
  25009. Client cli("127.0.0.1", s.target_port());
  25010. cli.set_proxy("127.0.0.1", s.proxy_port());
  25011. cli.set_no_proxy({"127.0.0.1"});
  25012. auto res = cli.Get("/");
  25013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25014. EXPECT_EQ(0, s.proxy_hits());
  25015. EXPECT_EQ(1, s.target_hits());
  25016. }
  25017. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25018. ProxyAndTargetServers s;
  25019. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25020. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25021. cli.set_proxy("127.0.0.1", s.proxy_port());
  25022. cli.set_no_proxy({"::1"});
  25023. auto res = cli.Get("/");
  25024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25025. EXPECT_EQ(0, s.proxy_hits());
  25026. EXPECT_EQ(1, s.target_hits());
  25027. }
  25028. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25029. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25030. // must still be recognized as IPv6 for CIDR matching. Implementations
  25031. // that detect IPv6 only when the host begins with '[' would parse the
  25032. // host as a hostname and miss the match.
  25033. ProxyAndTargetServers s;
  25034. Client cli("fe80::1", s.target_port());
  25035. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25036. cli.set_proxy("127.0.0.1", s.proxy_port());
  25037. cli.set_no_proxy({"fe80::/10"});
  25038. auto res = cli.Get("/");
  25039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25040. EXPECT_EQ(0, s.proxy_hits());
  25041. EXPECT_EQ(1, s.target_hits());
  25042. }
  25043. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25044. ProxyAndTargetServers s;
  25045. Client cli("::1", s.target_port());
  25046. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25047. cli.set_proxy("127.0.0.1", s.proxy_port());
  25048. cli.set_no_proxy({"[::1]"});
  25049. auto res = cli.Get("/");
  25050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25051. EXPECT_EQ(0, s.proxy_hits());
  25052. EXPECT_EQ(1, s.target_hits());
  25053. }
  25054. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25055. ProxyAndTargetServers s;
  25056. Client cli("fe80::1", s.target_port());
  25057. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25058. cli.set_proxy("127.0.0.1", s.proxy_port());
  25059. cli.set_no_proxy({"[fe80::]/10"});
  25060. auto res = cli.Get("/");
  25061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25062. EXPECT_EQ(0, s.proxy_hits());
  25063. EXPECT_EQ(1, s.target_hits());
  25064. }
  25065. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25066. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25067. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25068. // tricks via address-family conversion.
  25069. ProxyAndTargetServers s;
  25070. Client cli("::ffff:127.0.0.1", s.target_port());
  25071. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25072. cli.set_proxy("127.0.0.1", s.proxy_port());
  25073. cli.set_no_proxy({"127.0.0.1"});
  25074. auto res = cli.Get("/");
  25075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25076. EXPECT_GE(s.proxy_hits(), 1);
  25077. EXPECT_EQ(0, s.target_hits());
  25078. }
  25079. TEST(NoProxyTest, IPv4CidrMatch) {
  25080. ProxyAndTargetServers s;
  25081. Client cli("127.0.0.1", s.target_port());
  25082. cli.set_proxy("127.0.0.1", s.proxy_port());
  25083. cli.set_no_proxy({"127.0.0.0/8"});
  25084. auto res = cli.Get("/");
  25085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25086. EXPECT_EQ(0, s.proxy_hits());
  25087. EXPECT_EQ(1, s.target_hits());
  25088. }
  25089. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25090. ProxyAndTargetServers s;
  25091. Client cli("127.0.0.1", s.target_port());
  25092. cli.set_proxy("127.0.0.1", s.proxy_port());
  25093. cli.set_no_proxy({"10.0.0.0/8"});
  25094. auto res = cli.Get("/");
  25095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25096. EXPECT_GE(s.proxy_hits(), 1);
  25097. EXPECT_EQ(0, s.target_hits());
  25098. }
  25099. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25100. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25101. // IPv4 target matches.
  25102. ProxyAndTargetServers s;
  25103. Client cli("127.0.0.1", s.target_port());
  25104. cli.set_proxy("127.0.0.1", s.proxy_port());
  25105. cli.set_no_proxy({"0.0.0.0/0"});
  25106. auto res = cli.Get("/");
  25107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25108. EXPECT_EQ(0, s.proxy_hits());
  25109. EXPECT_EQ(1, s.target_hits());
  25110. }
  25111. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25112. ProxyAndTargetServers s;
  25113. Client cli("127.0.0.1", s.target_port());
  25114. cli.set_proxy("127.0.0.1", s.proxy_port());
  25115. cli.set_no_proxy({"127.0.0.1"});
  25116. auto res = cli.Get("/");
  25117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25118. EXPECT_EQ(0, s.proxy_hits());
  25119. EXPECT_EQ(1, s.target_hits());
  25120. }
  25121. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25122. ProxyAndTargetServers s;
  25123. Client cli("127.0.0.1", s.target_port());
  25124. cli.set_proxy("127.0.0.1", s.proxy_port());
  25125. cli.set_no_proxy({"127.0.0.0/33"});
  25126. auto res = cli.Get("/");
  25127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25128. EXPECT_GE(s.proxy_hits(), 1);
  25129. EXPECT_EQ(0, s.target_hits());
  25130. }
  25131. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25132. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25133. ProxyAndTargetServers s;
  25134. Client cli("127.0.0.1", s.target_port());
  25135. cli.set_proxy("127.0.0.1", s.proxy_port());
  25136. cli.set_no_proxy({"127.0.0.1/"});
  25137. auto res = cli.Get("/");
  25138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25139. EXPECT_GE(s.proxy_hits(), 1);
  25140. EXPECT_EQ(0, s.target_hits());
  25141. }
  25142. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25143. ProxyAndTargetServers s;
  25144. auto cli = make_client("internal.corp", s);
  25145. cli->set_proxy_basic_auth("u", "p");
  25146. cli->set_no_proxy({"internal.corp"});
  25147. auto res = cli->Get("/");
  25148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25149. EXPECT_EQ(1, s.target_hits());
  25150. EXPECT_EQ(0, s.proxy_hits());
  25151. EXPECT_FALSE(s.last_had_proxy_authz())
  25152. << "Proxy-Authorization must not be sent direct to the target";
  25153. }
  25154. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25155. ProxyAndTargetServers s;
  25156. auto cli = make_client("public.example", s);
  25157. cli->set_proxy_basic_auth("u", "p");
  25158. cli->set_no_proxy({"internal.corp"}); // does not match
  25159. auto res = cli->Get("/");
  25160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25161. EXPECT_GE(s.proxy_hits(), 1);
  25162. EXPECT_TRUE(s.last_had_proxy_authz());
  25163. }
  25164. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25165. std::atomic<int> hits{0};
  25166. std::atomic<int> hits_with_authz{0};
  25167. no_proxy_test::ScopedServer proxy_mock;
  25168. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25169. hits++;
  25170. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25171. if (req.target.find("/redir") != std::string::npos) {
  25172. res.set_redirect("http://other.example/landed");
  25173. } else {
  25174. res.set_content("via-proxy", "text/plain");
  25175. }
  25176. });
  25177. proxy_mock.listen();
  25178. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25179. hits = 0;
  25180. hits_with_authz = 0;
  25181. Client cli("public.example", 80);
  25182. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25183. cli.set_proxy_basic_auth(c.first, c.second);
  25184. cli.set_follow_location(true);
  25185. // The redirect to another host goes through the proxy as well
  25186. auto res = cli.Get("/redir");
  25187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25188. EXPECT_EQ(2, hits.load());
  25189. EXPECT_EQ(2, hits_with_authz.load());
  25190. }
  25191. }
  25192. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25193. ProxyAndTargetServers s;
  25194. auto cli = make_client("anything.test", s);
  25195. auto res = cli->Get("/");
  25196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25197. EXPECT_GE(s.proxy_hits(), 1);
  25198. EXPECT_EQ(0, s.target_hits());
  25199. }
  25200. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25201. ProxyAndTargetServers s;
  25202. auto cli = make_client("example.com", s);
  25203. cli->set_no_proxy({"example.com:8080"});
  25204. auto res = cli->Get("/");
  25205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25206. EXPECT_GE(s.proxy_hits(), 1);
  25207. EXPECT_EQ(0, s.target_hits());
  25208. }
  25209. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25210. ProxyAndTargetServers s;
  25211. auto cli = make_client("anything.test", s);
  25212. cli->set_no_proxy({"", " ", "\t"});
  25213. auto res = cli->Get("/");
  25214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25215. EXPECT_GE(s.proxy_hits(), 1);
  25216. EXPECT_EQ(0, s.target_hits());
  25217. }
  25218. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25219. // An entry with leading/trailing whitespace must still match — env-style
  25220. // values are commonly pasted with stray spaces and an implementation
  25221. // that feeds the raw token directly to inet_pton would fail to match
  25222. // valid CIDRs because of the spaces.
  25223. ProxyAndTargetServers s;
  25224. Client cli("127.0.0.1", s.target_port());
  25225. cli.set_proxy("127.0.0.1", s.proxy_port());
  25226. cli.set_no_proxy({" 127.0.0.0/8 "});
  25227. auto res = cli.Get("/");
  25228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25229. EXPECT_EQ(0, s.proxy_hits());
  25230. EXPECT_EQ(1, s.target_hits());
  25231. }
  25232. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25233. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25234. // go direct and must NOT carry Proxy-Authorization.
  25235. std::atomic<int> proxy_hits{0};
  25236. std::atomic<int> target_hits{0};
  25237. std::atomic<bool> target_saw_authz{false};
  25238. no_proxy_test::ScopedServer proxy_mock, target;
  25239. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25240. proxy_hits++;
  25241. res.status = 302;
  25242. res.set_header("Location", "http://127.0.0.1:" +
  25243. std::to_string(target.port()) + "/landed");
  25244. });
  25245. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25246. target_hits++;
  25247. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25248. res.set_content("direct", "text/plain");
  25249. });
  25250. proxy_mock.listen();
  25251. target.listen();
  25252. Client cli("public.example", target.port());
  25253. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25254. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25255. cli.set_proxy_basic_auth("u", "p");
  25256. cli.set_no_proxy({"127.0.0.1"});
  25257. cli.set_follow_location(true);
  25258. auto res = cli.Get("/redir");
  25259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25260. EXPECT_GE(proxy_hits.load(), 1);
  25261. EXPECT_GE(target_hits.load(), 1);
  25262. EXPECT_FALSE(target_saw_authz.load());
  25263. }
  25264. #ifdef CPPHTTPLIB_SSL_ENABLED
  25265. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25266. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25267. // proxy creds would be sent to the (possibly hostile) origin.
  25268. std::atomic<int> target_hits{0};
  25269. std::atomic<bool> target_saw_proxy_authz{false};
  25270. no_proxy_test::ScopedServer target;
  25271. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25272. target_hits++;
  25273. if (req.has_header("Proxy-Authorization")) {
  25274. target_saw_proxy_authz = true;
  25275. }
  25276. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25277. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25278. "nonce=\"abc\", algorithm=MD5");
  25279. });
  25280. target.listen();
  25281. // The proxy address is set to the target's port: the bypass MUST kick in;
  25282. // if it doesn't, the test still routes "via proxy" to the same server and
  25283. // the Proxy-Authorization assertion below catches the leak.
  25284. Client cli("evil.example", target.port());
  25285. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25286. cli.set_proxy("127.0.0.1", target.port());
  25287. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25288. cli.set_no_proxy({"evil.example"});
  25289. auto res = cli.Get("/x");
  25290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25291. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25292. EXPECT_EQ(1, target_hits.load());
  25293. EXPECT_FALSE(target_saw_proxy_authz.load());
  25294. }
  25295. #endif
  25296. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25297. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25298. std::atomic<int> proxy_hits{0};
  25299. std::atomic<int> bypass_hits{0};
  25300. std::atomic<bool> proxy_saw_c_url{false};
  25301. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25302. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25303. proxy_hits++;
  25304. if (req.path.find("/start") != std::string::npos) {
  25305. res.status = 302;
  25306. res.set_header("Location", "http://127.0.0.1:" +
  25307. std::to_string(bypass_server.port()) +
  25308. "/middle");
  25309. return;
  25310. }
  25311. if (req.path.find("/end") != std::string::npos) {
  25312. proxy_saw_c_url = true;
  25313. res.set_content("c-via-proxy", "text/plain");
  25314. return;
  25315. }
  25316. res.set_content("unexpected", "text/plain");
  25317. });
  25318. // public.example's "advertised" port is arbitrary (the request never lands
  25319. // there — it goes through the proxy), but use a dynamic value to stay
  25320. // friendly with sharded parallel runs.
  25321. int public_port = bypass_server.port();
  25322. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25323. bypass_hits++;
  25324. res.status = 302;
  25325. res.set_header("Location", "http://public.example:" +
  25326. std::to_string(public_port) + "/end");
  25327. });
  25328. proxy_mock.listen();
  25329. bypass_server.listen();
  25330. Client cli("public.example", public_port);
  25331. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25332. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25333. cli.set_no_proxy({"127.0.0.1"});
  25334. cli.set_follow_location(true);
  25335. auto res = cli.Get("/start");
  25336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25337. EXPECT_EQ(StatusCode::OK_200, res->status);
  25338. EXPECT_EQ("c-via-proxy", res->body);
  25339. EXPECT_GE(proxy_hits.load(), 2);
  25340. EXPECT_GE(bypass_hits.load(), 1);
  25341. EXPECT_TRUE(proxy_saw_c_url.load());
  25342. }
  25343. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25344. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25345. // request reconnects to the correct endpoint.
  25346. std::atomic<int> proxy_hits{0};
  25347. std::atomic<int> target_hits{0};
  25348. no_proxy_test::ScopedServer proxy_mock, target;
  25349. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25350. proxy_hits++;
  25351. res.set_content("via-proxy", "text/plain");
  25352. });
  25353. target.svr().Get(".*", [&](const Request &, Response &res) {
  25354. target_hits++;
  25355. res.set_content("direct", "text/plain");
  25356. });
  25357. proxy_mock.listen();
  25358. target.listen();
  25359. Client cli("public.example", target.port());
  25360. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25361. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25362. cli.set_keep_alive(true);
  25363. auto res1 = cli.Get("/a");
  25364. ASSERT_TRUE(res1);
  25365. EXPECT_EQ("via-proxy", res1->body);
  25366. EXPECT_EQ(1, proxy_hits.load());
  25367. EXPECT_EQ(0, target_hits.load());
  25368. cli.set_no_proxy({"public.example"});
  25369. auto res2 = cli.Get("/b");
  25370. ASSERT_TRUE(res2);
  25371. EXPECT_EQ("direct", res2->body);
  25372. EXPECT_EQ(1, proxy_hits.load());
  25373. EXPECT_EQ(1, target_hits.load());
  25374. }
  25375. // Forward declarations (see the base64_encode note).
  25376. namespace httplib {
  25377. namespace detail {
  25378. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25379. int shutdown_socket(socket_t sock) noexcept;
  25380. } // namespace detail
  25381. } // namespace httplib
  25382. namespace proxy_tunnel_test {
  25383. const char *const kTunnelEstablished =
  25384. "HTTP/1.1 200 Connection established\r\n\r\n";
  25385. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25386. using ConnectReply = std::function<std::string(const std::string &head)>;
  25387. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25388. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25389. class ScopedConnectProxy {
  25390. public:
  25391. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25392. : forward_port_(forward_port), reply_(std::move(reply)) {
  25393. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25394. if (listen_sock_ == INVALID_SOCKET) { return; }
  25395. auto a = loopback(0);
  25396. auto addr = reinterpret_cast<sockaddr *>(&a);
  25397. socklen_t alen = sizeof(a);
  25398. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25399. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25400. ::listen(listen_sock_, 4) != 0) {
  25401. return;
  25402. }
  25403. port_ = ntohs(a.sin_port);
  25404. th_ = std::thread([this] { run(); });
  25405. }
  25406. ~ScopedConnectProxy() {
  25407. if (th_.joinable()) {
  25408. stop_ = true;
  25409. auto wake = connect_to(port_);
  25410. th_.join();
  25411. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25412. }
  25413. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25414. }
  25415. int port() const { return port_; }
  25416. int connect_hits() const { return connect_hits_.load(); }
  25417. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25418. std::string connect_request() const {
  25419. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25420. return connect_request_;
  25421. }
  25422. private:
  25423. static sockaddr_in loopback(int port) {
  25424. sockaddr_in a{};
  25425. a.sin_family = AF_INET;
  25426. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25427. a.sin_port = htons(static_cast<unsigned short>(port));
  25428. return a;
  25429. }
  25430. static socket_t connect_to(int port) {
  25431. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25432. if (sock == INVALID_SOCKET) { return sock; }
  25433. auto a = loopback(port);
  25434. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25435. detail::close_socket(sock);
  25436. return INVALID_SOCKET;
  25437. }
  25438. return sock;
  25439. }
  25440. static bool send_all(socket_t sock, const char *data, size_t size) {
  25441. while (size > 0) {
  25442. auto n = detail::send_socket(sock, data, size, 0);
  25443. if (n <= 0) { return false; }
  25444. data += n;
  25445. size -= static_cast<size_t>(n);
  25446. }
  25447. return true;
  25448. }
  25449. void run() {
  25450. for (;;) {
  25451. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25452. if (stop_) {
  25453. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25454. return;
  25455. }
  25456. if (client == INVALID_SOCKET) { continue; }
  25457. serve(client);
  25458. detail::close_socket(client);
  25459. }
  25460. }
  25461. void serve(socket_t client) {
  25462. std::string head;
  25463. char buf[2048];
  25464. while (head.find("\r\n\r\n") == std::string::npos) {
  25465. if (detail::select_read(client, 5, 0) <= 0) { return; }
  25466. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  25467. if (n <= 0) { return; }
  25468. head.append(buf, static_cast<size_t>(n));
  25469. }
  25470. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  25471. connect_hits_++;
  25472. {
  25473. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25474. connect_request_ = head;
  25475. }
  25476. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  25477. if (!send_all(client, res.data(), res.size()) ||
  25478. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  25479. return;
  25480. }
  25481. auto origin = connect_to(forward_port_);
  25482. if (origin == INVALID_SOCKET) { return; }
  25483. // When either side stops, shut both down so the other pump returns too.
  25484. auto pump = [&](socket_t from, socket_t to) {
  25485. char b[8192];
  25486. for (;;) {
  25487. auto n = detail::read_socket(from, b, sizeof(b), 0);
  25488. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  25489. }
  25490. detail::shutdown_socket(client);
  25491. detail::shutdown_socket(origin);
  25492. };
  25493. std::thread up([&] { pump(client, origin); });
  25494. pump(origin, client);
  25495. up.join();
  25496. detail::close_socket(origin);
  25497. }
  25498. int forward_port_;
  25499. ConnectReply reply_;
  25500. socket_t listen_sock_ = INVALID_SOCKET;
  25501. int port_ = 0;
  25502. std::thread th_;
  25503. std::atomic<bool> stop_{false};
  25504. std::atomic<int> connect_hits_{0};
  25505. mutable std::mutex connect_request_mutex_;
  25506. std::string connect_request_;
  25507. };
  25508. } // namespace proxy_tunnel_test
  25509. #ifdef CPPHTTPLIB_SSL_ENABLED
  25510. namespace proxy_tunnel_test {
  25511. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25512. class ScopedSSLServer {
  25513. public:
  25514. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25515. port_ = svr_.bind_to_any_port("127.0.0.1");
  25516. }
  25517. ~ScopedSSLServer() {
  25518. svr_.stop();
  25519. if (th_.joinable()) { th_.join(); }
  25520. }
  25521. SSLServer &svr() { return svr_; }
  25522. int port() const { return port_; }
  25523. void listen() {
  25524. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25525. svr_.wait_until_ready();
  25526. }
  25527. private:
  25528. SSLServer svr_;
  25529. std::thread th_;
  25530. int port_ = 0;
  25531. };
  25532. // Sends one request through the CONNECT proxy to the TLS origin with a
  25533. // credential configured for each hop, and checks that each credential reaches
  25534. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25535. // origin's (every header in origin_headers) on the tunnelled request.
  25536. void CredentialsStayWithTheirHop(
  25537. const std::function<void(SSLClient &)> &set_credentials,
  25538. const std::string &scheme,
  25539. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25540. std::atomic<int> origin_hits{0};
  25541. std::atomic<bool> origin_saw_proxy_authz{false};
  25542. std::atomic<bool> origin_saw_headers{false};
  25543. ScopedSSLServer origin;
  25544. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25545. origin_hits++;
  25546. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25547. origin_saw_headers =
  25548. std::all_of(origin_headers.begin(), origin_headers.end(),
  25549. [&](const std::string &h) { return req.has_header(h); });
  25550. res.set_content("ok", "text/plain");
  25551. });
  25552. origin.listen();
  25553. ScopedConnectProxy proxy(origin.port());
  25554. ASSERT_NE(0, proxy.port());
  25555. // Pinned to 127.0.0.1 for the same reason as the test below.
  25556. SSLClient cli("127.0.0.1", origin.port());
  25557. cli.enable_server_certificate_verification(false);
  25558. cli.set_proxy("127.0.0.1", proxy.port());
  25559. set_credentials(cli);
  25560. auto res = cli.Get("/x");
  25561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25562. EXPECT_EQ(StatusCode::OK_200, res->status);
  25563. EXPECT_EQ(1, origin_hits.load());
  25564. EXPECT_EQ(1, proxy.connect_hits());
  25565. EXPECT_TRUE(origin_saw_headers.load());
  25566. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25567. << "Proxy-Authorization must not be sent inside the tunnel";
  25568. auto connect_req = proxy.connect_request();
  25569. EXPECT_NE(std::string::npos,
  25570. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25571. for (const auto &h : origin_headers) {
  25572. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25573. << h << " must not be sent to the proxy on CONNECT";
  25574. }
  25575. }
  25576. } // namespace proxy_tunnel_test
  25577. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25578. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25579. [](SSLClient &cli) {
  25580. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25581. cli.set_basic_auth("origin-user", "origin-pass");
  25582. },
  25583. "Basic");
  25584. }
  25585. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25586. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25587. [](SSLClient &cli) {
  25588. cli.set_proxy_bearer_token_auth("proxy-token");
  25589. cli.set_bearer_token_auth("origin-token");
  25590. },
  25591. "Bearer");
  25592. }
  25593. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25594. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25595. [](SSLClient &cli) {
  25596. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25597. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25598. {"Cookie", "sid=origin-session"},
  25599. {"X-Api-Key", "origin-key"}});
  25600. },
  25601. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25602. }
  25603. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25604. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25605. // retry; otherwise proxy creds would be sent to the origin.
  25606. std::atomic<int> origin_hits{0};
  25607. std::atomic<bool> origin_saw_proxy_authz{false};
  25608. proxy_tunnel_test::ScopedSSLServer origin;
  25609. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25610. origin_hits++;
  25611. if (req.has_header("Proxy-Authorization")) {
  25612. origin_saw_proxy_authz = true;
  25613. }
  25614. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25615. res.set_header("Proxy-Authenticate",
  25616. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25617. "algorithm=MD5");
  25618. });
  25619. origin.listen();
  25620. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25621. ASSERT_NE(0, proxy.port());
  25622. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25623. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25624. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25625. // and answer with its own status, making this test flaky.
  25626. SSLClient cli("127.0.0.1", origin.port());
  25627. cli.enable_server_certificate_verification(false);
  25628. cli.set_proxy("127.0.0.1", proxy.port());
  25629. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25630. auto res = cli.Get("/x");
  25631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25632. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25633. EXPECT_EQ(1, origin_hits.load());
  25634. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25635. EXPECT_EQ(1, proxy.connect_hits());
  25636. }
  25637. #endif
  25638. namespace proxy_tunnel_test {
  25639. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  25640. // anything else gets a 407 with `challenge`.
  25641. ConnectReply require_proxy_auth(const std::string &expected,
  25642. const std::string &challenge) {
  25643. return [=](const std::string &head) -> std::string {
  25644. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  25645. std::string::npos) {
  25646. return kTunnelEstablished;
  25647. }
  25648. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25649. "Proxy-Authenticate: " +
  25650. challenge + "\r\nContent-Length: 0\r\n\r\n";
  25651. };
  25652. }
  25653. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  25654. // request, then echoes.
  25655. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  25656. ws.send(
  25657. "authorization:" + req.get_header_value("Authorization") +
  25658. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  25659. std::string msg;
  25660. while (ws.read(msg)) {
  25661. ws.send(msg);
  25662. }
  25663. }
  25664. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  25665. class ScopedWebSocketOrigin {
  25666. public:
  25667. ScopedWebSocketOrigin() {
  25668. server_.svr().WebSocket("/ws", report_auth_then_echo);
  25669. server_.listen();
  25670. }
  25671. int port() const { return server_.port(); }
  25672. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  25673. std::string url() const {
  25674. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  25675. }
  25676. private:
  25677. no_proxy_test::ScopedServer server_;
  25678. };
  25679. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  25680. // passed as a constructor header, and checks that each reaches only its hop.
  25681. void WebSocketCredentialsStayWithTheirHop(
  25682. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  25683. const std::string &proxy_authz, const std::string &origin_authz) {
  25684. ScopedWebSocketOrigin origin;
  25685. ScopedConnectProxy proxy(
  25686. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  25687. ASSERT_NE(0, proxy.port());
  25688. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  25689. client.set_proxy("127.0.0.1", proxy.port());
  25690. set_proxy_credentials(client);
  25691. auto res = client.connect();
  25692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25693. std::string msg;
  25694. ASSERT_TRUE(client.read(msg));
  25695. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  25696. client.close();
  25697. EXPECT_EQ(1, proxy.connect_hits());
  25698. EXPECT_EQ(std::string::npos,
  25699. proxy.connect_request().find("\r\nAuthorization: "))
  25700. << "origin credentials must not be sent to the proxy";
  25701. }
  25702. } // namespace proxy_tunnel_test
  25703. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  25704. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25705. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25706. ASSERT_NE(0, proxy.port());
  25707. ws::WebSocketClient client(origin.url());
  25708. client.set_proxy("127.0.0.1", proxy.port());
  25709. auto res = client.connect();
  25710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25711. std::string msg;
  25712. ASSERT_TRUE(client.read(msg));
  25713. ASSERT_TRUE(client.send("hello"));
  25714. ASSERT_TRUE(client.read(msg));
  25715. EXPECT_EQ("hello", msg);
  25716. client.close();
  25717. EXPECT_EQ(1, proxy.connect_hits());
  25718. auto target = "127.0.0.1:" + std::to_string(origin.port());
  25719. auto connect_req = proxy.connect_request();
  25720. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  25721. EXPECT_NE(std::string::npos,
  25722. connect_req.find("\r\nHost: " + target + "\r\n"));
  25723. }
  25724. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  25725. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25726. [](ws::WebSocketClient &cli) {
  25727. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25728. },
  25729. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  25730. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  25731. }
  25732. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  25733. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25734. [](ws::WebSocketClient &cli) {
  25735. cli.set_proxy_bearer_token_auth("proxy-token");
  25736. },
  25737. "Bearer proxy-token", "Bearer origin-token");
  25738. }
  25739. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  25740. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25741. proxy_tunnel_test::ScopedConnectProxy proxy(
  25742. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25743. "Basic " + detail::base64_encode("proxy-user:"),
  25744. "Basic realm=\"proxy\""));
  25745. ASSERT_NE(0, proxy.port());
  25746. ws::WebSocketClient client(origin.url());
  25747. client.set_proxy("127.0.0.1", proxy.port());
  25748. client.set_proxy_basic_auth("proxy-user", "");
  25749. auto res = client.connect();
  25750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25751. client.close();
  25752. EXPECT_EQ(1, proxy.connect_hits());
  25753. }
  25754. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  25755. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25756. proxy_tunnel_test::ScopedConnectProxy proxy(
  25757. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25758. "Bearer proxy-token", "Basic realm=\"proxy\""));
  25759. ASSERT_NE(0, proxy.port());
  25760. ws::WebSocketClient client(origin.url());
  25761. client.set_proxy("127.0.0.1", proxy.port());
  25762. auto res = client.connect();
  25763. EXPECT_FALSE(res);
  25764. EXPECT_EQ(Error::ProxyConnection, res.error());
  25765. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  25766. EXPECT_EQ("Basic realm=\"proxy\"",
  25767. res.get_header_value("Proxy-Authenticate"));
  25768. EXPECT_FALSE(client.is_open());
  25769. }
  25770. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  25771. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25772. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25773. ASSERT_NE(0, proxy.port());
  25774. ws::WebSocketClient client(origin.url());
  25775. client.set_proxy("127.0.0.1", proxy.port());
  25776. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25777. client.set_no_proxy({"127.0.0.1"});
  25778. auto res = client.connect();
  25779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25780. std::string msg;
  25781. ASSERT_TRUE(client.read(msg));
  25782. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  25783. << "proxy credentials must not reach a bypassed origin";
  25784. client.close();
  25785. EXPECT_EQ(0, proxy.connect_hits());
  25786. }
  25787. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  25788. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25789. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25790. ASSERT_NE(0, proxy.port());
  25791. ws::WebSocketClient client(origin.url());
  25792. client.set_proxy("127.0.0.1", proxy.port());
  25793. ASSERT_TRUE(client.connect());
  25794. ASSERT_TRUE(client.connect());
  25795. client.close();
  25796. EXPECT_EQ(2, proxy.connect_hits());
  25797. }
  25798. #ifdef CPPHTTPLIB_SSL_ENABLED
  25799. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  25800. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25801. proxy_tunnel_test::ScopedConnectProxy proxy(
  25802. origin.port(), [](const std::string &head) -> std::string {
  25803. if (head.find(
  25804. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  25805. std::string::npos) {
  25806. return proxy_tunnel_test::kTunnelEstablished;
  25807. }
  25808. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25809. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  25810. "nonce=\"abc\", algorithm=MD5\r\n"
  25811. "Content-Length: 0\r\n\r\n";
  25812. });
  25813. ASSERT_NE(0, proxy.port());
  25814. ws::WebSocketClient client(origin.url());
  25815. client.set_proxy("127.0.0.1", proxy.port());
  25816. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25817. auto res = client.connect();
  25818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25819. std::string msg;
  25820. ASSERT_TRUE(client.read(msg));
  25821. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  25822. client.close();
  25823. EXPECT_EQ(2, proxy.connect_hits());
  25824. }
  25825. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  25826. proxy_tunnel_test::ScopedSSLServer origin;
  25827. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  25828. origin.listen();
  25829. proxy_tunnel_test::ScopedConnectProxy proxy(
  25830. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25831. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  25832. ASSERT_NE(0, proxy.port());
  25833. ws::WebSocketClient client(
  25834. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  25835. client.enable_server_certificate_verification(false);
  25836. client.set_proxy("127.0.0.1", proxy.port());
  25837. client.set_proxy_bearer_token_auth("proxy-token");
  25838. auto res = client.connect();
  25839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25840. std::string msg;
  25841. ASSERT_TRUE(client.read(msg));
  25842. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  25843. << "Proxy-Authorization must not be sent inside the tunnel";
  25844. client.close();
  25845. EXPECT_EQ(1, proxy.connect_hits());
  25846. }
  25847. #endif