test.cc 948 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  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("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1470. // Server::read_content() keeps a FormFields::iterator alive across the
  1471. // content callbacks that fill the part it points at. The container is
  1472. // vector-backed, so a later emplace can reallocate and invalidate an older
  1473. // iterator; 64 parts grow the vector through seven reallocations, which
  1474. // checks that every part's content still lands in its own entry.
  1475. const size_t part_count = 64;
  1476. // One formula for both the parts sent and the values expected back, so the
  1477. // two cannot drift apart.
  1478. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1479. auto content_of = [](size_t i) {
  1480. return std::string(64, static_cast<char>('a' + (i % 26)));
  1481. };
  1482. Server svr;
  1483. std::vector<std::pair<std::string, std::string>> received;
  1484. svr.Post("/many", [&](const Request &req, Response &res) {
  1485. for (const auto &field : req.form.fields) {
  1486. received.emplace_back(field.first, field.second.content);
  1487. }
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. UploadFormDataItems items;
  1499. for (size_t i = 0; i < part_count; i++) {
  1500. items.push_back({name_of(i), content_of(i), "", ""});
  1501. }
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/many", items);
  1504. ASSERT_TRUE(res);
  1505. ASSERT_EQ(part_count, received.size());
  1506. for (size_t i = 0; i < part_count; i++) {
  1507. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1508. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1509. }
  1510. }
  1511. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1512. string content_type = "multipart/form-data; boundary=something";
  1513. string boundary;
  1514. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1515. EXPECT_TRUE(ret);
  1516. EXPECT_EQ(boundary, "something");
  1517. }
  1518. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1519. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1520. string boundary;
  1521. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1522. EXPECT_TRUE(ret);
  1523. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1524. }
  1525. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1526. string content_type =
  1527. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1528. string boundary;
  1529. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1530. EXPECT_TRUE(ret);
  1531. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1534. string content_type =
  1535. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1536. string boundary;
  1537. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1538. EXPECT_TRUE(ret);
  1539. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1542. const string boundary(70, 'a');
  1543. string content_type = "multipart/form-data; boundary=" + boundary;
  1544. string parsed;
  1545. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(parsed, boundary);
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1550. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1551. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1552. string parsed;
  1553. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1554. EXPECT_FALSE(ret);
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1557. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1558. // is 72 characters on the wire and still valid.
  1559. const string boundary(70, 'a');
  1560. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, boundary);
  1564. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1565. parsed.clear();
  1566. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1569. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1570. // The parameter parser must not treat that '=' as the key/value separator.
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1573. "charset=UTF-8";
  1574. string parsed;
  1575. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1576. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1579. // A ';' inside the quoted-string is part of the value, not a parameter
  1580. // separator, so it must not truncate the boundary.
  1581. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1582. string parsed;
  1583. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1584. EXPECT_EQ(parsed, "a;b");
  1585. }
  1586. TEST(ParseDispositionParamsTest, QuotedValues) {
  1587. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1588. // ';' and '=' are ordinary characters inside one.
  1589. struct {
  1590. const char *value;
  1591. std::vector<std::pair<const char *, const char *>> expected;
  1592. } cases[] = {
  1593. {"name=\"file1\"; filename=\"a.txt\"",
  1594. {{"name", "file1"}, {"filename", "a.txt"}}},
  1595. // Whitespace around '=' and ';' is still trimmed
  1596. {"name=\"file2\" ;filename = \"a.html\"",
  1597. {{"name", "file2"}, {"filename", "a.html"}}},
  1598. // '=' inside the value used to leave only the text after the last one
  1599. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1600. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1601. {"name=\"x=y\"", {{"name", "x=y"}}},
  1602. // ';' inside the value used to truncate the pair and leave a bogus one
  1603. {"name=\"file3\"; filename=\"a;b.txt\"",
  1604. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1605. // An unquoted value keeps working, and so does filename*
  1606. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1607. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1608. // A parameter with no key is dropped rather than turned into one whose
  1609. // key is the value
  1610. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1611. // An escaped quote does not end the value
  1612. {"name=\"a\\\"; filename=evil.php\"",
  1613. {{"name", "a\"; filename=evil.php"}}},
  1614. // Other backslashes, as in a Windows path, are kept
  1615. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1616. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1617. };
  1618. for (const auto &c : cases) {
  1619. Params params;
  1620. detail::parse_disposition_params(c.value, params);
  1621. for (const auto &kv : c.expected) {
  1622. auto it = params.find(kv.first);
  1623. ASSERT_NE(it, params.end())
  1624. << "value: " << c.value << ", key: " << kv.first;
  1625. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1626. }
  1627. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1628. }
  1629. }
  1630. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1631. Server svr;
  1632. std::string filename;
  1633. std::string content;
  1634. svr.Post("/upload", [&](const Request &req, Response &) {
  1635. const auto &file = req.form.get_file("file");
  1636. filename = file.filename;
  1637. content = file.content;
  1638. });
  1639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. thread.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. std::string body = "--B\r\n"
  1647. "Content-Disposition: form-data; name=\"file\"; "
  1648. "filename=\"a.txt\"\r\n"
  1649. "Content-Type: text/plain\r\n"
  1650. "\r\n"
  1651. "hello\r\n"
  1652. "--B--\r\n";
  1653. Client cli(HOST, PORT);
  1654. auto res = cli.Post(
  1655. "/upload",
  1656. [&](size_t offset, DataSink &sink) {
  1657. if (offset < body.size()) {
  1658. sink.write(&body[offset], 1);
  1659. } else {
  1660. sink.done();
  1661. }
  1662. return true;
  1663. },
  1664. "multipart/form-data; boundary=B");
  1665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1666. EXPECT_EQ(StatusCode::OK_200, res->status);
  1667. EXPECT_EQ("a.txt", filename);
  1668. EXPECT_EQ("hello", content);
  1669. }
  1670. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1671. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1672. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1673. Server svr;
  1674. std::string field_value, file_name, file_filename;
  1675. bool has_field = false, has_file = false;
  1676. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1677. has_field = req.form.has_field("x=y");
  1678. field_value = req.form.get_field("x=y");
  1679. has_file = req.form.has_file("file1");
  1680. const auto &file = req.form.get_file("file1");
  1681. file_name = file.name;
  1682. file_filename = file.filename;
  1683. res.set_content("ok", "text/plain");
  1684. });
  1685. auto port = svr.bind_to_any_port(HOST);
  1686. thread t = thread([&] { svr.listen_after_bind(); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. t.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. UploadFormDataItems items = {
  1694. {"x=y", "field-value", "", ""},
  1695. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1696. };
  1697. Client cli(HOST, port);
  1698. auto res = cli.Post("/quoted", items);
  1699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1700. ASSERT_EQ(StatusCode::OK_200, res->status);
  1701. EXPECT_TRUE(has_field);
  1702. EXPECT_EQ("field-value", field_value);
  1703. EXPECT_TRUE(has_file);
  1704. EXPECT_EQ("file1", file_name);
  1705. EXPECT_EQ("a;b=report.pdf", file_filename);
  1706. }
  1707. TEST(GetHeaderValueTest, DefaultValue) {
  1708. Headers headers = {{"Dummy", "Dummy"}};
  1709. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1710. EXPECT_STREQ("text/plain", val);
  1711. }
  1712. TEST(GetHeaderValueTest, DefaultValueInt) {
  1713. Headers headers = {{"Dummy", "Dummy"}};
  1714. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1715. EXPECT_EQ(100ull, val);
  1716. }
  1717. TEST(GetHeaderValueTest, RegularValue) {
  1718. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1719. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1720. EXPECT_STREQ("text/html", val);
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1723. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1725. EXPECT_STREQ("text/html", val);
  1726. }
  1727. TEST(GetHeaderValueTest, SetContent) {
  1728. Response res;
  1729. res.set_content("html", "text/html");
  1730. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1731. res.set_content("text", "text/plain");
  1732. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1733. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1734. }
  1735. TEST(GetHeaderValueTest, RegularValueInt) {
  1736. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1737. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1738. EXPECT_EQ(100ull, val);
  1739. }
  1740. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1741. Headers headers = {{"Content-Length", "x"}};
  1742. auto is_invalid_value = false;
  1743. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1744. is_invalid_value);
  1745. EXPECT_EQ(0ull, val);
  1746. EXPECT_TRUE(is_invalid_value);
  1747. }
  1748. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1749. // An all-digit value that overflows size_t must be reported as invalid, not
  1750. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1751. // a large length to a small one on 32-bit builds, leaving the framing length
  1752. // wrong while is_invalid_value stayed false.
  1753. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1754. auto is_invalid_value = false;
  1755. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1756. is_invalid_value);
  1757. EXPECT_TRUE(is_invalid_value);
  1758. // A well-formed length is unaffected.
  1759. Headers ok = {{"Content-Length", "1234"}};
  1760. is_invalid_value = false;
  1761. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1762. is_invalid_value);
  1763. EXPECT_EQ(1234ull, val);
  1764. EXPECT_FALSE(is_invalid_value);
  1765. }
  1766. TEST(GetHeaderValueTest, Range) {
  1767. {
  1768. Headers headers = {make_range_header({{1, -1}})};
  1769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1770. EXPECT_STREQ("bytes=1-", val);
  1771. }
  1772. {
  1773. Headers headers = {make_range_header({{-1, 1}})};
  1774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1775. EXPECT_STREQ("bytes=-1", val);
  1776. }
  1777. {
  1778. Headers headers = {make_range_header({{1, 10}})};
  1779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1780. EXPECT_STREQ("bytes=1-10", val);
  1781. }
  1782. {
  1783. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1785. EXPECT_STREQ("bytes=1-10, 100-", val);
  1786. }
  1787. {
  1788. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1789. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1790. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1791. }
  1792. {
  1793. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1794. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1795. EXPECT_STREQ("bytes=0-0, -1", val);
  1796. }
  1797. }
  1798. TEST(BearerTokenAuthTest, SchemeValidation) {
  1799. // A value shorter than "Bearer " must not throw from the fixed-length
  1800. // substr, and a non-Bearer scheme must not be reported as a token.
  1801. struct {
  1802. const char *value;
  1803. const char *expected;
  1804. } cases[] = {
  1805. {"x", ""},
  1806. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1807. {"Bearer abc123", "abc123"},
  1808. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1809. };
  1810. for (const auto &c : cases) {
  1811. Request req;
  1812. req.set_header("Authorization", c.value);
  1813. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1814. }
  1815. }
  1816. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1817. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1818. // to depend on the standard library (libstdc++ handed back duplicates in
  1819. // reverse insertion order, libc++ in insertion order).
  1820. Request req;
  1821. req.set_header("Accept-Encoding", "gzip");
  1822. req.set_header("Accept-Encoding", "deflate");
  1823. req.set_header("Accept-Encoding", "br");
  1824. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1825. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1826. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1827. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1828. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1829. }
  1830. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1831. Request req;
  1832. req.set_header("X-Test", "only");
  1833. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1834. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1835. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1836. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1837. }
  1838. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1839. Request req;
  1840. req.set_header("X-First", "1");
  1841. req.set_header("X-Test", "2");
  1842. req.params.emplace("first", "1");
  1843. req.params.emplace("test", "2");
  1844. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1845. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1846. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1847. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1848. // The second one is negative when read as a signed value
  1849. const auto max_id = (std::numeric_limits<size_t>::max)();
  1850. for (auto id : {max_id / 2, max_id}) {
  1851. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1852. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1853. EXPECT_EQ("", req.get_param_value("test", id));
  1854. EXPECT_EQ("", req.form.get_field("test", id));
  1855. EXPECT_EQ("", req.form.get_file("test", id).content);
  1856. }
  1857. }
  1858. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1859. Headers headers;
  1860. headers.emplace("Host", "example.com");
  1861. headers.emplace("Accept-Encoding", "gzip");
  1862. headers.emplace("User-Agent", "test");
  1863. headers.emplace("Accept-Encoding", "deflate");
  1864. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1865. "Accept-Encoding=deflate ",
  1866. entries_to_string(headers));
  1867. }
  1868. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1869. Headers headers = {{"Content-Type", "text/html"},
  1870. {"CONTENT-TYPE", "text/xml"}};
  1871. EXPECT_EQ(2U, headers.count("content-type"));
  1872. auto it = headers.find("content-type");
  1873. ASSERT_TRUE(it != headers.end());
  1874. EXPECT_EQ("text/html", it->second);
  1875. }
  1876. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1877. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1878. // drop only those fields and leave everything positioned between them.
  1879. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1880. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1881. auto rng = headers.equal_range("a");
  1882. headers.erase(rng.first, rng.second);
  1883. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1884. }
  1885. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1886. Headers headers = {
  1887. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1888. EXPECT_EQ(3U, headers.erase("A"));
  1889. EXPECT_EQ(0U, headers.count("A"));
  1890. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1891. }
  1892. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1893. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1894. headers.emplace_front("Host", "example.com");
  1895. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1896. entries_to_string(headers));
  1897. }
  1898. TEST(ParseHeaderValueTest, Range) {
  1899. {
  1900. Ranges ranges;
  1901. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1902. EXPECT_TRUE(ret);
  1903. EXPECT_EQ(1u, ranges.size());
  1904. EXPECT_EQ(1u, ranges[0].first);
  1905. EXPECT_EQ(-1, ranges[0].second);
  1906. }
  1907. {
  1908. Ranges ranges;
  1909. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1910. EXPECT_TRUE(ret);
  1911. EXPECT_EQ(1u, ranges.size());
  1912. EXPECT_EQ(-1, ranges[0].first);
  1913. EXPECT_EQ(1u, ranges[0].second);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(1u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. }
  1923. {
  1924. Ranges ranges;
  1925. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1926. EXPECT_FALSE(ret);
  1927. }
  1928. {
  1929. Ranges ranges;
  1930. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1931. EXPECT_TRUE(ret);
  1932. EXPECT_EQ(2u, ranges.size());
  1933. EXPECT_EQ(1u, ranges[0].first);
  1934. EXPECT_EQ(10u, ranges[0].second);
  1935. EXPECT_EQ(100u, ranges[1].first);
  1936. EXPECT_EQ(-1, ranges[1].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ(3u, ranges.size());
  1944. EXPECT_EQ(1u, ranges[0].first);
  1945. EXPECT_EQ(10u, ranges[0].second);
  1946. EXPECT_EQ(100u, ranges[1].first);
  1947. EXPECT_EQ(200u, ranges[1].second);
  1948. EXPECT_EQ(300u, ranges[2].first);
  1949. EXPECT_EQ(400u, ranges[2].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1962. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1963. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1964. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1965. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1966. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1967. EXPECT_FALSE(
  1968. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1969. EXPECT_TRUE(ranges.empty());
  1970. }
  1971. {
  1972. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1973. // remainder of the representation, so it stays accepted.
  1974. Ranges ranges;
  1975. auto ret =
  1976. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1977. EXPECT_TRUE(ret);
  1978. ASSERT_EQ(1u, ranges.size());
  1979. EXPECT_EQ(0, ranges[0].first);
  1980. EXPECT_EQ(-1, ranges[0].second);
  1981. }
  1982. // RFC 9110 14.1: range unit names are case-insensitive.
  1983. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1984. Ranges ranges;
  1985. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1986. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1987. }
  1988. }
  1989. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1990. Request req;
  1991. req.set_header("Accept-Encoding", "gzip");
  1992. Response res;
  1993. res.set_header("Content-Type", "text/plain");
  1994. auto ret = detail::encoding_type(req, res);
  1995. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2004. Response res;
  2005. res.set_header("Content-Type", "text/plain");
  2006. auto ret = detail::encoding_type(req, res);
  2007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2009. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2010. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2011. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2013. #else
  2014. EXPECT_TRUE(ret == detail::EncodingType::None);
  2015. #endif
  2016. }
  2017. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding",
  2020. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2021. Response res;
  2022. res.set_header("Content-Type", "text/plain");
  2023. auto ret = detail::encoding_type(req, res);
  2024. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2026. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2029. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2030. #else
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. #endif
  2033. }
  2034. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2035. // All supported encodings rejected with q=0 should return None
  2036. Request req;
  2037. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2038. Response res;
  2039. res.set_header("Content-Type", "text/plain");
  2040. auto ret = detail::encoding_type(req, res);
  2041. EXPECT_TRUE(ret == detail::EncodingType::None);
  2042. }
  2043. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2044. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2045. Request req;
  2046. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2047. Response res;
  2048. res.set_header("Content-Type", "text/plain");
  2049. auto ret = detail::encoding_type(req, res);
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. }
  2052. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2053. Request req;
  2054. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2055. Response res;
  2056. res.set_header("Content-Type", "text/plain");
  2057. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2058. }
  2059. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2060. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2061. Request req;
  2062. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2063. Response res;
  2064. res.set_header("Content-Type", "text/plain");
  2065. auto ret = detail::encoding_type(req, res);
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. }
  2068. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2069. // RFC 7231: Accept-Encoding values are case-insensitive
  2070. Request req;
  2071. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2072. Response res;
  2073. res.set_header("Content-Type", "text/plain");
  2074. auto ret = detail::encoding_type(req, res);
  2075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2077. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2078. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2079. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2081. #else
  2082. EXPECT_TRUE(ret == detail::EncodingType::None);
  2083. #endif
  2084. }
  2085. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2086. // q value should determine priority, not hardcoded order
  2087. Request req;
  2088. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2089. Response res;
  2090. res.set_header("Content-Type", "text/plain");
  2091. auto ret = detail::encoding_type(req, res);
  2092. // gzip has highest q=1.0, so it should be selected even though
  2093. // br and zstd are also supported
  2094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2096. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2098. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #else
  2101. EXPECT_TRUE(ret == detail::EncodingType::None);
  2102. #endif
  2103. }
  2104. TEST(BufferStreamTest, read) {
  2105. detail::BufferStream strm1;
  2106. Stream &strm = strm1;
  2107. EXPECT_EQ(5, strm.write("hello"));
  2108. char buf[512];
  2109. EXPECT_EQ(2, strm.read(buf, 2));
  2110. EXPECT_EQ('h', buf[0]);
  2111. EXPECT_EQ('e', buf[1]);
  2112. EXPECT_EQ(2, strm.read(buf, 2));
  2113. EXPECT_EQ('l', buf[0]);
  2114. EXPECT_EQ('l', buf[1]);
  2115. EXPECT_EQ(1, strm.read(buf, 1));
  2116. EXPECT_EQ('o', buf[0]);
  2117. EXPECT_EQ(0, strm.read(buf, 1));
  2118. }
  2119. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2120. auto host = "www.httpwatch.com";
  2121. auto ip = hosted_at(host);
  2122. EXPECT_EQ("23.96.13.243", ip);
  2123. std::vector<std::string> addrs;
  2124. hosted_at(host, addrs);
  2125. EXPECT_EQ(1u, addrs.size());
  2126. }
  2127. #if 0 // It depends on each test environment...
  2128. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2129. auto host = "www.youtube.com";
  2130. std::vector<std::string> addrs;
  2131. hosted_at(host, addrs);
  2132. EXPECT_EQ(20u, addrs.size());
  2133. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2134. EXPECT_TRUE(it != addrs.end());
  2135. }
  2136. #endif
  2137. class ChunkedEncodingTest : public ::testing::Test {
  2138. protected:
  2139. ChunkedEncodingTest()
  2140. : cli_(HOST, PORT)
  2141. #ifdef CPPHTTPLIB_SSL_ENABLED
  2142. ,
  2143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2144. #endif
  2145. {
  2146. cli_.set_connection_timeout(2);
  2147. #ifdef CPPHTTPLIB_SSL_ENABLED
  2148. cli_.enable_server_certificate_verification(false);
  2149. #endif
  2150. }
  2151. virtual void SetUp() {
  2152. read_file("./image.jpg", image_data_);
  2153. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2154. res.set_content("Hello World!", "text/plain");
  2155. });
  2156. svr_.Get(
  2157. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2158. res.set_chunked_content_provider(
  2159. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2160. size_t remaining = image_data_.size() - offset;
  2161. if (remaining == 0) {
  2162. sink.done();
  2163. } else {
  2164. constexpr size_t CHUNK_SIZE = 1024;
  2165. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2166. sink.write(&image_data_[offset], send_size);
  2167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2168. }
  2169. return true;
  2170. });
  2171. });
  2172. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2173. svr_.wait_until_ready();
  2174. }
  2175. virtual void TearDown() {
  2176. svr_.stop();
  2177. if (!request_threads_.empty()) {
  2178. std::this_thread::sleep_for(std::chrono::seconds(1));
  2179. for (auto &t : request_threads_) {
  2180. t.join();
  2181. }
  2182. }
  2183. t_.join();
  2184. }
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. SSLClient cli_;
  2187. SSLServer svr_;
  2188. #else
  2189. Client cli_;
  2190. Server svr_;
  2191. #endif
  2192. thread t_;
  2193. std::vector<thread> request_threads_;
  2194. std::string image_data_;
  2195. };
  2196. TEST_F(ChunkedEncodingTest, NormalGet) {
  2197. auto res = cli_.Get("/chunked");
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. std::string out;
  2200. read_file("./image.jpg", out);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ(out, res->body);
  2203. }
  2204. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2205. std::string body;
  2206. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2207. body.append(data, data_length);
  2208. return true;
  2209. });
  2210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2211. std::string out;
  2212. read_file("./image.jpg", out);
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. EXPECT_EQ(out, body);
  2215. }
  2216. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2217. std::string body;
  2218. auto res = cli_.Get(
  2219. "/chunked",
  2220. [&](const Response &response) {
  2221. EXPECT_EQ(StatusCode::OK_200, response.status);
  2222. return true;
  2223. },
  2224. [&](const char *data, size_t data_length) {
  2225. body.append(data, data_length);
  2226. return true;
  2227. });
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, body);
  2233. }
  2234. TEST(RangeTest, FromHTTPBin_Online) {
  2235. auto host = "httpbingo.org";
  2236. auto path = std::string{"/range/32"};
  2237. #ifdef CPPHTTPLIB_SSL_ENABLED
  2238. auto port = 443;
  2239. SSLClient cli(host, port);
  2240. #else
  2241. auto port = 80;
  2242. Client cli(host, port);
  2243. #endif
  2244. cli.set_connection_timeout(5);
  2245. {
  2246. auto res = cli.Get(path);
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. }
  2251. {
  2252. Headers headers = {make_range_header({{1, -1}})};
  2253. auto res = cli.Get(path, headers);
  2254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2255. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2257. }
  2258. {
  2259. Headers headers = {make_range_header({{1, 10}})};
  2260. auto res = cli.Get(path, headers);
  2261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2262. EXPECT_EQ("bcdefghijk", res->body);
  2263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2264. }
  2265. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2266. // entire resource, while the original httpbin returned 200. Both are
  2267. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2268. {
  2269. Headers headers = {make_range_header({{0, 31}})};
  2270. auto res = cli.Get(path, headers);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2274. res->status == StatusCode::PartialContent_206);
  2275. }
  2276. {
  2277. Headers headers = {make_range_header({{0, -1}})};
  2278. auto res = cli.Get(path, headers);
  2279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2280. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2281. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2282. res->status == StatusCode::PartialContent_206);
  2283. }
  2284. // go-httpbin returns 206 with clamped range for over-range requests,
  2285. // while the original httpbin returned 416. Both behaviors are observed
  2286. // in real servers, so we only verify the request succeeds.
  2287. {
  2288. Headers headers = {make_range_header({{0, 32}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. }
  2292. }
  2293. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2294. auto host = "unresolvableaddress.local";
  2295. auto path = std::string{"/"};
  2296. #ifdef CPPHTTPLIB_SSL_ENABLED
  2297. auto port = 443;
  2298. SSLClient cli(host, port);
  2299. #else
  2300. auto port = 80;
  2301. Client cli(host, port);
  2302. #endif
  2303. cli.set_connection_timeout(1);
  2304. {
  2305. auto res = cli.Get(path);
  2306. ASSERT_FALSE(res);
  2307. }
  2308. std::this_thread::sleep_for(std::chrono::seconds(8));
  2309. }
  2310. #if defined(__linux__) && defined(__GLIBC__) && \
  2311. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2312. // Forward declaration: in split builds split.py strips `inline` and moves the
  2313. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2314. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2315. // against the symbol in both header-only and split builds.
  2316. namespace httplib {
  2317. namespace detail {
  2318. int getaddrinfo_with_timeout(const char *node, const char *service,
  2319. const struct addrinfo *hints,
  2320. struct addrinfo **res, time_t timeout_sec);
  2321. } // namespace detail
  2322. } // namespace httplib
  2323. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2324. //
  2325. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2326. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2327. // gai_suspend() call hits the connection timeout the function calls
  2328. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2329. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2330. // still alive and still references the now-destroyed stack frame.
  2331. //
  2332. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2333. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2334. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2335. // and runs them in a container.
  2336. namespace {
  2337. bool should_run_issue_2431_tests() {
  2338. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2339. return v && *v && std::string(v) != "0";
  2340. }
  2341. std::string unique_unresolvable_host(int n) {
  2342. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2343. // glibc still asks the configured nameserver — which is exactly the path
  2344. // we want to exercise. A unique label per call avoids the resolver cache.
  2345. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2346. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2347. std::to_string(n) + ".invalid";
  2348. }
  2349. } // namespace
  2350. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2351. if (!should_run_issue_2431_tests()) {
  2352. GTEST_SKIP()
  2353. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2354. }
  2355. for (int i = 0; i < 8; ++i) {
  2356. struct addrinfo hints;
  2357. memset(&hints, 0, sizeof(hints));
  2358. hints.ai_family = AF_UNSPEC;
  2359. hints.ai_socktype = SOCK_STREAM;
  2360. auto host = unique_unresolvable_host(i);
  2361. struct addrinfo *result = nullptr;
  2362. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2363. &result, /*timeout_sec=*/1);
  2364. if (rc == 0 && result) { freeaddrinfo(result); }
  2365. }
  2366. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2367. // stack region they still believe holds their gaicb.
  2368. std::this_thread::sleep_for(std::chrono::seconds(3));
  2369. }
  2370. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2371. if (!should_run_issue_2431_tests()) {
  2372. GTEST_SKIP()
  2373. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2374. }
  2375. std::atomic<bool> stop{false};
  2376. std::vector<std::thread> threads;
  2377. for (int t = 0; t < 8; ++t) {
  2378. threads.emplace_back([t, &stop] {
  2379. int i = 0;
  2380. while (!stop.load(std::memory_order_relaxed)) {
  2381. struct addrinfo hints;
  2382. memset(&hints, 0, sizeof(hints));
  2383. hints.ai_family = AF_UNSPEC;
  2384. hints.ai_socktype = SOCK_STREAM;
  2385. auto host = unique_unresolvable_host(t * 100000 + i++);
  2386. struct addrinfo *result = nullptr;
  2387. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2388. &result, /*timeout_sec=*/1);
  2389. if (rc == 0 && result) { freeaddrinfo(result); }
  2390. }
  2391. });
  2392. }
  2393. std::this_thread::sleep_for(std::chrono::seconds(8));
  2394. stop.store(true, std::memory_order_relaxed);
  2395. for (auto &th : threads) {
  2396. th.join();
  2397. }
  2398. std::this_thread::sleep_for(std::chrono::seconds(3));
  2399. }
  2400. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2401. if (!should_run_issue_2431_tests()) {
  2402. GTEST_SKIP()
  2403. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2404. }
  2405. std::atomic<bool> stop{false};
  2406. std::vector<std::thread> threads;
  2407. for (int t = 0; t < 8; ++t) {
  2408. threads.emplace_back([t, &stop] {
  2409. int i = 0;
  2410. while (!stop.load(std::memory_order_relaxed)) {
  2411. auto host = unique_unresolvable_host(t * 100000 + i++);
  2412. Client cli(host, 80);
  2413. cli.set_connection_timeout(1, 0);
  2414. cli.set_read_timeout(1, 0);
  2415. cli.set_write_timeout(1, 0);
  2416. (void)cli.Get("/");
  2417. }
  2418. });
  2419. }
  2420. std::this_thread::sleep_for(std::chrono::seconds(8));
  2421. stop.store(true, std::memory_order_relaxed);
  2422. for (auto &th : threads) {
  2423. th.join();
  2424. }
  2425. std::this_thread::sleep_for(std::chrono::seconds(3));
  2426. }
  2427. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2428. TEST(ConnectionErrorTest, InvalidHost) {
  2429. auto host = "-abcde.com";
  2430. #ifdef CPPHTTPLIB_SSL_ENABLED
  2431. auto port = 443;
  2432. SSLClient cli(host, port);
  2433. #else
  2434. auto port = 80;
  2435. Client cli(host, port);
  2436. #endif
  2437. cli.set_connection_timeout(std::chrono::seconds(2));
  2438. auto res = cli.Get("/");
  2439. ASSERT_TRUE(!res);
  2440. EXPECT_EQ(Error::Connection, res.error());
  2441. }
  2442. TEST(ConnectionErrorTest, InvalidHost2) {
  2443. auto host = "httpcan.org/";
  2444. #ifdef CPPHTTPLIB_SSL_ENABLED
  2445. SSLClient cli(host);
  2446. #else
  2447. Client cli(host);
  2448. #endif
  2449. cli.set_connection_timeout(std::chrono::seconds(2));
  2450. auto res = cli.Get("/");
  2451. ASSERT_TRUE(!res);
  2452. EXPECT_EQ(Error::Connection, res.error());
  2453. }
  2454. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2455. auto host = "httpcan.org/";
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. SSLClient cli(host);
  2458. #else
  2459. Client cli(host);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. stringstream s;
  2465. s << "error code: " << res.error();
  2466. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2467. }
  2468. TEST(ConnectionErrorTest, InvalidPort) {
  2469. auto host = "localhost";
  2470. auto port = 44380;
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. SSLClient cli(host, port);
  2473. #else
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_TRUE(Error::Connection == res.error() ||
  2480. Error::ConnectionTimeout == res.error());
  2481. }
  2482. TEST(ConnectionErrorTest, Timeout_Online) {
  2483. auto host = "google.com";
  2484. #ifdef CPPHTTPLIB_SSL_ENABLED
  2485. auto port = 44380;
  2486. SSLClient cli(host, port);
  2487. #else
  2488. auto port = 8080;
  2489. Client cli(host, port);
  2490. #endif
  2491. cli.set_connection_timeout(std::chrono::seconds(2));
  2492. // only probe one address type so that the error reason
  2493. // correlates to the timed-out IPv4, not the unsupported
  2494. // IPv6 connection attempt
  2495. cli.set_address_family(AF_INET);
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2499. }
  2500. TEST(CancelTest, NoCancel_Online) {
  2501. auto host = "httpbingo.org";
  2502. auto path = std::string{"/range/32"};
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. auto port = 443;
  2505. SSLClient cli(host, port);
  2506. #else
  2507. auto port = 80;
  2508. Client cli(host, port);
  2509. #endif
  2510. cli.set_connection_timeout(std::chrono::seconds(5));
  2511. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. }
  2516. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2517. // Use /bytes with a large payload so that the DownloadProgress callback
  2518. // (which only fires for Content-Length responses) is invoked before the
  2519. // entire body is received, giving cancellation a chance to fire.
  2520. auto host = "httpbingo.org";
  2521. auto path = std::string{"/bytes/524288"};
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. auto port = 443;
  2524. SSLClient cli(host, port);
  2525. #else
  2526. auto port = 80;
  2527. Client cli(host, port);
  2528. #endif
  2529. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. TEST(CancelTest, WithCancelLargePayload_Online) {
  2535. auto host = "httpbingo.org";
  2536. auto path = std::string{"/bytes/524288"};
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 443;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 80;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. uint32_t count = 0;
  2546. auto res =
  2547. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, NoCancelPost) {
  2552. Server svr;
  2553. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return true; });
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ("Hello World!", res->body);
  2570. EXPECT_EQ(StatusCode::OK_200, res->status);
  2571. }
  2572. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2573. Server svr;
  2574. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content("Hello World!", "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_connection_timeout(std::chrono::seconds(5));
  2586. auto res =
  2587. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2588. "application/json", [](uint64_t, uint64_t) { return false; });
  2589. ASSERT_TRUE(!res);
  2590. EXPECT_EQ(Error::Canceled, res.error());
  2591. }
  2592. TEST(CancelTest, WithCancelLargePayloadPost) {
  2593. Server svr;
  2594. svr.set_payload_max_length(200 * 1024 * 1024);
  2595. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2596. res.set_content(LARGE_DATA, "text/plain");
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. Client cli(HOST, PORT);
  2606. cli.set_payload_max_length(200 * 1024 * 1024);
  2607. cli.set_connection_timeout(std::chrono::seconds(5));
  2608. auto res =
  2609. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2610. "application/json", [](uint64_t, uint64_t) { return false; });
  2611. ASSERT_TRUE(!res);
  2612. EXPECT_EQ(Error::Canceled, res.error());
  2613. }
  2614. TEST(CancelTest, NoCancelPut) {
  2615. Server svr;
  2616. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("Hello World!", "text/plain");
  2618. });
  2619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2620. auto se = detail::scope_exit([&] {
  2621. svr.stop();
  2622. thread.join();
  2623. ASSERT_FALSE(svr.is_running());
  2624. });
  2625. svr.wait_until_ready();
  2626. Client cli(HOST, PORT);
  2627. cli.set_connection_timeout(std::chrono::seconds(5));
  2628. auto res =
  2629. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2630. "application/json", [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("Hello World!", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2636. Server svr;
  2637. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. });
  2640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2641. auto se = detail::scope_exit([&] {
  2642. svr.stop();
  2643. thread.join();
  2644. ASSERT_FALSE(svr.is_running());
  2645. });
  2646. svr.wait_until_ready();
  2647. Client cli(HOST, PORT);
  2648. cli.set_connection_timeout(std::chrono::seconds(5));
  2649. auto res =
  2650. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2651. "application/json", [](uint64_t, uint64_t) { return false; });
  2652. ASSERT_TRUE(!res);
  2653. EXPECT_EQ(Error::Canceled, res.error());
  2654. }
  2655. TEST(CancelTest, WithCancelLargePayloadPut) {
  2656. Server svr;
  2657. svr.set_payload_max_length(200 * 1024 * 1024);
  2658. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2659. res.set_content(LARGE_DATA, "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. Client cli(HOST, PORT);
  2669. cli.set_payload_max_length(200 * 1024 * 1024);
  2670. cli.set_connection_timeout(std::chrono::seconds(5));
  2671. auto res =
  2672. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2673. "application/json", [](uint64_t, uint64_t) { return false; });
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Canceled, res.error());
  2676. }
  2677. TEST(CancelTest, NoCancelPatch) {
  2678. Server svr;
  2679. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2680. res.set_content("Hello World!", "text/plain");
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, PORT);
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res =
  2692. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2693. "application/json", [](uint64_t, uint64_t) { return true; });
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ("Hello World!", res->body);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. }
  2698. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2699. Server svr;
  2700. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2701. res.set_content("Hello World!", "text/plain");
  2702. });
  2703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2704. auto se = detail::scope_exit([&] {
  2705. svr.stop();
  2706. thread.join();
  2707. ASSERT_FALSE(svr.is_running());
  2708. });
  2709. svr.wait_until_ready();
  2710. Client cli(HOST, PORT);
  2711. cli.set_connection_timeout(std::chrono::seconds(5));
  2712. auto res =
  2713. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2714. "application/json", [](uint64_t, uint64_t) { return false; });
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Canceled, res.error());
  2717. }
  2718. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2719. Server svr;
  2720. svr.set_payload_max_length(200 * 1024 * 1024);
  2721. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2722. res.set_content(LARGE_DATA, "text/plain");
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. Client cli(HOST, PORT);
  2732. cli.set_payload_max_length(200 * 1024 * 1024);
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res =
  2735. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2736. "application/json", [](uint64_t, uint64_t) { return false; });
  2737. ASSERT_TRUE(!res);
  2738. EXPECT_EQ(Error::Canceled, res.error());
  2739. }
  2740. TEST(CancelTest, NoCancelDelete) {
  2741. Server svr;
  2742. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2743. res.set_content("Hello World!", "text/plain");
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, PORT);
  2753. cli.set_connection_timeout(std::chrono::seconds(5));
  2754. auto res =
  2755. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2756. "application/json", [](uint64_t, uint64_t) { return true; });
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("Hello World!", res->body);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2762. Server svr;
  2763. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. Client cli(HOST, PORT);
  2774. cli.set_connection_timeout(std::chrono::seconds(5));
  2775. auto res =
  2776. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2777. "application/json", [](uint64_t, uint64_t) { return false; });
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2782. Server svr;
  2783. svr.set_payload_max_length(200 * 1024 * 1024);
  2784. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content(LARGE_DATA, "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_payload_max_length(200 * 1024 * 1024);
  2796. cli.set_connection_timeout(std::chrono::seconds(5));
  2797. auto res =
  2798. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2799. "application/json", [](uint64_t, uint64_t) { return false; });
  2800. ASSERT_TRUE(!res);
  2801. EXPECT_EQ(Error::Canceled, res.error());
  2802. }
  2803. static std::string remove_whitespace(const std::string &input) {
  2804. std::string output;
  2805. output.reserve(input.size());
  2806. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2807. [](unsigned char c) { return !std::isspace(c); });
  2808. return output;
  2809. }
  2810. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2811. auto host = "httpbingo.org";
  2812. auto path = std::string{"/basic-auth/hello/world"};
  2813. #ifdef CPPHTTPLIB_SSL_ENABLED
  2814. auto port = 443;
  2815. SSLClient cli(host, port);
  2816. #else
  2817. auto port = 80;
  2818. Client cli(host, port);
  2819. #endif
  2820. {
  2821. auto res = cli.Get(path);
  2822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2823. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2824. }
  2825. {
  2826. auto res = cli.Get(
  2827. path, Headers{make_basic_authentication_header("hello", "world")});
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. auto body = remove_whitespace(res->body);
  2830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2832. EXPECT_EQ(StatusCode::OK_200, res->status);
  2833. }
  2834. {
  2835. cli.set_basic_auth("hello", "world");
  2836. auto res = cli.Get(path);
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. auto body = remove_whitespace(res->body);
  2839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2841. EXPECT_EQ(StatusCode::OK_200, res->status);
  2842. }
  2843. {
  2844. cli.set_basic_auth("hello", "bad");
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. cli.set_basic_auth("bad", "world");
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2854. }
  2855. }
  2856. #ifdef CPPHTTPLIB_SSL_ENABLED
  2857. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2858. auto host = "httpbingo.org";
  2859. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2860. auto paths = std::vector<std::string>{
  2861. "/digest-auth/auth/hello/world/MD5",
  2862. "/digest-auth/auth/hello/world/SHA-256",
  2863. };
  2864. auto port = 443;
  2865. SSLClient cli(host, port);
  2866. {
  2867. auto res = cli.Get(unauth_path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. cli.set_digest_auth("hello", "world");
  2873. for (const auto &path : paths) {
  2874. auto res = cli.Get(path.c_str());
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. auto body = remove_whitespace(res->body);
  2877. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2878. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. cli.set_digest_auth("hello", "bad");
  2882. for (const auto &path : paths) {
  2883. auto res = cli.Get(path.c_str());
  2884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2886. }
  2887. }
  2888. }
  2889. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2890. // comma-separated list of challenges, and each challenge may itself carry a
  2891. // comma-separated auth-param list, so a server can legally offer Basic
  2892. // before Digest, either as two field lines or packed into one. Runs one 401
  2893. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2894. // value() joins them in receipt order) and checks that the retry carries a
  2895. // well-formed Digest Authorization header naming expected_realm.
  2896. static void
  2897. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2898. const std::string &expected_realm) {
  2899. std::atomic<int> hits{0};
  2900. Server svr;
  2901. svr.Get("/x", [&](const Request &req, Response &res) {
  2902. if (++hits == 1) {
  2903. res.status = StatusCode::Unauthorized_401;
  2904. for (const auto &challenge : challenges) {
  2905. res.set_header("WWW-Authenticate", challenge);
  2906. }
  2907. } else {
  2908. auto authorization = req.get_header_value("Authorization");
  2909. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2910. EXPECT_NE(std::string::npos,
  2911. authorization.find("realm=\"" + expected_realm + "\""));
  2912. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2913. res.set_content("ok", "text/plain");
  2914. }
  2915. });
  2916. auto port = svr.bind_to_any_port(HOST);
  2917. std::thread t([&]() { svr.listen_after_bind(); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. t.join();
  2921. });
  2922. svr.wait_until_ready();
  2923. Client cli(HOST, port);
  2924. cli.set_digest_auth("hello", "world");
  2925. auto res = cli.Get("/x");
  2926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2927. EXPECT_EQ(2, hits.load());
  2928. }
  2929. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2930. static const char *kDigestChallenge =
  2931. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2932. "algorithm=MD5";
  2933. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2934. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2935. "testrealm");
  2936. }
  2937. // Same challenge list with the schemes in the opposite order, to make sure
  2938. // the fix above didn't just special-case "Basic first".
  2939. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2940. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2941. "testrealm");
  2942. }
  2943. // A comma inside a quoted auth-param value must not be mistaken for the
  2944. // separator between two challenges (or two auth-params).
  2945. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2946. run_digest_challenge_list_test(
  2947. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2948. "algorithm=MD5"},
  2949. "test,realm");
  2950. }
  2951. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2952. // make_digest_authentication_header() dereferences both unconditionally, so
  2953. // a server sending a challenge missing either one must not be treated as
  2954. // usable -- doing so used to crash the client with std::out_of_range.
  2955. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2958. res.status = StatusCode::Unauthorized_401;
  2959. res.set_header("WWW-Authenticate", challenge);
  2960. });
  2961. auto port = svr.bind_to_any_port(HOST);
  2962. std::thread t([&]() { svr.listen_after_bind(); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. t.join();
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, port);
  2969. cli.set_digest_auth("hello", "world");
  2970. auto res = cli.Get("/x");
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2973. }
  2974. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2975. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2976. }
  2977. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2978. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2979. }
  2980. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2981. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2982. }
  2983. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2984. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2985. // when storing the values, so the header builder has to re-escape them (and
  2986. // keep algorithm a bare token); otherwise the value breaks out of its
  2987. // quoted-string and injects extra auth-params into the client's Authorization.
  2988. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2989. std::atomic<int> hits{0};
  2990. std::string authorization;
  2991. Server svr;
  2992. svr.Get("/x", [&](const Request &req, Response &res) {
  2993. if (++hits == 1) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. // On the wire the quotes embedded in the values are backslash-escaped.
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"testrealm\", "
  2998. "nonce=\"n\\\"; injected=\\\"x\", "
  2999. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3000. } else {
  3001. authorization = req.get_header_value("Authorization");
  3002. res.set_content("ok", "text/plain");
  3003. }
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/x");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(2, hits.load());
  3017. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3018. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3019. // inside its quoted-string rather than starting an "injected" auth-param.
  3020. EXPECT_NE(std::string::npos,
  3021. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3022. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3023. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3024. }
  3025. #endif
  3026. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3027. auto host = "google.com";
  3028. auto another_host = "example.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3041. auto host = "google.com";
  3042. auto wrong_ip = "0.0.0.0";
  3043. #ifdef CPPHTTPLIB_SSL_ENABLED
  3044. SSLClient cli(host);
  3045. #else
  3046. Client cli(host);
  3047. #endif
  3048. cli.set_hostname_addr_map({{host, wrong_ip}});
  3049. auto res = cli.Get("/");
  3050. ASSERT_TRUE(!res);
  3051. EXPECT_EQ(Error::Connection, res.error());
  3052. }
  3053. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3054. // A mapped value that is not an IP literal must be resolved. "localhost"
  3055. // resolves from the hosts file, so this test needs no external DNS.
  3056. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3057. auto host = "target.invalid";
  3058. Server svr;
  3059. std::string received_host;
  3060. svr.Get("/hi", [&](const Request &req, Response &res) {
  3061. received_host = req.get_header_value("Host");
  3062. res.set_content("Hello World!", "text/plain");
  3063. });
  3064. auto port = svr.bind_to_any_port(HOST);
  3065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. Client cli(host, port);
  3073. cli.set_hostname_addr_map({{host, HOST}});
  3074. auto res = cli.Get("/hi");
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. // The mapping only redirects the connection; the identity stays host_.
  3078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3079. }
  3080. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3081. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3082. auto host = "target.invalid";
  3083. Server svr;
  3084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3085. res.set_content("Hello World!", "text/plain");
  3086. });
  3087. auto port = svr.bind_to_any_port("127.0.0.1");
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(host, port);
  3096. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3097. auto res = cli.Get("/hi");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. }
  3101. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3102. // An empty mapped value must leave host_ as the connection target. Without
  3103. // that guard the empty value would become the host argument, getaddrinfo
  3104. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3105. // loopback - silently connecting somewhere the caller never asked for.
  3106. // The server listens on loopback, so such a fallback would succeed and is
  3107. // therefore observable as a failure of this test.
  3108. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3109. Server svr;
  3110. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3111. res.set_content("Hello World!", "text/plain");
  3112. });
  3113. auto port = svr.bind_to_any_port(HOST);
  3114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3115. auto se = detail::scope_exit([&] {
  3116. svr.stop();
  3117. thread.join();
  3118. ASSERT_FALSE(svr.is_running());
  3119. });
  3120. svr.wait_until_ready();
  3121. Client cli(blackhole, port);
  3122. cli.set_hostname_addr_map({{blackhole, ""}});
  3123. cli.set_connection_timeout(1);
  3124. auto res = cli.Get("/hi");
  3125. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3126. }
  3127. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/absolute-redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(RelativeRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/relative-redirect/3"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::OK_200, res->status);
  3165. }
  3166. TEST(TooManyRedirectTest, Redirect_Online) {
  3167. auto host = "httpbingo.org";
  3168. auto path = std::string{"/redirect/21"};
  3169. #ifdef CPPHTTPLIB_SSL_ENABLED
  3170. SSLClient cli(host);
  3171. #else
  3172. Client cli(host);
  3173. #endif
  3174. cli.set_follow_location(true);
  3175. auto res = cli.Get(path);
  3176. ASSERT_TRUE(!res);
  3177. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3178. }
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. TEST(YahooRedirectTest, Redirect_Online) {
  3181. Client cli("yahoo.com");
  3182. auto res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3185. cli.set_follow_location(true);
  3186. res = cli.Get("/");
  3187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3188. EXPECT_EQ(StatusCode::OK_200, res->status);
  3189. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3190. }
  3191. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3192. #define REDIR_HOST "httpbingo.org"
  3193. #define REDIR_PATH "/redirect-to"
  3194. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3195. SSLClient cli(REDIR_HOST);
  3196. cli.set_follow_location(true);
  3197. auto res =
  3198. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3203. SSLClient cli(REDIR_HOST);
  3204. cli.set_follow_location(true);
  3205. Params params;
  3206. params.emplace("url", "http://example.com");
  3207. params.emplace("status_code", "302");
  3208. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. }
  3212. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3213. SSLClient cli(REDIR_HOST);
  3214. cli.set_follow_location(true);
  3215. Params params;
  3216. params.emplace("url", "http://example.com");
  3217. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(UrlWithSpace, Redirect_Online) {
  3222. SSLClient cli("edge.forgecdn.net");
  3223. cli.set_follow_location(true);
  3224. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3228. }
  3229. #endif
  3230. #if !defined(_WIN32) && !defined(_WIN64)
  3231. TEST(ReceiveSignals, Signal) {
  3232. auto setupSignalHandlers = []() {
  3233. struct sigaction act;
  3234. sigemptyset(&act.sa_mask);
  3235. act.sa_flags = SA_SIGINFO;
  3236. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3237. switch (sig) {
  3238. case SIGINT:
  3239. default: break;
  3240. }
  3241. };
  3242. ::sigaction(SIGINT, &act, nullptr);
  3243. };
  3244. Server svr;
  3245. int port = 0;
  3246. auto thread = std::thread([&]() {
  3247. setupSignalHandlers();
  3248. port = svr.bind_to_any_port(HOST);
  3249. svr.listen_after_bind();
  3250. });
  3251. auto se = detail::scope_exit([&] {
  3252. svr.stop();
  3253. thread.join();
  3254. ASSERT_FALSE(svr.is_running());
  3255. });
  3256. svr.wait_until_ready();
  3257. ASSERT_TRUE(svr.is_running());
  3258. pthread_kill(thread.native_handle(), SIGINT);
  3259. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3260. ASSERT_TRUE(svr.is_running());
  3261. }
  3262. #endif
  3263. TEST(RedirectToDifferentPort, Redirect) {
  3264. Server svr1;
  3265. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3266. res.set_content("Hello World!", "text/plain");
  3267. });
  3268. int svr1_port = 0;
  3269. auto thread1 = std::thread([&]() {
  3270. svr1_port = svr1.bind_to_any_port(HOST);
  3271. svr1.listen_after_bind();
  3272. });
  3273. Server svr2;
  3274. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3275. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3276. });
  3277. int svr2_port = 0;
  3278. auto thread2 = std::thread([&]() {
  3279. svr2_port = svr2.bind_to_any_port(HOST);
  3280. svr2.listen_after_bind();
  3281. });
  3282. auto se = detail::scope_exit([&] {
  3283. svr2.stop();
  3284. thread2.join();
  3285. svr1.stop();
  3286. thread1.join();
  3287. ASSERT_FALSE(svr2.is_running());
  3288. ASSERT_FALSE(svr1.is_running());
  3289. });
  3290. svr1.wait_until_ready();
  3291. svr2.wait_until_ready();
  3292. Client cli("localhost", svr2_port);
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/2");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("Hello World!", res->body);
  3298. }
  3299. // GET /redir on one server redirects to /target on another port, so the
  3300. // client follows it with a new client.
  3301. static Result
  3302. GetThroughRedirectToDifferentPort(Server::Handler target,
  3303. const std::function<void(Client &)> &setup,
  3304. const Headers &headers = Headers()) {
  3305. Server target_svr;
  3306. target_svr.Get("/target", target);
  3307. int target_port = 0;
  3308. auto target_thread = std::thread([&]() {
  3309. target_port = target_svr.bind_to_any_port(HOST);
  3310. target_svr.listen_after_bind();
  3311. });
  3312. Server origin_svr;
  3313. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3314. res.set_redirect(
  3315. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3316. });
  3317. int origin_port = 0;
  3318. auto origin_thread = std::thread([&]() {
  3319. origin_port = origin_svr.bind_to_any_port(HOST);
  3320. origin_svr.listen_after_bind();
  3321. });
  3322. auto se = detail::scope_exit([&] {
  3323. origin_svr.stop();
  3324. origin_thread.join();
  3325. target_svr.stop();
  3326. target_thread.join();
  3327. });
  3328. target_svr.wait_until_ready();
  3329. origin_svr.wait_until_ready();
  3330. Client cli("localhost", origin_port);
  3331. cli.set_follow_location(true);
  3332. setup(cli);
  3333. return cli.Get("/redir", headers);
  3334. }
  3335. static void
  3336. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3337. std::string captured_authorization;
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [&](const Request &req, Response &res) {
  3340. captured_authorization = req.get_header_value("Authorization");
  3341. res.set_content("OK", "text/plain");
  3342. },
  3343. set_auth);
  3344. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3345. EXPECT_EQ(StatusCode::OK_200, result->status);
  3346. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3347. EXPECT_TRUE(captured_authorization.empty());
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3354. TestDoNotForwardCredentialsOnRedirect(
  3355. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3356. }
  3357. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3358. std::string captured_cookie;
  3359. auto result = GetThroughRedirectToDifferentPort(
  3360. [&](const Request &req, Response &res) {
  3361. captured_cookie = req.get_header_value("Cookie");
  3362. res.set_content("OK", "text/plain");
  3363. },
  3364. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3365. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3366. EXPECT_EQ(StatusCode::OK_200, result->status);
  3367. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3368. EXPECT_TRUE(captured_cookie.empty());
  3369. }
  3370. TEST(RedirectToSamePort, ForwardCookie) {
  3371. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3372. // header so that ordinary session flows keep working.
  3373. Server svr;
  3374. std::string captured_cookie;
  3375. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3376. res.set_redirect("/target", 302);
  3377. });
  3378. svr.Get("/target", [&](const Request &req, Response &res) {
  3379. captured_cookie = req.get_header_value("Cookie");
  3380. res.set_content("OK", "text/plain");
  3381. });
  3382. auto port = svr.bind_to_any_port(HOST);
  3383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. thread.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_follow_location(true);
  3392. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3393. auto res = cli.Get("/redir", headers);
  3394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3397. }
  3398. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3399. std::string authorization;
  3400. std::string trace_id;
  3401. auto result = GetThroughRedirectToDifferentPort(
  3402. [&](const Request &req, Response &res) {
  3403. authorization = req.get_header_value("Authorization");
  3404. trace_id = req.get_header_value("X-Trace-Id");
  3405. res.set_content("OK", "text/plain");
  3406. },
  3407. [](Client &cli) {
  3408. cli.set_default_headers(
  3409. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3410. });
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // Like a header given with the request, a default one goes along unless it
  3414. // carries credentials (RFC 9110 15.4).
  3415. EXPECT_TRUE(authorization.empty());
  3416. EXPECT_EQ("42", trace_id);
  3417. }
  3418. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3419. auto result = GetThroughRedirectToDifferentPort(
  3420. [](const Request &, Response &res) {
  3421. res.set_content(std::string(2048, 'x'), "text/plain");
  3422. },
  3423. [](Client &cli) { cli.set_payload_max_length(1024); });
  3424. EXPECT_FALSE(result);
  3425. }
  3426. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [](const Request &req, Response &res) {
  3429. // Answer after a second, or once the client gives up.
  3430. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3432. }
  3433. res.set_content("late", "text/plain");
  3434. },
  3435. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3436. ASSERT_FALSE(result);
  3437. EXPECT_EQ(Error::Read, result.error());
  3438. }
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3441. auto result = GetThroughRedirectToDifferentPort(
  3442. [](const Request &, Response &res) {
  3443. res.status = StatusCode::Unauthorized_401;
  3444. res.set_header("WWW-Authenticate",
  3445. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3446. },
  3447. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3450. }
  3451. #endif
  3452. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3453. Server svr;
  3454. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3455. // Port number that overflows int — should not crash
  3456. res.set_redirect("http://localhost:99999999999999999999/target");
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. Client cli(HOST, port);
  3467. cli.set_follow_location(true);
  3468. auto res = cli.Get("/redir");
  3469. // Should fail gracefully, not crash (no valid response due to bad port)
  3470. EXPECT_FALSE(res);
  3471. }
  3472. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3473. Server svr;
  3474. auto port = svr.bind_to_any_port(HOST);
  3475. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3476. // The server's own port followed by junk must not be followed
  3477. res.set_redirect("http://" + std::string(HOST) + ":" +
  3478. std::to_string(port) + "junk/target");
  3479. });
  3480. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3481. res.set_content("target", "text/plain");
  3482. });
  3483. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. thread.join();
  3487. ASSERT_FALSE(svr.is_running());
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_follow_location(true);
  3492. auto res = cli.Get("/redir");
  3493. EXPECT_FALSE(res);
  3494. }
  3495. TEST(RedirectFromPageWithContent, Redirect) {
  3496. Server svr;
  3497. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("___", "text/plain");
  3499. res.set_redirect("/2");
  3500. });
  3501. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3502. res.set_content("Hello World!", "text/plain");
  3503. });
  3504. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3505. auto se = detail::scope_exit([&] {
  3506. svr.stop();
  3507. th.join();
  3508. ASSERT_FALSE(svr.is_running());
  3509. });
  3510. svr.wait_until_ready();
  3511. {
  3512. Client cli("localhost", PORT);
  3513. cli.set_follow_location(true);
  3514. std::string body;
  3515. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3516. body.append(data, data_length);
  3517. return true;
  3518. });
  3519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("Hello World!", body);
  3522. }
  3523. {
  3524. Client cli("localhost", PORT);
  3525. std::string body;
  3526. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3527. body.append(data, data_length);
  3528. return true;
  3529. });
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::Found_302, res->status);
  3532. EXPECT_EQ("___", body);
  3533. }
  3534. }
  3535. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3536. Server svr;
  3537. auto port_str = std::to_string(PORT);
  3538. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3539. auto expected_host = "[::1]:" + port_str;
  3540. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3541. res.set_content("___", "text/plain");
  3542. // res.set_redirect("/2");
  3543. res.set_redirect(redirect_url);
  3544. });
  3545. svr.Get("/2", [&](const Request &req, Response &res) {
  3546. auto host_header = req.headers.find("Host");
  3547. ASSERT_TRUE(host_header != req.headers.end());
  3548. EXPECT_EQ(expected_host, host_header->second);
  3549. res.set_content("Hello World!", "text/plain");
  3550. });
  3551. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. th.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3558. // actually starts anything, so the condition !svr.is_running() will
  3559. // always remain true, and the loop never stops.
  3560. // This basically counts how many milliseconds have passed since the
  3561. // call to svr.listen(), and if after 5 seconds nothing started yet
  3562. // aborts the test.
  3563. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3564. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3565. ASSERT_LT(milliseconds, 5000U);
  3566. }
  3567. {
  3568. Client cli("::1", PORT);
  3569. cli.set_follow_location(true);
  3570. std::string body;
  3571. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3572. body.append(data, data_length);
  3573. return true;
  3574. });
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("Hello World!", body);
  3578. }
  3579. {
  3580. Client cli("::1", PORT);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::Found_302, res->status);
  3588. EXPECT_EQ("___", body);
  3589. }
  3590. }
  3591. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3592. Server svr;
  3593. svr.Get("/foo", [](const Request &req, Response &res) {
  3594. auto a = req.params.find("a");
  3595. if (a != req.params.end()) {
  3596. res.set_content((*a).second, "text/plain");
  3597. res.status = StatusCode::OK_200;
  3598. } else {
  3599. res.status = StatusCode::BadRequest_400;
  3600. }
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. {
  3610. Client cli(HOST, PORT);
  3611. cli.set_path_encode(false);
  3612. auto res = cli.Get("/foo?a=explicitly+encoded");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. // This expects it back with a space, as the `+` won't have been
  3616. // url-encoded, and server-side the params get decoded turning `+`
  3617. // into spaces.
  3618. EXPECT_EQ("explicitly encoded", res->body);
  3619. }
  3620. }
  3621. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3622. // When path encoding is disabled the client must transmit the supplied
  3623. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3624. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3625. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3626. // than a space (0x20). Assert on the raw wire target to catch this.
  3627. Server svr;
  3628. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3629. svr.Get("/foo", [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(expected_target, req.target);
  3631. res.status = StatusCode::OK_200;
  3632. });
  3633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. {
  3641. Client cli(HOST, PORT);
  3642. cli.set_path_encode(false);
  3643. auto res = cli.Get(expected_target.c_str());
  3644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3649. // `open_stream()` used to skip the path encoding that the buffered send
  3650. // path applies, so the same `path` produced different bytes in the request
  3651. // line depending on which API was used. Assert the two agree.
  3652. Server svr;
  3653. std::string target;
  3654. svr.Get(".*", [&](const Request &req, Response &res) {
  3655. target = req.target;
  3656. res.status = StatusCode::OK_200;
  3657. });
  3658. auto port = svr.bind_to_any_port(HOST);
  3659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. struct {
  3667. const char *path;
  3668. const char *expected;
  3669. } cases[] = {
  3670. {"/a b?x=1", "/a%20b?x=1"},
  3671. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3672. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3673. };
  3674. for (const auto &c : cases) {
  3675. Client cli(HOST, port);
  3676. target.clear();
  3677. auto res = cli.Get(c.path);
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3680. auto buffered_target = target;
  3681. target.clear();
  3682. auto handle = cli.open_stream("GET", c.path);
  3683. EXPECT_TRUE(handle.is_valid())
  3684. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3685. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3689. // The `set_path_encode(false)` contract — transmit the supplied target
  3690. // verbatim — must hold for the streaming API too.
  3691. Server svr;
  3692. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3693. std::string target;
  3694. svr.Get("/foo", [&](const Request &req, Response &res) {
  3695. target = req.target;
  3696. res.status = StatusCode::OK_200;
  3697. });
  3698. auto port = svr.bind_to_any_port(HOST);
  3699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3700. auto se = detail::scope_exit([&] {
  3701. svr.stop();
  3702. thread.join();
  3703. ASSERT_FALSE(svr.is_running());
  3704. });
  3705. svr.wait_until_ready();
  3706. {
  3707. Client cli(HOST, port);
  3708. cli.set_path_encode(false);
  3709. auto handle = cli.open_stream("GET", expected_target);
  3710. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3711. EXPECT_EQ(expected_target, target);
  3712. }
  3713. }
  3714. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3715. // With path encoding enabled a CR/LF in the target is percent-encoded
  3716. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3717. // write_request_line still backstops `set_path_encode(false)`, which is
  3718. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3719. Server svr;
  3720. // Captured before routing: the decoded path contains a newline, which a
  3721. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3722. std::string target;
  3723. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. return Server::HandlerResponse::Handled;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. {
  3737. Client cli(HOST, port);
  3738. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3739. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3740. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3744. // Every control character is percent-encoded, not just CR/LF, so the target
  3745. // passes the request-target check in write_request_line.
  3746. Server svr;
  3747. std::string target;
  3748. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. return Server::HandlerResponse::Handled;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. auto res = cli.Get("/a\tb\x1b\x7f");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ("/a%09b%1B%7F", target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3769. // Nothing may reach the wire: a raw CR/LF target would split the request
  3770. // line and inject headers.
  3771. Server svr;
  3772. // Pre-routing so that "not called" means nothing reached the server at all,
  3773. // rather than merely failing to match a handler pattern.
  3774. auto handler_called = false;
  3775. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3776. handler_called = true;
  3777. res.status = StatusCode::OK_200;
  3778. return Server::HandlerResponse::Handled;
  3779. });
  3780. auto port = svr.bind_to_any_port(HOST);
  3781. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, port);
  3790. cli.set_path_encode(false);
  3791. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3792. EXPECT_FALSE(handle.is_valid());
  3793. EXPECT_EQ(Error::Write, handle.error);
  3794. EXPECT_FALSE(handler_called);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3798. // Which of the two branches runs is decided by whether the query component
  3799. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3800. // an empty query and must still fall back to building one from
  3801. // `req.params`, while a non-empty query must win over `req.params`.
  3802. Server svr;
  3803. std::string target;
  3804. svr.Get("/foo", [&](const Request &req, Response &res) {
  3805. target = req.target;
  3806. res.status = StatusCode::OK_200;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. // Trailing `?` -> empty query component -> `req.params` is used.
  3818. Client cli(HOST, port);
  3819. Request req;
  3820. req.method = "GET";
  3821. req.path = "/foo?";
  3822. req.params.emplace("a", "1");
  3823. target.clear();
  3824. auto res = cli.send(req);
  3825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3826. EXPECT_EQ("/foo?a=1", target);
  3827. }
  3828. {
  3829. // Non-empty query in `req.path` -> `req.params` is not appended.
  3830. Client cli(HOST, port);
  3831. Request req;
  3832. req.method = "GET";
  3833. req.path = "/foo?b=2";
  3834. req.params.emplace("a", "1");
  3835. target.clear();
  3836. auto res = cli.send(req);
  3837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3838. EXPECT_EQ("/foo?b=2", target);
  3839. }
  3840. }
  3841. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3842. Server svr;
  3843. svr.Get("/", [](const Request &req, Response &) {
  3844. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. {
  3854. Client cli(HOST, PORT);
  3855. cli.set_path_encode(false);
  3856. auto res = cli.Get("/?something=%0A");
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::OK_200, res->status);
  3859. }
  3860. }
  3861. TEST(BindServerTest, BindDualStack) {
  3862. Server svr;
  3863. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3864. res.set_content("Hello World!", "text/plain");
  3865. });
  3866. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. thread.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. {
  3874. Client cli("127.0.0.1", PORT);
  3875. auto res = cli.Get("/1");
  3876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ("Hello World!", res->body);
  3879. }
  3880. {
  3881. Client cli("::1", PORT);
  3882. auto res = cli.Get("/1");
  3883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3884. EXPECT_EQ(StatusCode::OK_200, res->status);
  3885. EXPECT_EQ("Hello World!", res->body);
  3886. }
  3887. }
  3888. TEST(BindServerTest, BindAndListenSeparately) {
  3889. Server svr;
  3890. int port = svr.bind_to_any_port("0.0.0.0");
  3891. ASSERT_TRUE(svr.is_valid());
  3892. ASSERT_TRUE(port > 0);
  3893. svr.stop();
  3894. }
  3895. // Reports whether anything is still listening on a loopback port. A plain
  3896. // connect() is used instead of a Client request because a socket left bound by
  3897. // mistake accepts the connection into its backlog and never answers, which
  3898. // would hang the test instead of failing it.
  3899. static bool is_loopback_port_accepting(int port) {
  3900. sockaddr_in addr{};
  3901. addr.sin_family = AF_INET;
  3902. addr.sin_port = htons(static_cast<uint16_t>(port));
  3903. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3904. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3905. EXPECT_NE(sock, INVALID_SOCKET);
  3906. if (sock == INVALID_SOCKET) { return false; }
  3907. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3908. static_cast<socklen_t>(sizeof(addr)));
  3909. detail::close_socket(sock);
  3910. return ret == 0;
  3911. }
  3912. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3913. Server svr;
  3914. auto port = svr.bind_to_any_port("127.0.0.1");
  3915. ASSERT_TRUE(port > 0);
  3916. svr.stop();
  3917. // bind_to_any_port() already called listen(2), so until stop() closed the
  3918. // descriptor the port kept accepting connections into the backlog. ASSERT
  3919. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3920. // below blocks forever in the accept loop.
  3921. ASSERT_FALSE(is_loopback_port_accepting(port));
  3922. // Nothing is left to accept on, so listen_after_bind() must report failure
  3923. // instead of returning success without ever serving.
  3924. EXPECT_FALSE(svr.listen_after_bind());
  3925. // The failed listen marks the server decommissioned, so a waiter returns
  3926. // instead of spinning forever.
  3927. svr.wait_until_ready();
  3928. }
  3929. #ifdef CPPHTTPLIB_SSL_ENABLED
  3930. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3932. CLIENT_CA_CERT_DIR);
  3933. int port = svr.bind_to_any_port("0.0.0.0");
  3934. ASSERT_TRUE(svr.is_valid());
  3935. ASSERT_TRUE(port > 0);
  3936. svr.stop();
  3937. }
  3938. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3939. // or a rejected CustomRoute() registration would not stop the server binding.
  3940. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3942. CLIENT_CA_CERT_DIR);
  3943. ASSERT_TRUE(svr.is_valid());
  3944. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3945. EXPECT_FALSE(svr.is_valid());
  3946. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3947. }
  3948. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3949. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3950. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3951. int port = svr.bind_to_any_port("0.0.0.0");
  3952. ASSERT_TRUE(svr.is_valid());
  3953. ASSERT_TRUE(port > 0);
  3954. svr.stop();
  3955. }
  3956. TEST(BindServerTest, UpdateCertsPem) {
  3957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. // Read PEM files
  3962. std::string cert_pem, key_pem, ca_pem;
  3963. read_file(SERVER_CERT_FILE, cert_pem);
  3964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3966. // Update server certificates using PEM API
  3967. ASSERT_TRUE(
  3968. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3969. ASSERT_TRUE(svr.is_valid());
  3970. svr.stop();
  3971. }
  3972. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3973. // Start server with client CA (enables client auth)
  3974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3975. ASSERT_TRUE(svr.is_valid());
  3976. bool handler_called = false;
  3977. svr.Get("/test", [&](const Request &req, Response &res) {
  3978. handler_called = true;
  3979. // Verify client certificate is present
  3980. auto cert = req.peer_cert();
  3981. EXPECT_TRUE(static_cast<bool>(cert));
  3982. res.set_content("ok", "text/plain");
  3983. });
  3984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3985. auto se = detail::scope_exit([&] {
  3986. svr.stop();
  3987. t.join();
  3988. ASSERT_FALSE(svr.is_running());
  3989. });
  3990. svr.wait_until_ready();
  3991. // Read PEM files
  3992. std::string cert_pem, key_pem, ca_pem;
  3993. read_file(SERVER_CERT_FILE, cert_pem);
  3994. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3995. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3996. // Update server certificates and client CA using PEM API while server running
  3997. ASSERT_TRUE(
  3998. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3999. // Connect with client certificate
  4000. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4001. cli.enable_server_certificate_verification(false);
  4002. cli.set_connection_timeout(30);
  4003. auto res = cli.Get("/test");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. ASSERT_EQ(StatusCode::OK_200, res->status);
  4006. ASSERT_TRUE(handler_called);
  4007. EXPECT_EQ("ok", res->body);
  4008. }
  4009. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.Get("/test", [](const Request &, Response &res) {
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. auto get = [] {
  4023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4024. cli.enable_server_certificate_verification(false);
  4025. return cli.Get("/test");
  4026. };
  4027. ASSERT_TRUE(get());
  4028. // A CA that did not sign the client's certificate takes the old one's place.
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(SERVER_CERT2_FILE, ca_pem);
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. EXPECT_FALSE(get());
  4036. }
  4037. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.Get("/test", [](const Request &, Response &res) {
  4041. res.set_content("ok", "text/plain");
  4042. });
  4043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4044. auto se = detail::scope_exit([&] {
  4045. svr.stop();
  4046. t.join();
  4047. ASSERT_FALSE(svr.is_running());
  4048. });
  4049. svr.wait_until_ready();
  4050. // A connection that sends no ClientHello keeps its handshake in progress,
  4051. // once the server has had a moment to start it.
  4052. auto error = Error::Success;
  4053. auto sock = detail::create_client_socket(
  4054. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4055. /*connection_timeout_sec=*/5, 0,
  4056. /*read_timeout_sec=*/5, 0,
  4057. /*write_timeout_sec=*/5, 0, std::string(), error);
  4058. ASSERT_NE(INVALID_SOCKET, sock);
  4059. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4060. std::string cert_pem, key_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. auto update = std::async(std::launch::async, [&]() {
  4064. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4065. });
  4066. EXPECT_EQ(std::future_status::timeout,
  4067. update.wait_for(std::chrono::milliseconds(200)));
  4068. detail::close_socket(sock);
  4069. EXPECT_TRUE(update.get());
  4070. SSLClient cli(HOST, PORT);
  4071. cli.enable_server_certificate_verification(false);
  4072. auto res = cli.Get("/test");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. }
  4076. #endif
  4077. TEST(ErrorHandlerTest, ContentLength) {
  4078. Server svr;
  4079. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::OK_200;
  4081. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4082. "text/html"); // <= Content-Length still 13
  4083. });
  4084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4085. res.set_content("Hello World!\n", "text/plain");
  4086. res.status = 524;
  4087. });
  4088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4089. auto se = detail::scope_exit([&] {
  4090. svr.stop();
  4091. thread.join();
  4092. ASSERT_FALSE(svr.is_running());
  4093. });
  4094. svr.wait_until_ready();
  4095. {
  4096. Client cli(HOST, PORT);
  4097. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4101. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4103. }
  4104. }
  4105. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4106. TEST(ExceptionTest, WithoutExceptionHandler) {
  4107. Server svr;
  4108. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4109. throw std::runtime_error("exception...");
  4110. });
  4111. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4112. throw std::runtime_error("exception\r\n...");
  4113. });
  4114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. listen_thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli("localhost", PORT);
  4122. {
  4123. auto res = cli.Get("/exception");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4126. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4127. }
  4128. {
  4129. auto res = cli.Get("/unknown");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4132. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4133. }
  4134. }
  4135. TEST(ExceptionTest, WithExceptionHandler) {
  4136. Server svr;
  4137. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4138. std::exception_ptr ep) {
  4139. EXPECT_FALSE(ep == nullptr);
  4140. try {
  4141. std::rethrow_exception(ep);
  4142. } catch (std::exception &e) {
  4143. EXPECT_EQ("abc", std::string(e.what()));
  4144. } catch (...) {}
  4145. res.status = StatusCode::InternalServerError_500;
  4146. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4147. "text/html"); // <= Content-Length still 13 at this point
  4148. });
  4149. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4150. res.set_content("Hello World!\n", "text/plain");
  4151. throw std::runtime_error("abc");
  4152. });
  4153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4154. auto se = detail::scope_exit([&] {
  4155. svr.stop();
  4156. thread.join();
  4157. ASSERT_FALSE(svr.is_running());
  4158. });
  4159. svr.wait_until_ready();
  4160. for (size_t i = 0; i < 10; i++) {
  4161. Client cli(HOST, PORT);
  4162. for (size_t j = 0; j < 100; j++) {
  4163. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4166. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4167. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4169. }
  4170. cli.set_keep_alive(true);
  4171. for (size_t j = 0; j < 100; j++) {
  4172. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4174. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4176. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4178. }
  4179. }
  4180. }
  4181. TEST(ExceptionTest, AndErrorHandler) {
  4182. Server svr;
  4183. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4184. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4185. });
  4186. svr.set_exception_handler(
  4187. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4188. EXPECT_FALSE(ep == nullptr);
  4189. try {
  4190. std::rethrow_exception(ep);
  4191. } catch (std::exception &e) {
  4192. res.set_content(e.what(), "text/html");
  4193. } catch (...) {}
  4194. res.status = StatusCode::InternalServerError_500;
  4195. });
  4196. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4197. throw std::runtime_error("EXCEPTION");
  4198. });
  4199. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4200. res.set_content("ERROR", "text/html");
  4201. res.status = StatusCode::InternalServerError_500;
  4202. });
  4203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. thread.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. Client cli(HOST, PORT);
  4211. {
  4212. auto res = cli.Get("/exception");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4215. EXPECT_EQ("EXCEPTION", res->body);
  4216. }
  4217. {
  4218. auto res = cli.Get("/error");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4221. EXPECT_EQ("ERROR", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/invalid");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4227. EXPECT_EQ("NOT_FOUND", res->body);
  4228. }
  4229. }
  4230. #endif
  4231. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4232. // process_request() wraps only routing() in a try/catch, so an exception from
  4233. // any other user callback used to unwind into the task queue - which does not
  4234. // catch - and terminate the process. Each test below runs the server on a
  4235. // single worker thread: a guard that catches the exception but still loses the
  4236. // thread would otherwise be hidden by a spare worker serving the follow-up
  4237. // request. Note that a regression here aborts the whole test binary rather
  4238. // than failing one test.
  4239. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4240. Server svr;
  4241. svr.new_task_queue = [] { return new ThreadPool(1); };
  4242. std::atomic<int> reported{0};
  4243. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4244. if (err == Error::UserCallbackException) { reported++; }
  4245. });
  4246. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4247. res.set_content_provider(
  4248. 1024, "text/plain",
  4249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4250. sink.write("hello", 5);
  4251. throw std::runtime_error("from the content provider");
  4252. });
  4253. });
  4254. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("ok", "text/plain");
  4256. });
  4257. auto port = svr.bind_to_any_port(HOST);
  4258. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. listen_thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, port);
  4267. cli.set_read_timeout(5, 0);
  4268. EXPECT_FALSE(cli.Get("/throw"));
  4269. }
  4270. EXPECT_TRUE(svr.is_running());
  4271. EXPECT_EQ(1, reported.load());
  4272. // A request on a fresh connection is still served.
  4273. {
  4274. Client cli(HOST, port);
  4275. auto res = cli.Get("/ok");
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. EXPECT_EQ(StatusCode::OK_200, res->status);
  4278. EXPECT_EQ("ok", res->body);
  4279. }
  4280. }
  4281. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4282. Server svr;
  4283. svr.new_task_queue = [] { return new ThreadPool(1); };
  4284. std::atomic<bool> should_throw{true};
  4285. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4286. res.set_content("hi", "text/plain");
  4287. });
  4288. svr.set_post_routing_handler(
  4289. [&](const Request & /*req*/, Response & /*res*/) {
  4290. if (should_throw) {
  4291. throw std::runtime_error("from the post-routing handler");
  4292. }
  4293. });
  4294. auto port = svr.bind_to_any_port(HOST);
  4295. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4296. auto se = detail::scope_exit([&] {
  4297. svr.stop();
  4298. listen_thread.join();
  4299. ASSERT_FALSE(svr.is_running());
  4300. });
  4301. svr.wait_until_ready();
  4302. {
  4303. Client cli(HOST, port);
  4304. cli.set_read_timeout(5, 0);
  4305. EXPECT_FALSE(cli.Get("/hi"));
  4306. }
  4307. EXPECT_TRUE(svr.is_running());
  4308. should_throw = false;
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/hi");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("hi", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4318. // The guard reports the caught exception through the error logger, which is
  4319. // a user callback too. A logger that throws has to be contained as well, or
  4320. // the process would terminate from inside the catch.
  4321. Server svr;
  4322. svr.new_task_queue = [] { return new ThreadPool(1); };
  4323. std::atomic<int> reported{0};
  4324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4325. if (err == Error::UserCallbackException) {
  4326. reported++;
  4327. throw std::runtime_error("from the error logger");
  4328. }
  4329. });
  4330. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4331. res.set_content_provider(
  4332. 1024, "text/plain",
  4333. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4334. sink.write("hello", 5);
  4335. throw std::runtime_error("from the content provider");
  4336. });
  4337. });
  4338. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4339. res.set_content("ok", "text/plain");
  4340. });
  4341. auto port = svr.bind_to_any_port(HOST);
  4342. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4343. auto se = detail::scope_exit([&] {
  4344. svr.stop();
  4345. listen_thread.join();
  4346. ASSERT_FALSE(svr.is_running());
  4347. });
  4348. svr.wait_until_ready();
  4349. {
  4350. Client cli(HOST, port);
  4351. cli.set_read_timeout(5, 0);
  4352. EXPECT_FALSE(cli.Get("/throw"));
  4353. }
  4354. EXPECT_TRUE(svr.is_running());
  4355. EXPECT_EQ(1, reported.load());
  4356. {
  4357. Client cli(HOST, port);
  4358. auto res = cli.Get("/ok");
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("ok", res->body);
  4362. }
  4363. }
  4364. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4365. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4366. // so the exception unwinds through the ws::WebSocket object on its way to
  4367. // the guard. None of the HTTP cases above cross that.
  4368. Server svr;
  4369. svr.new_task_queue = [] { return new ThreadPool(1); };
  4370. std::atomic<int> reported{0};
  4371. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4372. if (err == Error::UserCallbackException) { reported++; }
  4373. });
  4374. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4375. throw std::runtime_error("from the WebSocket handler");
  4376. });
  4377. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("ok", "text/plain");
  4379. });
  4380. auto port = svr.bind_to_any_port(HOST);
  4381. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. listen_thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4390. "/ws");
  4391. auto res = client.connect();
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. // The server dropped the connection instead of dying.
  4394. std::string msg;
  4395. EXPECT_FALSE(client.read(msg));
  4396. client.close();
  4397. }
  4398. EXPECT_TRUE(svr.is_running());
  4399. EXPECT_EQ(1, reported.load());
  4400. {
  4401. Client cli(HOST, port);
  4402. auto res = cli.Get("/ok");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ("ok", res->body);
  4406. }
  4407. }
  4408. #ifdef CPPHTTPLIB_SSL_ENABLED
  4409. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4410. // SSLServer::process_and_close_socket() is a separate overload with its own
  4411. // guard, so it is exercised on its own.
  4412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4413. ASSERT_TRUE(svr.is_valid());
  4414. svr.new_task_queue = [] { return new ThreadPool(1); };
  4415. std::atomic<int> reported{0};
  4416. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4417. if (err == Error::UserCallbackException) { reported++; }
  4418. });
  4419. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4420. res.set_content_provider(
  4421. 1024, "text/plain",
  4422. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4423. sink.write("hello", 5);
  4424. throw std::runtime_error("from the content provider");
  4425. });
  4426. });
  4427. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("ok", "text/plain");
  4429. });
  4430. auto port = svr.bind_to_any_port(HOST);
  4431. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. listen_thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. SSLClient cli(HOST, port);
  4440. cli.enable_server_certificate_verification(false);
  4441. cli.set_read_timeout(5, 0);
  4442. EXPECT_FALSE(cli.Get("/throw"));
  4443. }
  4444. EXPECT_TRUE(svr.is_running());
  4445. EXPECT_EQ(1, reported.load());
  4446. {
  4447. SSLClient cli(HOST, port);
  4448. cli.enable_server_certificate_verification(false);
  4449. auto res = cli.Get("/ok");
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::OK_200, res->status);
  4452. EXPECT_EQ("ok", res->body);
  4453. }
  4454. }
  4455. #endif
  4456. #endif
  4457. TEST(NoContentTest, ContentLength) {
  4458. Server svr;
  4459. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4460. res.status = StatusCode::NoContent_204;
  4461. });
  4462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4463. auto se = detail::scope_exit([&] {
  4464. svr.stop();
  4465. thread.join();
  4466. ASSERT_FALSE(svr.is_running());
  4467. });
  4468. svr.wait_until_ready();
  4469. {
  4470. Client cli(HOST, PORT);
  4471. auto res = cli.Get("/hi");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4474. // RFC 9110 8.6: none in a 204 response
  4475. EXPECT_FALSE(res->has_header("Content-Length"));
  4476. }
  4477. }
  4478. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4479. Server svr;
  4480. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4481. res.set_header("Content-Length", "5");
  4482. res.set_content("hello world", "text/plain");
  4483. });
  4484. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4485. // A body that reads as the last chunk, were it taken as chunked
  4486. res.set_header("Transfer-Encoding", "chunked");
  4487. res.set_content("0\r\n\r\n", "text/plain");
  4488. });
  4489. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4490. res.set_header("Content-Length", "2");
  4491. res.set_content_provider(5, "text/plain",
  4492. [](size_t offset, size_t length, DataSink &sink) {
  4493. sink.write(&"hello"[offset], length);
  4494. return true;
  4495. });
  4496. });
  4497. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4498. res.set_header("Content-Length", "1234");
  4499. });
  4500. thread t = thread([&] { svr.listen(HOST, PORT); });
  4501. auto se = detail::scope_exit([&] {
  4502. svr.stop();
  4503. t.join();
  4504. ASSERT_FALSE(svr.is_running());
  4505. });
  4506. svr.wait_until_ready();
  4507. Client cli(HOST, PORT);
  4508. cli.set_read_timeout(1, 0);
  4509. auto expect_body = [&](const Result &res, const std::string &body) {
  4510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4511. EXPECT_EQ(body, res->body);
  4512. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4513. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4514. };
  4515. Headers identity{{"Accept-Encoding", ""}};
  4516. expect_body(cli.Get("/body", identity), "hello world");
  4517. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4518. expect_body(cli.Get("/body",
  4519. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4520. "he");
  4521. expect_body(cli.Get("/provider", identity), "hello");
  4522. expect_body(cli.Get("/empty", identity), "");
  4523. // A HEAD response may give the length of the body a GET would get.
  4524. auto res = cli.Head("/empty");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4527. }
  4528. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4529. Server svr;
  4530. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4531. res.set_content("short", "text/plain");
  4532. });
  4533. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4534. res.body += " with a footer";
  4535. res.set_header("Transfer-Encoding", "chunked");
  4536. });
  4537. thread t = thread([&] { svr.listen(HOST, PORT); });
  4538. auto se = detail::scope_exit([&] {
  4539. svr.stop();
  4540. t.join();
  4541. ASSERT_FALSE(svr.is_running());
  4542. });
  4543. svr.wait_until_ready();
  4544. Client cli(HOST, PORT);
  4545. cli.set_read_timeout(1, 0);
  4546. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4548. EXPECT_EQ("short with a footer", res->body);
  4549. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4550. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4551. }
  4552. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4553. #ifdef CPPHTTPLIB_SSL_ENABLED
  4554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4555. ASSERT_TRUE(svr.is_valid());
  4556. #else
  4557. Server svr;
  4558. #endif
  4559. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4560. if (req.path == "/routing_handler") {
  4561. res.set_header("PRE_ROUTING", "on");
  4562. res.set_content("Routing Handler", "text/plain");
  4563. return httplib::Server::HandlerResponse::Handled;
  4564. }
  4565. return httplib::Server::HandlerResponse::Unhandled;
  4566. });
  4567. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4568. res.set_content("Error", "text/html");
  4569. });
  4570. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4571. if (req.path == "/routing_handler") {
  4572. res.set_header("POST_ROUTING", "on");
  4573. }
  4574. });
  4575. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4576. res.set_content("Hello World!\n", "text/plain");
  4577. });
  4578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4579. auto se = detail::scope_exit([&] {
  4580. svr.stop();
  4581. thread.join();
  4582. ASSERT_FALSE(svr.is_running());
  4583. });
  4584. svr.wait_until_ready();
  4585. {
  4586. #ifdef CPPHTTPLIB_SSL_ENABLED
  4587. SSLClient cli(HOST, PORT);
  4588. cli.enable_server_certificate_verification(false);
  4589. #else
  4590. Client cli(HOST, PORT);
  4591. #endif
  4592. auto res = cli.Get("/routing_handler");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("Routing Handler", res->body);
  4596. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4597. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4598. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4599. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4600. }
  4601. {
  4602. #ifdef CPPHTTPLIB_SSL_ENABLED
  4603. SSLClient cli(HOST, PORT);
  4604. cli.enable_server_certificate_verification(false);
  4605. #else
  4606. Client cli(HOST, PORT);
  4607. #endif
  4608. auto res = cli.Get("/hi");
  4609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. EXPECT_EQ("Hello World!\n", res->body);
  4612. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4613. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4614. }
  4615. {
  4616. #ifdef CPPHTTPLIB_SSL_ENABLED
  4617. SSLClient cli(HOST, PORT);
  4618. cli.enable_server_certificate_verification(false);
  4619. #else
  4620. Client cli(HOST, PORT);
  4621. #endif
  4622. auto res = cli.Get("/aaa");
  4623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4625. EXPECT_EQ("Error", res->body);
  4626. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4627. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4628. }
  4629. }
  4630. TEST(RequestHandlerTest, PreRequestHandler) {
  4631. auto route_path = "/user/:user";
  4632. Server svr;
  4633. svr.Get("/hi", [](const Request &, Response &res) {
  4634. res.set_content("hi", "text/plain");
  4635. });
  4636. svr.Get(route_path, [](const Request &req, Response &res) {
  4637. res.set_content(req.path_params.at("user"), "text/plain");
  4638. });
  4639. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4640. if (req.matched_route == route_path) {
  4641. auto user = req.path_params.at("user");
  4642. if (user != "john") {
  4643. res.status = StatusCode::Forbidden_403;
  4644. res.set_content("error", "text/html");
  4645. return Server::HandlerResponse::Handled;
  4646. }
  4647. }
  4648. return Server::HandlerResponse::Unhandled;
  4649. });
  4650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4651. auto se = detail::scope_exit([&] {
  4652. svr.stop();
  4653. thread.join();
  4654. ASSERT_FALSE(svr.is_running());
  4655. });
  4656. svr.wait_until_ready();
  4657. Client cli(HOST, PORT);
  4658. {
  4659. auto res = cli.Get("/hi");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("hi", res->body);
  4663. }
  4664. {
  4665. auto res = cli.Get("/user/john");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("john", res->body);
  4669. }
  4670. {
  4671. auto res = cli.Get("/user/invalid-user");
  4672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4673. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4674. EXPECT_EQ("error", res->body);
  4675. }
  4676. }
  4677. // The pre-request handler must run before the request body is read, so a
  4678. // rejected request never forces the server to buffer a (potentially large)
  4679. // body. Here the posted body is larger than the payload limit: if the body
  4680. // were read first the server would answer 413, but because the pre-request
  4681. // handler runs first it answers 403 and the body is never read.
  4682. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4683. Server svr;
  4684. svr.set_payload_max_length(8);
  4685. auto handler_ran = false;
  4686. svr.Post("/reject", [&](const Request &req, Response &res) {
  4687. handler_ran = true;
  4688. res.set_content(req.body, "text/plain");
  4689. });
  4690. svr.Post("/accept", [](const Request &req, Response &res) {
  4691. res.set_content(req.body, "text/plain");
  4692. });
  4693. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4694. if (req.matched_route == "/reject") {
  4695. res.status = StatusCode::Forbidden_403;
  4696. res.set_content("denied", "text/plain");
  4697. return Server::HandlerResponse::Handled;
  4698. }
  4699. return Server::HandlerResponse::Unhandled;
  4700. });
  4701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4702. auto se = detail::scope_exit([&] {
  4703. svr.stop();
  4704. thread.join();
  4705. ASSERT_FALSE(svr.is_running());
  4706. });
  4707. svr.wait_until_ready();
  4708. Client cli(HOST, PORT);
  4709. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4710. // rejects with 403 before the body is read, so 413 is never reached.
  4711. {
  4712. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4714. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4715. EXPECT_EQ("denied", res->body);
  4716. EXPECT_FALSE(handler_ran);
  4717. }
  4718. // An approved route still reads the body and enforces the payload limit.
  4719. {
  4720. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4722. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4723. }
  4724. }
  4725. TEST(UserDataTest, BasicOperations) {
  4726. httplib::UserData ud;
  4727. // Initially empty
  4728. EXPECT_FALSE(ud.has("key"));
  4729. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4730. // set and get
  4731. ud.set("key", 42);
  4732. EXPECT_TRUE(ud.has("key"));
  4733. auto *p = ud.get<int>("key");
  4734. ASSERT_NE(nullptr, p);
  4735. EXPECT_EQ(42, *p);
  4736. // Type mismatch → nullptr
  4737. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4738. // Overwrite with different type
  4739. ud.set("key", std::string("hello"));
  4740. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4741. auto *s = ud.get<std::string>("key");
  4742. ASSERT_NE(nullptr, s);
  4743. EXPECT_EQ("hello", *s);
  4744. // erase
  4745. ud.erase("key");
  4746. EXPECT_FALSE(ud.has("key"));
  4747. // clear
  4748. ud.set("a", 1);
  4749. ud.set("b", 2);
  4750. ud.clear();
  4751. EXPECT_FALSE(ud.has("a"));
  4752. EXPECT_FALSE(ud.has("b"));
  4753. }
  4754. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4755. struct AuthCtx {
  4756. std::string user_id;
  4757. };
  4758. Server svr;
  4759. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4760. res.user_data.set("auth", AuthCtx{"alice"});
  4761. return Server::HandlerResponse::Unhandled;
  4762. });
  4763. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4764. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4765. ASSERT_NE(nullptr, ctx);
  4766. res.set_content("Hello " + ctx->user_id, "text/plain");
  4767. });
  4768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. Client cli(HOST, PORT);
  4776. auto res = cli.Get("/me");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ("Hello alice", res->body);
  4780. }
  4781. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4782. struct RoleCtx {
  4783. std::string role;
  4784. };
  4785. Server svr;
  4786. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4787. res.user_data.set("role", RoleCtx{"admin"});
  4788. return Server::HandlerResponse::Unhandled;
  4789. });
  4790. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4791. auto *ctx = res.user_data.get<RoleCtx>("role");
  4792. ASSERT_NE(nullptr, ctx);
  4793. res.set_content(ctx->role, "text/plain");
  4794. });
  4795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4796. auto se = detail::scope_exit([&] {
  4797. svr.stop();
  4798. thread.join();
  4799. ASSERT_FALSE(svr.is_running());
  4800. });
  4801. svr.wait_until_ready();
  4802. Client cli(HOST, PORT);
  4803. auto res = cli.Get("/role");
  4804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4805. EXPECT_EQ(StatusCode::OK_200, res->status);
  4806. EXPECT_EQ("admin", res->body);
  4807. }
  4808. TEST(InvalidFormatTest, StatusCode) {
  4809. Server svr;
  4810. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("Hello World!\n", "text/plain");
  4812. res.status = 9999; // Status should be a three-digit code...
  4813. });
  4814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. thread.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. {
  4822. Client cli(HOST, PORT);
  4823. auto res = cli.Get("/hi");
  4824. ASSERT_FALSE(res);
  4825. }
  4826. }
  4827. TEST(URLFragmentTest, WithFragment) {
  4828. Server svr;
  4829. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4830. EXPECT_TRUE(req.target == "/hi");
  4831. });
  4832. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4833. auto se = detail::scope_exit([&] {
  4834. svr.stop();
  4835. thread.join();
  4836. ASSERT_FALSE(svr.is_running());
  4837. });
  4838. svr.wait_until_ready();
  4839. {
  4840. Client cli(HOST, PORT);
  4841. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4842. EXPECT_TRUE(res);
  4843. EXPECT_EQ(StatusCode::OK_200, res->status);
  4844. res = cli.Get("/hi%23key1=val1=key2=val2");
  4845. EXPECT_TRUE(res);
  4846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4847. }
  4848. }
  4849. TEST(HeaderWriter, SetHeaderWriter) {
  4850. Server svr;
  4851. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4852. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4853. return detail::write_headers(strm, hdrs);
  4854. });
  4855. svr.Get("/hi", [](const Request &req, Response &res) {
  4856. auto it = req.headers.find("CustomClientHeader");
  4857. EXPECT_TRUE(it != req.headers.end());
  4858. EXPECT_EQ(it->second, "CustomClientValue");
  4859. res.set_content("Hello World!\n", "text/plain");
  4860. });
  4861. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4862. auto se = detail::scope_exit([&] {
  4863. svr.stop();
  4864. thread.join();
  4865. ASSERT_FALSE(svr.is_running());
  4866. });
  4867. svr.wait_until_ready();
  4868. {
  4869. Client cli(HOST, PORT);
  4870. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4871. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4872. return detail::write_headers(strm, hdrs);
  4873. });
  4874. auto res = cli.Get("/hi");
  4875. EXPECT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. auto it = res->headers.find("CustomServerHeader");
  4878. EXPECT_TRUE(it != res->headers.end());
  4879. EXPECT_EQ(it->second, "CustomServerValue");
  4880. }
  4881. }
  4882. class ServerTest : public ::testing::Test {
  4883. protected:
  4884. ServerTest()
  4885. : cli_(HOST, PORT)
  4886. #ifdef CPPHTTPLIB_SSL_ENABLED
  4887. ,
  4888. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4889. #endif
  4890. {
  4891. #ifdef CPPHTTPLIB_SSL_ENABLED
  4892. cli_.enable_server_certificate_verification(false);
  4893. #endif
  4894. // Allow LARGE_DATA (100MB) responses
  4895. cli_.set_payload_max_length(200 * 1024 * 1024);
  4896. }
  4897. virtual void SetUp() {
  4898. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4899. svr_.set_payload_max_length(200 * 1024 * 1024);
  4900. svr_.set_mount_point("/", "./www");
  4901. svr_.set_mount_point("/mount", "./www2");
  4902. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4903. svr_.Get("/hi",
  4904. [&](const Request & /*req*/, Response &res) {
  4905. res.set_content("Hello World!", "text/plain");
  4906. })
  4907. .Get("/file_content",
  4908. [&](const Request & /*req*/, Response &res) {
  4909. res.set_file_content("./www/dir/test.html");
  4910. })
  4911. .Get("/file_content_with_content_type",
  4912. [&](const Request & /*req*/, Response &res) {
  4913. res.set_file_content("./www/file", "text/plain");
  4914. })
  4915. .Get("/invalid_file_content",
  4916. [&](const Request & /*req*/, Response &res) {
  4917. res.set_file_content("./www/dir/invalid_file_path");
  4918. })
  4919. .Get("/http_response_splitting",
  4920. [&](const Request & /*req*/, Response &res) {
  4921. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4922. EXPECT_EQ(0U, res.headers.size());
  4923. EXPECT_FALSE(res.has_header("a"));
  4924. res.set_header("a", "1\nSet-Cookie: a=1");
  4925. EXPECT_EQ(0U, res.headers.size());
  4926. EXPECT_FALSE(res.has_header("a"));
  4927. res.set_header("a", "1\rSet-Cookie: a=1");
  4928. EXPECT_EQ(0U, res.headers.size());
  4929. EXPECT_FALSE(res.has_header("a"));
  4930. res.set_header("a\r\nb", "0");
  4931. EXPECT_EQ(0U, res.headers.size());
  4932. EXPECT_FALSE(res.has_header("a"));
  4933. res.set_header("a\rb", "0");
  4934. EXPECT_EQ(0U, res.headers.size());
  4935. EXPECT_FALSE(res.has_header("a"));
  4936. res.set_header("a\nb", "0");
  4937. EXPECT_EQ(0U, res.headers.size());
  4938. EXPECT_FALSE(res.has_header("a"));
  4939. res.set_redirect("1\r\nSet-Cookie: a=1");
  4940. EXPECT_EQ(0U, res.headers.size());
  4941. EXPECT_FALSE(res.has_header("Location"));
  4942. })
  4943. .Get("/slow",
  4944. [&](const Request & /*req*/, Response &res) {
  4945. std::this_thread::sleep_for(std::chrono::seconds(4));
  4946. res.set_content("slow", "text/plain");
  4947. })
  4948. #if 0
  4949. .Post("/slowpost",
  4950. [&](const Request & /*req*/, Response &res) {
  4951. std::this_thread::sleep_for(std::chrono::seconds(2));
  4952. res.set_content("slow", "text/plain");
  4953. })
  4954. #endif
  4955. .Get("/remote_addr",
  4956. [&](const Request &req, Response &res) {
  4957. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4958. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4959. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4960. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4961. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4962. #endif
  4963. res.set_content(req.remote_addr, "text/plain");
  4964. })
  4965. .Get("/local_addr",
  4966. [&](const Request &req, Response &res) {
  4967. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4968. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4969. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4970. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4971. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4972. #endif
  4973. auto local_addr = req.local_addr;
  4974. auto local_port = std::to_string(req.local_port);
  4975. res.set_content(local_addr.append(":").append(local_port),
  4976. "text/plain");
  4977. })
  4978. .Get("/endwith%",
  4979. [&](const Request & /*req*/, Response &res) {
  4980. res.set_content("Hello World!", "text/plain");
  4981. })
  4982. .Get("/a\\+\\+b",
  4983. [&](const Request &req, Response &res) {
  4984. ASSERT_TRUE(req.has_param("a +b"));
  4985. auto val = req.get_param_value("a +b");
  4986. res.set_content(val, "text/plain");
  4987. })
  4988. .Get("/", [&](const Request & /*req*/,
  4989. Response &res) { res.set_redirect("/hi"); })
  4990. .Post("/1",
  4991. [](const Request & /*req*/, Response &res) {
  4992. res.set_redirect("/2", StatusCode::SeeOther_303);
  4993. })
  4994. .Get("/2",
  4995. [](const Request & /*req*/, Response &res) {
  4996. res.set_content("redirected.", "text/plain");
  4997. res.status = StatusCode::OK_200;
  4998. })
  4999. .Post("/person",
  5000. [&](const Request &req, Response &res) {
  5001. if (req.has_param("name") && req.has_param("note")) {
  5002. persons_[req.get_param_value("name")] =
  5003. req.get_param_value("note");
  5004. } else {
  5005. res.status = StatusCode::BadRequest_400;
  5006. }
  5007. })
  5008. .Put("/person",
  5009. [&](const Request &req, Response &res) {
  5010. if (req.has_param("name") && req.has_param("note")) {
  5011. persons_[req.get_param_value("name")] =
  5012. req.get_param_value("note");
  5013. } else {
  5014. res.status = StatusCode::BadRequest_400;
  5015. }
  5016. })
  5017. .Get("/person/(.*)",
  5018. [&](const Request &req, Response &res) {
  5019. string name = req.matches[1];
  5020. if (persons_.find(name) != persons_.end()) {
  5021. auto note = persons_[name];
  5022. res.set_content(note, "text/plain");
  5023. } else {
  5024. res.status = StatusCode::NotFound_404;
  5025. }
  5026. })
  5027. .Delete("/person",
  5028. [&](const Request &req, Response &res) {
  5029. if (req.has_param("name")) {
  5030. string name = req.get_param_value("name");
  5031. if (persons_.find(name) != persons_.end()) {
  5032. persons_.erase(name);
  5033. res.set_content("DELETED", "text/plain");
  5034. } else {
  5035. res.status = StatusCode::NotFound_404;
  5036. }
  5037. } else {
  5038. res.status = StatusCode::BadRequest_400;
  5039. }
  5040. })
  5041. .Post("/x-www-form-urlencoded-json",
  5042. [&](const Request &req, Response &res) {
  5043. auto json = req.get_param_value("json");
  5044. ASSERT_EQ(JSON_DATA, json);
  5045. res.set_content(json, "appliation/json");
  5046. res.status = StatusCode::OK_200;
  5047. })
  5048. .Get("/streamed-chunked",
  5049. [&](const Request & /*req*/, Response &res) {
  5050. res.set_chunked_content_provider(
  5051. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5052. sink.os << "123";
  5053. sink.os << "456";
  5054. sink.os << "789";
  5055. sink.done();
  5056. return true;
  5057. });
  5058. })
  5059. .Get("/streamed-chunked-with-prohibited-trailer",
  5060. [&](const Request & /*req*/, Response &res) {
  5061. auto i = new int(0);
  5062. // Declare both a prohibited trailer (Content-Length) and an
  5063. // allowed one
  5064. res.set_header("Trailer", "Content-Length, X-Allowed");
  5065. res.set_chunked_content_provider(
  5066. "text/plain",
  5067. [i](size_t /*offset*/, DataSink &sink) {
  5068. switch (*i) {
  5069. case 0: sink.os << "123"; break;
  5070. case 1: sink.os << "456"; break;
  5071. case 2: sink.os << "789"; break;
  5072. case 3: {
  5073. sink.done_with_trailer(
  5074. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5075. } break;
  5076. }
  5077. (*i)++;
  5078. return true;
  5079. },
  5080. [i](bool success) {
  5081. EXPECT_TRUE(success);
  5082. delete i;
  5083. });
  5084. })
  5085. .Get("/streamed-chunked2",
  5086. [&](const Request & /*req*/, Response &res) {
  5087. auto i = new int(0);
  5088. res.set_chunked_content_provider(
  5089. "text/plain",
  5090. [i](size_t /*offset*/, DataSink &sink) {
  5091. switch (*i) {
  5092. case 0: sink.os << "123"; break;
  5093. case 1: sink.os << "456"; break;
  5094. case 2: sink.os << "789"; break;
  5095. case 3: sink.done(); break;
  5096. }
  5097. (*i)++;
  5098. return true;
  5099. },
  5100. [i](bool success) {
  5101. EXPECT_TRUE(success);
  5102. delete i;
  5103. });
  5104. })
  5105. .Get("/streamed-chunked-with-trailer",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. auto i = new int(0);
  5108. res.set_header("Trailer", "Dummy1, Dummy2");
  5109. res.set_chunked_content_provider(
  5110. "text/plain",
  5111. [i](size_t /*offset*/, DataSink &sink) {
  5112. switch (*i) {
  5113. case 0: sink.os << "123"; break;
  5114. case 1: sink.os << "456"; break;
  5115. case 2: sink.os << "789"; break;
  5116. case 3: {
  5117. sink.done_with_trailer(
  5118. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5119. } break;
  5120. }
  5121. (*i)++;
  5122. return true;
  5123. },
  5124. [i](bool success) {
  5125. EXPECT_TRUE(success);
  5126. delete i;
  5127. });
  5128. })
  5129. .Get("/streamed",
  5130. [&](const Request & /*req*/, Response &res) {
  5131. res.set_content_provider(
  5132. 6, "text/plain",
  5133. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5134. sink.os << (offset < 3 ? "a" : "b");
  5135. return true;
  5136. });
  5137. })
  5138. .Get("/streamed-without-length",
  5139. [&](const Request & /*req*/, Response &res) {
  5140. auto data = new std::string("abcdefg");
  5141. res.set_content_provider(
  5142. "text/plain",
  5143. [data](size_t offset, DataSink &sink) {
  5144. if (offset < data->size()) {
  5145. sink.os << data->substr(offset);
  5146. }
  5147. sink.done();
  5148. return true;
  5149. },
  5150. [data](bool success) {
  5151. EXPECT_TRUE(success);
  5152. delete data;
  5153. });
  5154. })
  5155. .Get("/streamed-with-range",
  5156. [&](const Request &req, Response &res) {
  5157. auto data = new std::string("abcdefg");
  5158. // An explicit status keeps the server from picking the 206 it
  5159. // would otherwise choose for a ranged request, so the response
  5160. // is not a partial representation.
  5161. auto status = req.get_param_value("status");
  5162. if (status == "200") {
  5163. res.status = StatusCode::OK_200;
  5164. } else if (status == "403") {
  5165. res.status = StatusCode::Forbidden_403;
  5166. }
  5167. res.set_content_provider(
  5168. data->size(), "text/plain",
  5169. [data](size_t offset, size_t length, DataSink &sink) {
  5170. size_t DATA_CHUNK_SIZE = 4;
  5171. const auto &d = *data;
  5172. auto out_len =
  5173. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5174. auto ret =
  5175. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5176. EXPECT_TRUE(ret);
  5177. return true;
  5178. },
  5179. [data, &req](bool success) {
  5180. EXPECT_EQ(success, !req.has_param("error"));
  5181. delete data;
  5182. });
  5183. })
  5184. .Get("/streamed-cancel",
  5185. [&](const Request & /*req*/, Response &res) {
  5186. res.set_content_provider(
  5187. size_t(-1), "text/plain",
  5188. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5189. sink.os << "data_chunk";
  5190. return true;
  5191. });
  5192. })
  5193. .Get("/regex-with-delimiter",
  5194. [&](const Request &req, Response & /*res*/) {
  5195. ASSERT_TRUE(req.has_param("key"));
  5196. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5197. })
  5198. .Get("/with-range",
  5199. [&](const Request & /*req*/, Response &res) {
  5200. res.set_content("abcdefg", "text/plain");
  5201. })
  5202. .Get("/test-start-time",
  5203. [&](const Request &req, Response & /*res*/) {
  5204. EXPECT_NE(req.start_time_,
  5205. std::chrono::steady_clock::time_point::min());
  5206. })
  5207. .Get("/with-range-customized-response",
  5208. [&](const Request & /*req*/, Response &res) {
  5209. res.status = StatusCode::BadRequest_400;
  5210. res.set_content(JSON_DATA, "application/json");
  5211. })
  5212. .Post("/chunked",
  5213. [&](const Request &req, Response & /*res*/) {
  5214. EXPECT_EQ(req.body, "dechunked post body");
  5215. })
  5216. .Post("/large-chunked",
  5217. [&](const Request &req, Response & /*res*/) {
  5218. std::string expected(6 * 30 * 1024u, 'a');
  5219. EXPECT_EQ(req.body, expected);
  5220. })
  5221. .Post("/multipart",
  5222. [&](const Request &req, Response & /*res*/) {
  5223. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5224. req.form.get_field_count("text2") +
  5225. req.form.get_field_count("file3") +
  5226. req.form.get_field_count("file4"));
  5227. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5228. req.form.get_file_count("file2"));
  5229. ASSERT_TRUE(!req.form.has_file("???"));
  5230. ASSERT_TRUE(!req.form.has_field("???"));
  5231. ASSERT_TRUE(req.body.empty());
  5232. {
  5233. const auto &text = req.form.get_field("text1");
  5234. EXPECT_EQ("text default", text);
  5235. }
  5236. {
  5237. const auto &text = req.form.get_field("text2");
  5238. EXPECT_EQ("aωb", text);
  5239. }
  5240. {
  5241. const auto &file = req.form.get_file("file1");
  5242. EXPECT_EQ("hello.txt", file.filename);
  5243. EXPECT_EQ("text/plain", file.content_type);
  5244. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5245. }
  5246. {
  5247. const auto &file = req.form.get_file("file2");
  5248. EXPECT_EQ("world.json", file.filename);
  5249. EXPECT_EQ("application/json", file.content_type);
  5250. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5251. }
  5252. {
  5253. const auto &text = req.form.get_field("file3");
  5254. EXPECT_EQ(0u, text.size());
  5255. }
  5256. {
  5257. const auto &text = req.form.get_field("file4");
  5258. EXPECT_EQ(0u, text.size());
  5259. }
  5260. })
  5261. .Post("/multipart/multi_file_values",
  5262. [&](const Request &req, Response & /*res*/) {
  5263. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5264. req.form.get_field_count("multi_text1"));
  5265. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5266. ASSERT_TRUE(!req.form.has_file("???"));
  5267. ASSERT_TRUE(!req.form.has_field("???"));
  5268. ASSERT_TRUE(req.body.empty());
  5269. {
  5270. const auto &text = req.form.get_field("text");
  5271. EXPECT_EQ("default text", text);
  5272. }
  5273. {
  5274. const auto &text1_values = req.form.get_fields("multi_text1");
  5275. EXPECT_EQ(2u, text1_values.size());
  5276. EXPECT_EQ("aaaaa", text1_values[0]);
  5277. EXPECT_EQ("bbbbb", text1_values[1]);
  5278. }
  5279. {
  5280. const auto &file1_values = req.form.get_files("multi_file1");
  5281. EXPECT_EQ(2u, file1_values.size());
  5282. auto file1 = file1_values[0];
  5283. EXPECT_EQ(file1.filename, "hello.txt");
  5284. EXPECT_EQ(file1.content_type, "text/plain");
  5285. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5286. auto file2 = file1_values[1];
  5287. EXPECT_EQ(file2.filename, "world.json");
  5288. EXPECT_EQ(file2.content_type, "application/json");
  5289. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5290. }
  5291. })
  5292. .Post("/empty",
  5293. [&](const Request &req, Response &res) {
  5294. EXPECT_EQ(req.body, "");
  5295. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5296. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5297. res.set_content("empty", "text/plain");
  5298. })
  5299. .Post("/empty-no-content-type",
  5300. [&](const Request &req, Response &res) {
  5301. EXPECT_EQ(req.body, "");
  5302. EXPECT_FALSE(req.has_header("Content-Type"));
  5303. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5304. res.set_content("empty-no-content-type", "text/plain");
  5305. })
  5306. .Post("/path-only",
  5307. [&](const Request &req, Response &res) {
  5308. EXPECT_EQ(req.body, "");
  5309. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5310. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5311. res.set_content("path-only", "text/plain");
  5312. })
  5313. .Post("/path-headers-only",
  5314. [&](const Request &req, Response &res) {
  5315. EXPECT_EQ(req.body, "");
  5316. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5317. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5318. EXPECT_EQ("world", req.get_header_value("hello"));
  5319. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5320. res.set_content("path-headers-only", "text/plain");
  5321. })
  5322. .Post("/post-large",
  5323. [&](const Request &req, Response &res) {
  5324. EXPECT_EQ(req.body, LARGE_DATA);
  5325. res.set_content(req.body, "text/plain");
  5326. })
  5327. .Post("/post-loopback",
  5328. [&](const Request &, Response &res,
  5329. ContentReader const &content_reader) {
  5330. std::string body;
  5331. content_reader([&](const char *data, size_t data_length) {
  5332. body.append(data, data_length);
  5333. return true;
  5334. });
  5335. res.set_content(body, "text/plain");
  5336. })
  5337. .Put("/put-loopback",
  5338. [&](const Request &, Response &res,
  5339. ContentReader const &content_reader) {
  5340. std::string body;
  5341. content_reader([&](const char *data, size_t data_length) {
  5342. body.append(data, data_length);
  5343. return true;
  5344. });
  5345. res.set_content(body, "text/plain");
  5346. })
  5347. .Patch("/patch-loopback",
  5348. [&](const Request &, Response &res,
  5349. ContentReader const &content_reader) {
  5350. std::string body;
  5351. content_reader([&](const char *data, size_t data_length) {
  5352. body.append(data, data_length);
  5353. return true;
  5354. });
  5355. res.set_content(body, "text/plain");
  5356. })
  5357. .Put("/empty-no-content-type",
  5358. [&](const Request &req, Response &res) {
  5359. EXPECT_EQ(req.body, "");
  5360. EXPECT_FALSE(req.has_header("Content-Type"));
  5361. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5362. res.set_content("empty-no-content-type", "text/plain");
  5363. })
  5364. .Put("/put",
  5365. [&](const Request &req, Response &res) {
  5366. EXPECT_EQ(req.body, "PUT");
  5367. res.set_content(req.body, "text/plain");
  5368. })
  5369. .Put("/put-large",
  5370. [&](const Request &req, Response &res) {
  5371. EXPECT_EQ(req.body, LARGE_DATA);
  5372. res.set_content(req.body, "text/plain");
  5373. })
  5374. .Patch("/patch",
  5375. [&](const Request &req, Response &res) {
  5376. EXPECT_EQ(req.body, "PATCH");
  5377. res.set_content(req.body, "text/plain");
  5378. })
  5379. .Delete("/delete",
  5380. [&](const Request & /*req*/, Response &res) {
  5381. res.set_content("DELETE", "text/plain");
  5382. })
  5383. .Delete("/delete-body",
  5384. [&](const Request &req, Response &res) {
  5385. EXPECT_EQ(req.body, "content");
  5386. res.set_content(req.body, "text/plain");
  5387. })
  5388. .Options(R"(\*)",
  5389. [&](const Request & /*req*/, Response &res) {
  5390. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5391. })
  5392. .CustomRoute("PROPFIND", "/dav/:id",
  5393. [&](const Request &req, Response &res) {
  5394. res.set_header("x-body-size",
  5395. std::to_string(req.body.size()));
  5396. res.set_header("x-matched-route", req.matched_route);
  5397. res.set_header("x-dav-id", req.path_params.at("id"));
  5398. res.status = StatusCode::MultiStatus_207;
  5399. res.set_content(req.body, "application/xml");
  5400. })
  5401. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5402. [&](const Request &req, Response &res) {
  5403. res.set_header("x-dav-match", req.matches[1]);
  5404. res.status = StatusCode::MultiStatus_207;
  5405. })
  5406. .CustomRoute("MKCOL", "/dav-mkcol",
  5407. [&](const Request &req, Response &res) {
  5408. EXPECT_TRUE(req.body.empty());
  5409. res.status = StatusCode::Created_201;
  5410. })
  5411. .CustomRoute(
  5412. "REPORT", "/dav-report",
  5413. [&](const Request & /*req*/, Response &res,
  5414. const ContentReader &content_reader) {
  5415. std::string body;
  5416. content_reader([&](const char *data, size_t data_length) {
  5417. body.append(data, data_length);
  5418. return true;
  5419. });
  5420. res.set_header("x-body-size", std::to_string(body.size()));
  5421. res.status = StatusCode::MultiStatus_207;
  5422. res.set_content(body, "application/xml");
  5423. })
  5424. .Get("/request-target",
  5425. [&](const Request &req, Response & /*res*/) {
  5426. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5427. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5428. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5429. })
  5430. .Get("/long-query-value",
  5431. [&](const Request &req, Response & /*res*/) {
  5432. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5433. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5434. })
  5435. .Get("/too-long-query-value",
  5436. [&](const Request &req, Response & /*res*/) {
  5437. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5438. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5439. })
  5440. .Get("/array-param",
  5441. [&](const Request &req, Response & /*res*/) {
  5442. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5443. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5444. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5445. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5446. })
  5447. .Get("/array-param-values",
  5448. [&](const Request &req, Response & /*res*/) {
  5449. auto values = req.get_param_values("array");
  5450. EXPECT_EQ(3u, values.size());
  5451. EXPECT_EQ("value1", values[0]);
  5452. EXPECT_EQ("value2", values[1]);
  5453. EXPECT_EQ("value3", values[2]);
  5454. auto empty = req.get_param_values("nonexistent");
  5455. EXPECT_TRUE(empty.empty());
  5456. })
  5457. .Post("/validate-no-multiple-headers",
  5458. [&](const Request &req, Response & /*res*/) {
  5459. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5460. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5461. })
  5462. .Post("/content_receiver",
  5463. [&](const Request &req, Response &res,
  5464. const ContentReader &content_reader) {
  5465. if (req.is_multipart_form_data()) {
  5466. std::vector<FormData> items;
  5467. content_reader(
  5468. [&](const FormData &file) {
  5469. items.push_back(file);
  5470. return true;
  5471. },
  5472. [&](const char *data, size_t data_length) {
  5473. items.back().content.append(data, data_length);
  5474. return true;
  5475. });
  5476. EXPECT_EQ(5u, items.size());
  5477. {
  5478. const auto &file = get_file_value(items, "text1");
  5479. EXPECT_TRUE(file.filename.empty());
  5480. EXPECT_EQ("text default", file.content);
  5481. }
  5482. {
  5483. const auto &file = get_file_value(items, "text2");
  5484. EXPECT_TRUE(file.filename.empty());
  5485. EXPECT_EQ("aωb", file.content);
  5486. }
  5487. {
  5488. const auto &file = get_file_value(items, "file1");
  5489. EXPECT_EQ("hello.txt", file.filename);
  5490. EXPECT_EQ("text/plain", file.content_type);
  5491. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5492. }
  5493. {
  5494. const auto &file = get_file_value(items, "file2");
  5495. EXPECT_EQ("world.json", file.filename);
  5496. EXPECT_EQ("application/json", file.content_type);
  5497. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5498. }
  5499. {
  5500. const auto &file = get_file_value(items, "file3");
  5501. EXPECT_TRUE(file.filename.empty());
  5502. EXPECT_EQ("application/octet-stream", file.content_type);
  5503. EXPECT_EQ(0u, file.content.size());
  5504. }
  5505. } else {
  5506. std::string body;
  5507. content_reader([&](const char *data, size_t data_length) {
  5508. EXPECT_EQ(7U, data_length);
  5509. body.append(data, data_length);
  5510. return true;
  5511. });
  5512. EXPECT_EQ(body, "content");
  5513. res.set_content(body, "text/plain");
  5514. }
  5515. })
  5516. .Put("/content_receiver",
  5517. [&](const Request & /*req*/, Response &res,
  5518. const ContentReader &content_reader) {
  5519. std::string body;
  5520. content_reader([&](const char *data, size_t data_length) {
  5521. body.append(data, data_length);
  5522. return true;
  5523. });
  5524. EXPECT_EQ(body, "content");
  5525. res.set_content(body, "text/plain");
  5526. })
  5527. .Patch("/content_receiver",
  5528. [&](const Request & /*req*/, Response &res,
  5529. const ContentReader &content_reader) {
  5530. std::string body;
  5531. content_reader([&](const char *data, size_t data_length) {
  5532. body.append(data, data_length);
  5533. return true;
  5534. });
  5535. EXPECT_EQ(body, "content");
  5536. res.set_content(body, "text/plain");
  5537. })
  5538. .Post("/query-string-and-body",
  5539. [&](const Request &req, Response & /*res*/) {
  5540. ASSERT_TRUE(req.has_param("key"));
  5541. EXPECT_EQ(req.get_param_value("key"), "value");
  5542. EXPECT_EQ(req.body, "content");
  5543. })
  5544. .Get("/last-request",
  5545. [&](const Request &req, Response & /*res*/) {
  5546. EXPECT_EQ("close", req.get_header_value("Connection"));
  5547. })
  5548. .Get(R"(/redirect/(\d+))",
  5549. [&](const Request &req, Response &res) {
  5550. auto num = std::stoi(req.matches[1]) + 1;
  5551. std::string url = "/redirect/" + std::to_string(num);
  5552. res.set_redirect(url);
  5553. })
  5554. .Post("/binary",
  5555. [&](const Request &req, Response &res) {
  5556. EXPECT_EQ(4U, req.body.size());
  5557. EXPECT_EQ("application/octet-stream",
  5558. req.get_header_value("Content-Type"));
  5559. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5560. res.set_content(req.body, "application/octet-stream");
  5561. })
  5562. .Put("/binary",
  5563. [&](const Request &req, Response &res) {
  5564. EXPECT_EQ(4U, req.body.size());
  5565. EXPECT_EQ("application/octet-stream",
  5566. req.get_header_value("Content-Type"));
  5567. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5568. res.set_content(req.body, "application/octet-stream");
  5569. })
  5570. .Patch("/binary",
  5571. [&](const Request &req, Response &res) {
  5572. EXPECT_EQ(4U, req.body.size());
  5573. EXPECT_EQ("application/octet-stream",
  5574. req.get_header_value("Content-Type"));
  5575. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5576. res.set_content(req.body, "application/octet-stream");
  5577. })
  5578. .Delete("/binary",
  5579. [&](const Request &req, Response &res) {
  5580. EXPECT_EQ(4U, req.body.size());
  5581. EXPECT_EQ("application/octet-stream",
  5582. req.get_header_value("Content-Type"));
  5583. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5584. res.set_content(req.body, "application/octet-stream");
  5585. })
  5586. .Get("/issue1772",
  5587. [&](const Request & /*req*/, Response &res) {
  5588. res.status = 401;
  5589. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5590. })
  5591. .Delete("/issue609",
  5592. [](const httplib::Request &, httplib::Response &res,
  5593. const httplib::ContentReader &) {
  5594. res.set_content("ok", "text/plain");
  5595. })
  5596. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5597. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5598. .Get("/compress",
  5599. [&](const Request & /*req*/, Response &res) {
  5600. res.set_content(
  5601. "12345678901234567890123456789012345678901234567890123456789"
  5602. "01234567890123456789012345678901234567890",
  5603. "text/plain");
  5604. })
  5605. .Get("/compress-with-charset",
  5606. [&](const Request & /*req*/, Response &res) {
  5607. res.set_content(
  5608. "12345678901234567890123456789012345678901234567890123456789"
  5609. "01234567890123456789012345678901234567890",
  5610. "application/json; charset=utf-8");
  5611. })
  5612. .Get("/nocompress",
  5613. [&](const Request & /*req*/, Response &res) {
  5614. res.set_content(
  5615. "12345678901234567890123456789012345678901234567890123456789"
  5616. "01234567890123456789012345678901234567890",
  5617. "application/octet-stream");
  5618. })
  5619. .Post("/compress-multipart",
  5620. [&](const Request &req, Response & /*res*/) {
  5621. EXPECT_EQ(2u, req.form.fields.size());
  5622. ASSERT_TRUE(!req.form.has_field("???"));
  5623. {
  5624. const auto &text = req.form.get_field("key1");
  5625. EXPECT_EQ("test", text);
  5626. }
  5627. {
  5628. const auto &text = req.form.get_field("key2");
  5629. EXPECT_EQ("--abcdefg123", text);
  5630. }
  5631. })
  5632. #endif
  5633. ;
  5634. persons_["john"] = "programmer";
  5635. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5636. svr_.wait_until_ready();
  5637. }
  5638. virtual void TearDown() {
  5639. svr_.stop();
  5640. if (!request_threads_.empty()) {
  5641. std::this_thread::sleep_for(std::chrono::seconds(1));
  5642. for (auto &t : request_threads_) {
  5643. t.join();
  5644. }
  5645. }
  5646. t_.join();
  5647. }
  5648. map<string, string> persons_;
  5649. #ifdef CPPHTTPLIB_SSL_ENABLED
  5650. SSLClient cli_;
  5651. SSLServer svr_;
  5652. #else
  5653. Client cli_;
  5654. Server svr_;
  5655. #endif
  5656. thread t_;
  5657. std::vector<thread> request_threads_;
  5658. };
  5659. TEST_F(ServerTest, GetMethod200) {
  5660. auto res = cli_.Get("/hi");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ("HTTP/1.1", res->version);
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. EXPECT_EQ("OK", res->reason);
  5665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5666. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5667. EXPECT_EQ("Hello World!", res->body);
  5668. }
  5669. TEST_F(ServerTest, GetEmptyFile) {
  5670. auto res = cli_.Get("/empty_file");
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::OK_200, res->status);
  5673. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5674. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5675. EXPECT_EQ("", res->body);
  5676. }
  5677. TEST_F(ServerTest, GetFileContent) {
  5678. auto res = cli_.Get("/file_content");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5682. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5683. EXPECT_EQ("test.html", res->body);
  5684. }
  5685. TEST_F(ServerTest, GetFileContentWithRange) {
  5686. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5689. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5690. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5691. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5692. EXPECT_EQ("est", res->body);
  5693. }
  5694. TEST_F(ServerTest, GetFileContentWithContentType) {
  5695. auto res = cli_.Get("/file_content_with_content_type");
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. EXPECT_EQ(StatusCode::OK_200, res->status);
  5698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5699. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5700. EXPECT_EQ("file\n", res->body);
  5701. }
  5702. TEST_F(ServerTest, GetInvalidFileContent) {
  5703. auto res = cli_.Get("/invalid_file_content");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5706. }
  5707. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5708. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5710. EXPECT_EQ("HTTP/1.1", res->version);
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5713. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5714. EXPECT_EQ("Hello World!", res->body);
  5715. }
  5716. TEST_F(ServerTest, GetMethod302) {
  5717. auto res = cli_.Get("/");
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::Found_302, res->status);
  5720. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5721. }
  5722. TEST_F(ServerTest, GetMethod302Redirect) {
  5723. cli_.set_follow_location(true);
  5724. auto res = cli_.Get("/");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. EXPECT_EQ("Hello World!", res->body);
  5728. EXPECT_EQ("/hi", res->location);
  5729. }
  5730. TEST_F(ServerTest, GetMethod404) {
  5731. auto res = cli_.Get("/invalid");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5734. }
  5735. TEST_F(ServerTest, HeadMethod200) {
  5736. auto res = cli_.Head("/hi");
  5737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5738. EXPECT_EQ(StatusCode::OK_200, res->status);
  5739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5740. EXPECT_TRUE(res->body.empty());
  5741. }
  5742. TEST_F(ServerTest, HeadMethod200Static) {
  5743. auto res = cli_.Head("/mount/dir/index.html");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::OK_200, res->status);
  5746. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5747. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5748. EXPECT_TRUE(res->body.empty());
  5749. }
  5750. TEST_F(ServerTest, HeadMethod404) {
  5751. auto res = cli_.Head("/invalid");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5754. EXPECT_TRUE(res->body.empty());
  5755. }
  5756. TEST_F(ServerTest, GetMethodPersonJohn) {
  5757. auto res = cli_.Get("/person/john");
  5758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5759. EXPECT_EQ(StatusCode::OK_200, res->status);
  5760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5761. EXPECT_EQ("programmer", res->body);
  5762. }
  5763. TEST_F(ServerTest, PostMethod1) {
  5764. auto res = cli_.Get("/person/john1");
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5767. res = cli_.Post("/person", "name=john1&note=coder",
  5768. "application/x-www-form-urlencoded");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. ASSERT_EQ(StatusCode::OK_200, res->status);
  5771. res = cli_.Get("/person/john1");
  5772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5773. ASSERT_EQ(StatusCode::OK_200, res->status);
  5774. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5775. ASSERT_EQ("coder", res->body);
  5776. }
  5777. TEST_F(ServerTest, PostMethod2) {
  5778. auto res = cli_.Get("/person/john2");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5781. Params params;
  5782. params.emplace("name", "john2");
  5783. params.emplace("note", "coder");
  5784. res = cli_.Post("/person", params);
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. ASSERT_EQ(StatusCode::OK_200, res->status);
  5787. res = cli_.Get("/person/john2");
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. ASSERT_EQ(StatusCode::OK_200, res->status);
  5790. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5791. ASSERT_EQ("coder", res->body);
  5792. }
  5793. TEST_F(ServerTest, PutMethod3) {
  5794. auto res = cli_.Get("/person/john3");
  5795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5796. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5797. Params params;
  5798. params.emplace("name", "john3");
  5799. params.emplace("note", "coder");
  5800. res = cli_.Put("/person", params);
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. ASSERT_EQ(StatusCode::OK_200, res->status);
  5803. res = cli_.Get("/person/john3");
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. ASSERT_EQ(StatusCode::OK_200, res->status);
  5806. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5807. ASSERT_EQ("coder", res->body);
  5808. }
  5809. TEST_F(ServerTest, DeleteMethod1) {
  5810. auto res = cli_.Get("/person/john4");
  5811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5812. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5813. Params params;
  5814. params.emplace("name", "john4");
  5815. params.emplace("note", "coder");
  5816. res = cli_.Post("/person", params);
  5817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5818. ASSERT_EQ(StatusCode::OK_200, res->status);
  5819. res = cli_.Get("/person/john4");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. ASSERT_EQ(StatusCode::OK_200, res->status);
  5822. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5823. ASSERT_EQ("coder", res->body);
  5824. Params delete_params;
  5825. delete_params.emplace("name", "john4");
  5826. res = cli_.Delete("/person", delete_params);
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. ASSERT_EQ(StatusCode::OK_200, res->status);
  5829. ASSERT_EQ("DELETED", res->body);
  5830. res = cli_.Get("/person/john4");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5833. }
  5834. TEST_F(ServerTest, DeleteMethod2) {
  5835. auto res = cli_.Get("/person/john5");
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5838. Params params;
  5839. params.emplace("name", "john5");
  5840. params.emplace("note", "developer");
  5841. res = cli_.Post("/person", params);
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. ASSERT_EQ(StatusCode::OK_200, res->status);
  5844. res = cli_.Get("/person/john5");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. ASSERT_EQ(StatusCode::OK_200, res->status);
  5847. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5848. ASSERT_EQ("developer", res->body);
  5849. Params delete_params;
  5850. delete_params.emplace("name", "john5");
  5851. Headers headers;
  5852. headers.emplace("Custom-Header", "test-value");
  5853. res = cli_.Delete("/person", headers, delete_params);
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. ASSERT_EQ(StatusCode::OK_200, res->status);
  5856. ASSERT_EQ("DELETED", res->body);
  5857. res = cli_.Get("/person/john5");
  5858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5859. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5860. }
  5861. TEST_F(ServerTest, DeleteMethod3) {
  5862. auto res = cli_.Get("/person/john6");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5865. Params params;
  5866. params.emplace("name", "john6");
  5867. params.emplace("note", "tester");
  5868. res = cli_.Post("/person", params);
  5869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5870. ASSERT_EQ(StatusCode::OK_200, res->status);
  5871. res = cli_.Get("/person/john6");
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. ASSERT_EQ(StatusCode::OK_200, res->status);
  5874. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5875. ASSERT_EQ("tester", res->body);
  5876. Params delete_params;
  5877. delete_params.emplace("name", "john6");
  5878. Headers headers;
  5879. headers.emplace("Custom-Header", "test-value");
  5880. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5882. ASSERT_EQ(StatusCode::OK_200, res->status);
  5883. ASSERT_EQ("DELETED", res->body);
  5884. res = cli_.Get("/person/john6");
  5885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5886. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5887. }
  5888. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5889. Params params;
  5890. params.emplace("json", JSON_DATA);
  5891. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5893. ASSERT_EQ(StatusCode::OK_200, res->status);
  5894. ASSERT_EQ(JSON_DATA, res->body);
  5895. }
  5896. TEST_F(ServerTest, PostEmptyContent) {
  5897. auto res = cli_.Post("/empty", "", "text/plain");
  5898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5899. ASSERT_EQ(StatusCode::OK_200, res->status);
  5900. ASSERT_EQ("empty", res->body);
  5901. }
  5902. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5903. auto res = cli_.Post("/empty-no-content-type");
  5904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5905. ASSERT_EQ(StatusCode::OK_200, res->status);
  5906. ASSERT_EQ("empty-no-content-type", res->body);
  5907. }
  5908. TEST_F(ServerTest, PostPathOnly) {
  5909. auto res = cli_.Post("/path-only");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. ASSERT_EQ(StatusCode::OK_200, res->status);
  5912. ASSERT_EQ("path-only", res->body);
  5913. }
  5914. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5915. auto res = cli_.Post("/path-headers-only",
  5916. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. ASSERT_EQ(StatusCode::OK_200, res->status);
  5919. ASSERT_EQ("path-headers-only", res->body);
  5920. }
  5921. TEST_F(ServerTest, PostLarge) {
  5922. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. ASSERT_EQ(StatusCode::OK_200, res->status);
  5925. EXPECT_EQ(LARGE_DATA, res->body);
  5926. }
  5927. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5928. auto res = cli_.Put("/empty-no-content-type");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. ASSERT_EQ(StatusCode::OK_200, res->status);
  5931. ASSERT_EQ("empty-no-content-type", res->body);
  5932. }
  5933. TEST_F(ServerTest, GetMethodDir) {
  5934. auto res = cli_.Get("/dir/");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. EXPECT_EQ(StatusCode::OK_200, res->status);
  5937. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5938. auto body = R"(<html>
  5939. <head>
  5940. </head>
  5941. <body>
  5942. <a href="/dir/test.html">Test</a>
  5943. <a href="/hi">hi</a>
  5944. </body>
  5945. </html>
  5946. )";
  5947. EXPECT_EQ(body, res->body);
  5948. }
  5949. TEST_F(ServerTest, GetMethodDirTest) {
  5950. auto res = cli_.Get("/dir/test.html");
  5951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5952. EXPECT_EQ(StatusCode::OK_200, res->status);
  5953. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5954. EXPECT_EQ("test.html", res->body);
  5955. }
  5956. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5957. auto res = cli_.Get("/dir/../dir/test.html");
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::OK_200, res->status);
  5960. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5961. EXPECT_EQ("test.html", res->body);
  5962. }
  5963. TEST_F(ServerTest, GetMethodInvalidPath) {
  5964. auto res = cli_.Get("/dir/../test.html");
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5967. }
  5968. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5969. auto res = cli_.Get("/../www/dir/test.html");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5972. }
  5973. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5974. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5976. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5977. }
  5978. TEST_F(ServerTest, GetMethodDirMountTest) {
  5979. auto res = cli_.Get("/mount/dir/test.html");
  5980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5983. EXPECT_EQ("test.html", res->body);
  5984. }
  5985. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5986. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5988. EXPECT_EQ(StatusCode::OK_200, res->status);
  5989. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5990. EXPECT_EQ("test.html", res->body);
  5991. }
  5992. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5993. auto res = cli_.Get("/mount/dir/../test.html");
  5994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5995. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5996. }
  5997. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5998. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6001. }
  6002. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6003. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6005. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6006. }
  6007. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6008. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6011. }
  6012. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6013. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6015. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6016. }
  6017. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6018. auto res = cli_.Get("/mount/dir");
  6019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6020. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6021. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6022. }
  6023. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6024. auto res = cli_.Get("//dir");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6027. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6028. }
  6029. TEST_F(ServerTest, PostMethod303) {
  6030. auto res = cli_.Post("/1", "body", "text/plain");
  6031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6032. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6033. EXPECT_EQ("/2", res->get_header_value("Location"));
  6034. }
  6035. TEST_F(ServerTest, PostMethod303Redirect) {
  6036. cli_.set_follow_location(true);
  6037. auto res = cli_.Post("/1", "body", "text/plain");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. EXPECT_EQ("redirected.", res->body);
  6041. EXPECT_EQ("/2", res->location);
  6042. }
  6043. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6044. auto res = cli_.Get("/dir/test.abcde");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6048. EXPECT_EQ("abcde", res->body);
  6049. }
  6050. TEST_F(ServerTest, StaticFileRange) {
  6051. auto res =
  6052. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6055. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6056. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6057. EXPECT_EQ(true, res->has_header("Content-Range"));
  6058. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6059. EXPECT_EQ(std::string("cd"), res->body);
  6060. }
  6061. TEST_F(ServerTest, StaticFileRanges) {
  6062. auto res = cli_.Get("/dir/test.abcde",
  6063. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6066. EXPECT_TRUE(
  6067. res->get_header_value("Content-Type")
  6068. .find(
  6069. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6070. 0);
  6071. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6072. }
  6073. TEST_F(ServerTest, StaticFileRangeHead) {
  6074. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6077. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6078. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6079. EXPECT_EQ(true, res->has_header("Content-Range"));
  6080. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6081. }
  6082. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6083. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6087. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ(true, res->has_header("Content-Range"));
  6089. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6090. res->get_header_value("Content-Range"));
  6091. EXPECT_EQ("LAST\n", res->body);
  6092. }
  6093. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6094. auto res =
  6095. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6099. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6100. EXPECT_EQ(true, res->has_header("Content-Range"));
  6101. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6102. }
  6103. TEST_F(ServerTest, StaticFileBigFile) {
  6104. auto res = cli_.Get("/dir/1MB.txt");
  6105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6108. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6109. }
  6110. TEST_F(ServerTest, InvalidBaseDirMount) {
  6111. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6112. }
  6113. TEST_F(ServerTest, Binary) {
  6114. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6115. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6116. "application/octet-stream");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. ASSERT_EQ(StatusCode::OK_200, res->status);
  6119. ASSERT_EQ(4U, res->body.size());
  6120. res = cli_.Put("/binary", binary.data(), binary.size(),
  6121. "application/octet-stream");
  6122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6123. ASSERT_EQ(StatusCode::OK_200, res->status);
  6124. ASSERT_EQ(4U, res->body.size());
  6125. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6126. "application/octet-stream");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. ASSERT_EQ(StatusCode::OK_200, res->status);
  6129. ASSERT_EQ(4U, res->body.size());
  6130. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6131. "application/octet-stream");
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. ASSERT_EQ(StatusCode::OK_200, res->status);
  6134. ASSERT_EQ(4U, res->body.size());
  6135. }
  6136. TEST_F(ServerTest, BinaryString) {
  6137. auto binary = std::string("\x00\x01\x02\x03", 4);
  6138. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. ASSERT_EQ(4U, res->body.size());
  6142. res = cli_.Put("/binary", binary, "application/octet-stream");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. ASSERT_EQ(StatusCode::OK_200, res->status);
  6145. ASSERT_EQ(4U, res->body.size());
  6146. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6148. ASSERT_EQ(StatusCode::OK_200, res->status);
  6149. ASSERT_EQ(4U, res->body.size());
  6150. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. ASSERT_EQ(StatusCode::OK_200, res->status);
  6153. ASSERT_EQ(4U, res->body.size());
  6154. }
  6155. TEST_F(ServerTest, EmptyRequest) {
  6156. auto res = cli_.Get("");
  6157. ASSERT_TRUE(!res);
  6158. EXPECT_EQ(Error::Connection, res.error());
  6159. }
  6160. TEST_F(ServerTest, LongRequest) {
  6161. std::string request;
  6162. for (size_t i = 0; i < 545; i++) {
  6163. request += "/TooLongRequest";
  6164. }
  6165. request += "OK";
  6166. auto res = cli_.Get(request.c_str());
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6169. }
  6170. TEST_F(ServerTest, TooLongRequest) {
  6171. std::string request;
  6172. for (size_t i = 0; i < 546; i++) {
  6173. request += "/TooLongRequest";
  6174. }
  6175. request += "_NG";
  6176. auto start = std::chrono::high_resolution_clock::now();
  6177. cli_.set_keep_alive(true);
  6178. auto res = cli_.Get(request.c_str());
  6179. auto end = std::chrono::high_resolution_clock::now();
  6180. auto elapsed =
  6181. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6182. .count();
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6185. EXPECT_LE(elapsed, 1000);
  6186. EXPECT_EQ("close", res->get_header_value("Connection"));
  6187. EXPECT_FALSE(cli_.is_socket_open());
  6188. }
  6189. TEST_F(ServerTest, AlmostTooLongRequest) {
  6190. // test for #2046 - URI length check shouldn't include other content on req
  6191. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6192. // leading /, space, HTTP/1.1)
  6193. std::string request =
  6194. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6195. auto res = cli_.Get(request.c_str());
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6198. }
  6199. TEST_F(ServerTest, LongHeader) {
  6200. Request req;
  6201. req.method = "GET";
  6202. req.path = "/hi";
  6203. std::string host_and_port;
  6204. host_and_port += HOST;
  6205. host_and_port += ":";
  6206. host_and_port += std::to_string(PORT);
  6207. req.headers.emplace("Host", host_and_port.c_str());
  6208. req.headers.emplace("Accept", "*/*");
  6209. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6210. req.headers.emplace(
  6211. "Header-Name",
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6229. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6230. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6231. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6232. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6233. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6234. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6235. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6236. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6237. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6238. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6239. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6240. "@@@@@@@@@@@@@@@@");
  6241. auto res = std::make_shared<Response>();
  6242. auto error = Error::Success;
  6243. auto ret = cli_.send(req, *res, error);
  6244. ASSERT_TRUE(ret);
  6245. EXPECT_EQ(StatusCode::OK_200, res->status);
  6246. }
  6247. TEST_F(ServerTest, LongQueryValue) {
  6248. auto start = std::chrono::high_resolution_clock::now();
  6249. cli_.set_keep_alive(true);
  6250. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6251. auto end = std::chrono::high_resolution_clock::now();
  6252. auto elapsed =
  6253. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6254. .count();
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6257. EXPECT_LE(elapsed, 1000);
  6258. EXPECT_EQ("close", res->get_header_value("Connection"));
  6259. EXPECT_FALSE(cli_.is_socket_open());
  6260. }
  6261. TEST_F(ServerTest, TooLongQueryValue) {
  6262. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6263. ASSERT_FALSE(res);
  6264. EXPECT_EQ(Error::Read, res.error());
  6265. }
  6266. TEST_F(ServerTest, TooLongHeader) {
  6267. Request req;
  6268. req.method = "GET";
  6269. req.path = "/hi";
  6270. std::string host_and_port;
  6271. host_and_port += HOST;
  6272. host_and_port += ":";
  6273. host_and_port += std::to_string(PORT);
  6274. req.headers.emplace("Host", host_and_port.c_str());
  6275. req.headers.emplace("Accept", "*/*");
  6276. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6277. req.headers.emplace(
  6278. "Header-Name",
  6279. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6280. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6281. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6282. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6283. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6284. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6285. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6286. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6287. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6288. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6289. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6307. "@@@@@@@@@@@@@@@@@");
  6308. auto res = std::make_shared<Response>();
  6309. auto error = Error::Success;
  6310. auto ret = cli_.send(req, *res, error);
  6311. ASSERT_TRUE(ret);
  6312. EXPECT_EQ(StatusCode::OK_200, res->status);
  6313. }
  6314. TEST_F(ServerTest, HeaderCountAtLimit) {
  6315. // Test with headers just under the 100 limit
  6316. httplib::Headers headers;
  6317. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6318. // This should keep us just under the 100 header limit
  6319. for (int i = 0; i < 95; i++) {
  6320. std::string name = "X-Test-Header-" + std::to_string(i);
  6321. std::string value = "value" + std::to_string(i);
  6322. headers.emplace(name, value);
  6323. }
  6324. // This should work fine as we're under the limit
  6325. auto res = cli_.Get("/hi", headers);
  6326. EXPECT_TRUE(res);
  6327. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6328. }
  6329. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6330. // Test with many headers to exceed the 100 limit
  6331. httplib::Headers headers;
  6332. // Add 150 headers to definitely exceed the 100 limit
  6333. for (int i = 0; i < 150; i++) {
  6334. std::string name = "X-Test-Header-" + std::to_string(i);
  6335. std::string value = "value" + std::to_string(i);
  6336. headers.emplace(name, value);
  6337. }
  6338. // This should fail due to exceeding header count limit
  6339. cli_.set_keep_alive(true);
  6340. auto res = cli_.Get("/hi", headers);
  6341. // The server should respond with 400 Bad Request
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6344. EXPECT_EQ("close", res->get_header_value("Connection"));
  6345. EXPECT_FALSE(cli_.is_socket_open());
  6346. }
  6347. TEST_F(ServerTest, PercentEncoding) {
  6348. auto res = cli_.Get("/e%6edwith%");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. }
  6352. TEST_F(ServerTest, PercentEncodingUnicode) {
  6353. auto res = cli_.Get("/e%u006edwith%");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. }
  6357. TEST_F(ServerTest, InvalidPercentEncoding) {
  6358. auto res = cli_.Get("/%endwith%");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6361. }
  6362. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6363. auto res = cli_.Get("/%uendwith%");
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6366. }
  6367. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6368. auto res = cli_.Get("/hello?aaa=bbb%");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6371. }
  6372. TEST_F(ServerTest, PlusSignEncoding) {
  6373. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. EXPECT_EQ("a +b", res->body);
  6377. }
  6378. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6379. // This test simulates a potential DoS attack using many headers
  6380. // to verify our security fix prevents memory exhaustion
  6381. httplib::Headers attack_headers;
  6382. // Attempt to add many headers like an attacker would (200 headers to far
  6383. // exceed limit)
  6384. for (int i = 0; i < 200; i++) {
  6385. std::string name = "X-Attack-Header-" + std::to_string(i);
  6386. std::string value = "attack_payload_" + std::to_string(i);
  6387. attack_headers.emplace(name, value);
  6388. }
  6389. // Try to POST with excessive headers
  6390. cli_.set_keep_alive(true);
  6391. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6392. // Should either fail or return 400 Bad Request due to security limit
  6393. if (res) {
  6394. // If we get a response, it should be 400 Bad Request
  6395. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6396. EXPECT_EQ("close", res->get_header_value("Connection"));
  6397. }
  6398. EXPECT_FALSE(cli_.is_socket_open());
  6399. }
  6400. TEST_F(ServerTest, MultipartFormData) {
  6401. UploadFormDataItems items = {
  6402. {"text1", "text default", "", ""},
  6403. {"text2", "aωb", "", ""},
  6404. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6405. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6406. {"file3", "", "", "application/octet-stream"},
  6407. {"file4", "", "", " application/json tmp-string "}};
  6408. auto res = cli_.Post("/multipart", items);
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. EXPECT_EQ(StatusCode::OK_200, res->status);
  6411. }
  6412. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6413. UploadFormDataItems items = {
  6414. {"text", "default text", "", ""},
  6415. {"multi_text1", "aaaaa", "", ""},
  6416. {"multi_text1", "bbbbb", "", ""},
  6417. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6418. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6419. "application/json"},
  6420. };
  6421. auto res = cli_.Post("/multipart/multi_file_values", items);
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::OK_200, res->status);
  6424. }
  6425. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6426. auto res = cli_.Get("/hi");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::OK_200, res->status);
  6429. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6430. EXPECT_EQ("Hello World!", res->body);
  6431. }
  6432. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6433. Request req;
  6434. req.method = "POST";
  6435. req.path = "/chunked";
  6436. std::string host_and_port;
  6437. host_and_port += HOST;
  6438. host_and_port += ":";
  6439. host_and_port += std::to_string(PORT);
  6440. req.headers.emplace("Host", host_and_port.c_str());
  6441. req.headers.emplace("Accept", "*/*");
  6442. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6443. req.headers.emplace("Content-Type", "text/plain");
  6444. req.headers.emplace("Content-Length", "0");
  6445. req.headers.emplace(
  6446. "Transfer-Encoding",
  6447. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6448. // Client does not chunk, so make a chunked body manually.
  6449. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6450. auto res = std::make_shared<Response>();
  6451. auto error = Error::Success;
  6452. auto ret = cli_.send(req, *res, error);
  6453. ASSERT_TRUE(ret);
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. }
  6456. template <typename ClientT>
  6457. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6458. int expected_status) {
  6459. Request req;
  6460. req.method = "POST";
  6461. req.path = "/chunked";
  6462. std::string host_and_port;
  6463. host_and_port += HOST;
  6464. host_and_port += ":";
  6465. host_and_port += std::to_string(PORT);
  6466. req.headers.emplace("Host", host_and_port.c_str());
  6467. req.headers.emplace("Content-Length", "0");
  6468. req.headers.emplace("Transfer-Encoding", "chunked");
  6469. req.body = body;
  6470. auto res = std::make_shared<Response>();
  6471. auto error = Error::Success;
  6472. ASSERT_TRUE(cli.send(req, *res, error));
  6473. EXPECT_EQ(expected_status, res->status);
  6474. }
  6475. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6476. // rather than treat them as valid lengths.
  6477. template <typename ClientT>
  6478. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6479. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6480. }
  6481. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6482. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6483. }
  6484. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6485. expect_chunked_body_rejected(
  6486. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6487. }
  6488. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6489. // chunk-size line carries no CR, LF or other control character ahead of its
  6490. // terminator. Such a line must be refused rather than read as extension text.
  6491. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6492. expect_chunked_body_rejected(
  6493. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6494. }
  6495. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6496. expect_chunked_body_rejected(
  6497. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6498. }
  6499. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6500. expect_chunked_body_rejected(
  6501. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6502. }
  6503. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6504. // The literal stays split: a hex escape consumes every hex digit that
  6505. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6506. expect_chunked_body_rejected(
  6507. cli_, "4;a\x01"
  6508. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6509. }
  6510. TEST_F(ServerTest, AcceptsChunkExtension) {
  6511. expect_chunked_body_status(cli_,
  6512. "4;name=value\r\ndech\r\n"
  6513. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6514. "0;last\r\n\r\n",
  6515. StatusCode::OK_200);
  6516. }
  6517. TEST_F(ServerTest, GetStreamed2) {
  6518. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6521. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6522. EXPECT_EQ(true, res->has_header("Content-Range"));
  6523. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6524. EXPECT_EQ(std::string("ab"), res->body);
  6525. }
  6526. TEST_F(ServerTest, GetStreamed) {
  6527. auto res = cli_.Get("/streamed");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6531. EXPECT_EQ(std::string("aaabbb"), res->body);
  6532. }
  6533. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6534. auto res = cli_.Get("/streamed-without-length",
  6535. Headers{make_range_header({{0, -1}})});
  6536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6537. EXPECT_EQ(StatusCode::OK_200, res->status);
  6538. EXPECT_EQ(false, res->has_header("Content-Length"));
  6539. EXPECT_EQ(false, res->has_header("Content-Range"));
  6540. EXPECT_EQ(std::string("abcdefg"), res->body);
  6541. }
  6542. TEST_F(ServerTest, GetStreamedWithRange1) {
  6543. auto res =
  6544. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6547. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6548. EXPECT_EQ(true, res->has_header("Content-Range"));
  6549. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6550. EXPECT_EQ(std::string("def"), res->body);
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithRange2) {
  6553. auto res =
  6554. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6557. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6558. EXPECT_EQ(true, res->has_header("Content-Range"));
  6559. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6560. EXPECT_EQ(std::string("bcdefg"), res->body);
  6561. }
  6562. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6563. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6565. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6566. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6567. EXPECT_EQ(true, res->has_header("Content-Range"));
  6568. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6569. EXPECT_EQ(std::string("efg"), res->body);
  6570. }
  6571. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6572. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6573. // the entire representation.
  6574. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6575. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6578. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6579. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6580. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6581. }
  6582. }
  6583. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6584. auto res =
  6585. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6588. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6589. EXPECT_EQ(false, res->has_header("Content-Range"));
  6590. EXPECT_EQ(0U, res->body.size());
  6591. }
  6592. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6593. // Only a 206 is served as a partial representation. Under any other status
  6594. // `apply_ranges()` reported the full content length, so the body must match
  6595. // that header, and the content provider must never be asked for an offset
  6596. // outside the representation.
  6597. auto check = [&](int status, const char *range) {
  6598. auto path =
  6599. std::string("/streamed-with-range?status=") + std::to_string(status);
  6600. auto ctx = path + " Range: " + range;
  6601. auto res = cli_.Get(path, Headers{{"Range", range}});
  6602. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6603. EXPECT_EQ(status, res->status) << ctx;
  6604. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6606. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6607. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6608. };
  6609. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6610. check(403, "bytes=3-5");
  6611. // The offset is far past the representation.
  6612. check(403, "bytes=100000-100200");
  6613. // `first_pos` is still -1 here, and the bounds asserts in
  6614. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6615. check(403, "bytes=-3");
  6616. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6617. // multipart branch would have written one that is empty.
  6618. check(403, "bytes=1-2, 4-5");
  6619. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6620. // covers the whole representation.
  6621. check(200, "bytes=3-5");
  6622. check(200, "bytes=1-2, 4-5");
  6623. }
  6624. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6625. auto res =
  6626. cli_.Get("/streamed-with-range",
  6627. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6628. "92233720368547758079223372036854775807"}});
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6631. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6632. EXPECT_EQ(false, res->has_header("Content-Range"));
  6633. EXPECT_EQ(0U, res->body.size());
  6634. }
  6635. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6636. auto res = cli_.Get(
  6637. "/with-range",
  6638. Headers{{"Range",
  6639. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6640. {"Accept-Encoding", ""}});
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6643. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6644. EXPECT_EQ(true, res->has_header("Content-Range"));
  6645. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6646. EXPECT_EQ(std::string("abcdefg"), res->body);
  6647. }
  6648. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6649. auto res = cli_.Get("/with-range", Headers{
  6650. {"Range", "bytes=0-"},
  6651. {"Accept-Encoding", ""},
  6652. });
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6655. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6656. EXPECT_EQ(true, res->has_header("Content-Range"));
  6657. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6658. EXPECT_EQ(std::string("abcdefg"), res->body);
  6659. }
  6660. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6661. auto res = cli_.Get("/streamed-with-range",
  6662. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6664. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6665. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6666. EXPECT_EQ(false, res->has_header("Content-Range"));
  6667. EXPECT_EQ(267U, res->body.size());
  6668. // Check that both range contents are present
  6669. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6670. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6671. // Check that Content-Range headers are present for both ranges
  6672. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6673. std::string::npos);
  6674. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6675. std::string::npos);
  6676. }
  6677. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6678. Ranges ranges;
  6679. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6680. ranges.emplace_back(0, -1);
  6681. }
  6682. auto res = cli_.Get("/streamed-with-range?error",
  6683. Headers{{make_range_header(ranges)}});
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6686. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(false, res->has_header("Content-Range"));
  6688. EXPECT_EQ(0U, res->body.size());
  6689. }
  6690. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6691. auto res = cli_.Get("/streamed-with-range",
  6692. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6694. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6695. EXPECT_EQ(5U, res->body.size());
  6696. // Check that overlapping ranges are coalesced into a single range
  6697. EXPECT_EQ("bcdef", res->body);
  6698. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6699. // Should be single range, not multipart
  6700. EXPECT_TRUE(res->has_header("Content-Range"));
  6701. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6702. }
  6703. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6704. auto res = cli_.Get("/streamed-with-range",
  6705. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6708. EXPECT_EQ(268U, res->body.size());
  6709. // Check that both range contents are present
  6710. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6711. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6712. // Check that Content-Range headers are present for both ranges
  6713. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6714. std::string::npos);
  6715. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6716. std::string::npos);
  6717. }
  6718. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6719. auto res = cli_.Get("/streamed-with-range",
  6720. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6723. EXPECT_EQ(269U, res->body.size());
  6724. // Check that both duplicate range contents are present
  6725. size_t first_abc = res->body.find("abc\r\n");
  6726. EXPECT_TRUE(first_abc != std::string::npos);
  6727. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6728. EXPECT_TRUE(second_abc != std::string::npos);
  6729. // Check that Content-Range headers are present for both ranges
  6730. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6731. EXPECT_TRUE(first_range != std::string::npos);
  6732. size_t second_range =
  6733. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6734. EXPECT_TRUE(second_range != std::string::npos);
  6735. }
  6736. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6737. auto res =
  6738. cli_.Get("/streamed-with-range?error",
  6739. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6742. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6743. EXPECT_EQ(false, res->has_header("Content-Range"));
  6744. EXPECT_EQ(0U, res->body.size());
  6745. }
  6746. TEST_F(ServerTest, GetStreamedEndless) {
  6747. uint64_t offset = 0;
  6748. auto res = cli_.Get("/streamed-cancel",
  6749. [&](const char * /*data*/, uint64_t data_length) {
  6750. if (offset < 100) {
  6751. offset += data_length;
  6752. return true;
  6753. }
  6754. return false;
  6755. });
  6756. ASSERT_TRUE(!res);
  6757. EXPECT_EQ(Error::Canceled, res.error());
  6758. }
  6759. TEST_F(ServerTest, ClientStop) {
  6760. std::atomic_size_t count{4};
  6761. std::vector<std::thread> threads;
  6762. for (auto i = count.load(); i != 0; --i) {
  6763. threads.emplace_back([&]() {
  6764. auto res = cli_.Get("/streamed-cancel",
  6765. [&](const char *, uint64_t) { return true; });
  6766. --count;
  6767. ASSERT_TRUE(!res);
  6768. EXPECT_TRUE(res.error() == Error::Canceled ||
  6769. res.error() == Error::Read || res.error() == Error::Write);
  6770. });
  6771. }
  6772. std::this_thread::sleep_for(std::chrono::seconds(2));
  6773. while (count != 0) {
  6774. cli_.stop();
  6775. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6776. }
  6777. for (auto &t : threads) {
  6778. t.join();
  6779. }
  6780. }
  6781. TEST_F(ServerTest, GetWithRange1) {
  6782. auto res = cli_.Get("/with-range", Headers{
  6783. make_range_header({{3, 5}}),
  6784. {"Accept-Encoding", ""},
  6785. });
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6788. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6789. EXPECT_EQ(true, res->has_header("Content-Range"));
  6790. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6791. EXPECT_EQ(std::string("def"), res->body);
  6792. }
  6793. TEST_F(ServerTest, GetWithRange2) {
  6794. auto res = cli_.Get("/with-range", Headers{
  6795. make_range_header({{1, -1}}),
  6796. {"Accept-Encoding", ""},
  6797. });
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6800. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6801. EXPECT_EQ(true, res->has_header("Content-Range"));
  6802. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6803. EXPECT_EQ(std::string("bcdefg"), res->body);
  6804. }
  6805. TEST_F(ServerTest, GetWithRange3) {
  6806. auto res = cli_.Get("/with-range", Headers{
  6807. make_range_header({{0, 0}}),
  6808. {"Accept-Encoding", ""},
  6809. });
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6812. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6813. EXPECT_EQ(true, res->has_header("Content-Range"));
  6814. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6815. EXPECT_EQ(std::string("a"), res->body);
  6816. }
  6817. TEST_F(ServerTest, GetWithRange4) {
  6818. auto res = cli_.Get("/with-range", Headers{
  6819. make_range_header({{-1, 2}}),
  6820. {"Accept-Encoding", ""},
  6821. });
  6822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6823. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6824. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6825. EXPECT_EQ(true, res->has_header("Content-Range"));
  6826. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6827. EXPECT_EQ(std::string("fg"), res->body);
  6828. }
  6829. TEST_F(ServerTest, GetWithRange5) {
  6830. auto res = cli_.Get("/with-range", Headers{
  6831. make_range_header({{0, 5}}),
  6832. {"Accept-Encoding", ""},
  6833. });
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6836. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6837. EXPECT_EQ(true, res->has_header("Content-Range"));
  6838. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6839. EXPECT_EQ(std::string("abcdef"), res->body);
  6840. }
  6841. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6842. auto res =
  6843. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6845. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6846. }
  6847. TEST_F(ServerTest, GetWithRangeMultipart) {
  6848. auto res =
  6849. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6852. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6853. EXPECT_EQ(false, res->has_header("Content-Range"));
  6854. EXPECT_EQ(267U, res->body.size());
  6855. }
  6856. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6857. auto res = cli_.Get("/with-range",
  6858. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6861. }
  6862. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6863. auto res = cli_.Get("/with-range-customized-response",
  6864. Headers{{make_range_header({{1, 2}})}});
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6867. EXPECT_EQ(true, res->has_header("Content-Length"));
  6868. EXPECT_EQ(false, res->has_header("Content-Range"));
  6869. EXPECT_EQ(JSON_DATA, res->body);
  6870. }
  6871. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6872. auto res = cli_.Get("/with-range-customized-response",
  6873. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6876. EXPECT_EQ(true, res->has_header("Content-Length"));
  6877. EXPECT_EQ(false, res->has_header("Content-Range"));
  6878. EXPECT_EQ(JSON_DATA, res->body);
  6879. }
  6880. TEST_F(ServerTest, Issue1772) {
  6881. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6884. }
  6885. TEST_F(ServerTest, Issue609) {
  6886. auto res = cli_.Delete("/issue609");
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. EXPECT_EQ(StatusCode::OK_200, res->status);
  6889. EXPECT_EQ(std::string("ok"), res->body);
  6890. }
  6891. TEST_F(ServerTest, GetStreamedChunked) {
  6892. auto res = cli_.Get("/streamed-chunked");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::OK_200, res->status);
  6895. EXPECT_EQ(std::string("123456789"), res->body);
  6896. }
  6897. TEST_F(ServerTest, GetStreamedChunked2) {
  6898. auto res = cli_.Get("/streamed-chunked2");
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. EXPECT_EQ(std::string("123456789"), res->body);
  6902. }
  6903. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6904. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. EXPECT_EQ(std::string("123456789"), res->body);
  6908. EXPECT_TRUE(res->has_header("Trailer"));
  6909. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6910. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6911. // Trailers are now stored separately from headers (security fix)
  6912. EXPECT_EQ(2U, res->trailers.size());
  6913. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6914. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6915. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6916. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6917. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6918. // Verify trailers are NOT in headers (security verification)
  6919. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6920. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6921. }
  6922. TEST_F(ServerTest, LargeChunkedPost) {
  6923. Request req;
  6924. req.method = "POST";
  6925. req.path = "/large-chunked";
  6926. std::string host_and_port;
  6927. host_and_port += HOST;
  6928. host_and_port += ":";
  6929. host_and_port += std::to_string(PORT);
  6930. req.headers.emplace("Host", host_and_port.c_str());
  6931. req.headers.emplace("Accept", "*/*");
  6932. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6933. req.headers.emplace("Content-Type", "text/plain");
  6934. req.headers.emplace("Content-Length", "0");
  6935. req.headers.emplace("Transfer-Encoding", "chunked");
  6936. std::string long_string(30 * 1024u, 'a');
  6937. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6938. // Attempt to make a large enough post to exceed OS buffers, to test that
  6939. // the server handles short reads if the full chunk data isn't available.
  6940. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6941. auto res = std::make_shared<Response>();
  6942. auto error = Error::Success;
  6943. auto ret = cli_.send(req, *res, error);
  6944. ASSERT_TRUE(ret);
  6945. EXPECT_EQ(StatusCode::OK_200, res->status);
  6946. }
  6947. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6948. auto res = cli_.Get("/remote_addr");
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::OK_200, res->status);
  6951. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6952. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6953. }
  6954. TEST_F(ServerTest, GetMethodLocalAddr) {
  6955. auto res = cli_.Get("/local_addr");
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6959. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6960. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6961. }
  6962. TEST_F(ServerTest, HTTPResponseSplitting) {
  6963. auto res = cli_.Get("/http_response_splitting");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. TEST_F(ServerTest, SlowRequest) {
  6968. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6969. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6970. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6971. }
  6972. #if 0
  6973. TEST_F(ServerTest, SlowPost) {
  6974. char buffer[64 * 1024];
  6975. memset(buffer, 0x42, sizeof(buffer));
  6976. auto res = cli_.Post(
  6977. "/slowpost", 64 * 1024 * 1024,
  6978. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6979. auto ret = sink.write(buffer, sizeof(buffer));
  6980. EXPECT_TRUE(ret);
  6981. return true;
  6982. },
  6983. "text/plain");
  6984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6985. EXPECT_EQ(StatusCode::OK_200, res->status);
  6986. }
  6987. TEST_F(ServerTest, SlowPostFail) {
  6988. char buffer[64 * 1024];
  6989. memset(buffer, 0x42, sizeof(buffer));
  6990. cli_.set_write_timeout(std::chrono::seconds(0));
  6991. auto res = cli_.Post(
  6992. "/slowpost", 64 * 1024 * 1024,
  6993. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6994. sink.write(buffer, sizeof(buffer));
  6995. return true;
  6996. },
  6997. "text/plain");
  6998. ASSERT_TRUE(!res);
  6999. EXPECT_EQ(Error::Write, res.error());
  7000. }
  7001. #endif
  7002. TEST_F(ServerTest, Put) {
  7003. auto res = cli_.Put("/put", "PUT", "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("PUT", res->body);
  7007. }
  7008. TEST_F(ServerTest, PutWithContentProvider) {
  7009. auto res = cli_.Put(
  7010. "/put", 3,
  7011. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7012. sink.os << "PUT";
  7013. return true;
  7014. },
  7015. "text/plain");
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::OK_200, res->status);
  7018. EXPECT_EQ("PUT", res->body);
  7019. }
  7020. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7021. auto res = cli_.Post(
  7022. "/post", 42,
  7023. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7024. return false;
  7025. },
  7026. "text/plain");
  7027. ASSERT_TRUE(!res);
  7028. EXPECT_EQ(Error::Canceled, res.error());
  7029. }
  7030. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7031. auto res = cli_.Put(
  7032. "/put",
  7033. [](size_t /*offset*/, DataSink &sink) {
  7034. sink.os << "PUT";
  7035. sink.done();
  7036. return true;
  7037. },
  7038. "text/plain");
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. EXPECT_EQ("PUT", res->body);
  7042. }
  7043. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7044. auto res = cli_.Post(
  7045. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7046. "text/plain");
  7047. ASSERT_TRUE(!res);
  7048. EXPECT_EQ(Error::Canceled, res.error());
  7049. }
  7050. TEST_F(ServerTest, PostLoopBack) {
  7051. std::string body;
  7052. auto res = cli_.Post(
  7053. "/post-loopback", 9,
  7054. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7055. EXPECT_EQ(9u, length);
  7056. sink.write("123", 3);
  7057. sink.write("456", 3);
  7058. sink.write("789", 3);
  7059. return true;
  7060. },
  7061. "text/plain",
  7062. [&body](const char *data, size_t data_length) {
  7063. body.append(data, data_length);
  7064. return true;
  7065. });
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. EXPECT_EQ("123456789", body);
  7069. }
  7070. TEST_F(ServerTest, PutLoopBack) {
  7071. std::string body;
  7072. auto res = cli_.Put(
  7073. "/put-loopback", 9,
  7074. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7075. EXPECT_EQ(9u, length);
  7076. sink.write("123", 3);
  7077. sink.write("456", 3);
  7078. sink.write("789", 3);
  7079. return true;
  7080. },
  7081. "text/plain",
  7082. [&body](const char *data, size_t data_length) {
  7083. body.append(data, data_length);
  7084. return true;
  7085. });
  7086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7087. EXPECT_EQ(StatusCode::OK_200, res->status);
  7088. EXPECT_EQ("123456789", body);
  7089. }
  7090. TEST_F(ServerTest, PatchLoopBack) {
  7091. std::string body;
  7092. auto res = cli_.Patch(
  7093. "/patch-loopback", 9,
  7094. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7095. EXPECT_EQ(9u, length);
  7096. sink.write("123", 3);
  7097. sink.write("456", 3);
  7098. sink.write("789", 3);
  7099. return true;
  7100. },
  7101. "text/plain",
  7102. [&body](const char *data, size_t data_length) {
  7103. body.append(data, data_length);
  7104. return true;
  7105. });
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. EXPECT_EQ(StatusCode::OK_200, res->status);
  7108. EXPECT_EQ("123456789", body);
  7109. }
  7110. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7111. std::string body;
  7112. auto res = cli_.Post(
  7113. "/post-loopback",
  7114. [](size_t /*offset*/, DataSink &sink) {
  7115. sink.write("123", 3);
  7116. sink.write("456", 3);
  7117. sink.write("789", 3);
  7118. sink.done();
  7119. return true;
  7120. },
  7121. "text/plain",
  7122. [&body](const char *data, size_t data_length) {
  7123. body.append(data, data_length);
  7124. return true;
  7125. });
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. EXPECT_EQ("123456789", body);
  7129. }
  7130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7131. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7132. cli_.set_compress(true);
  7133. auto res = cli_.Put(
  7134. "/put", 3,
  7135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7136. sink.os << "PUT";
  7137. return true;
  7138. },
  7139. "text/plain");
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::OK_200, res->status);
  7142. EXPECT_EQ("PUT", res->body);
  7143. }
  7144. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7145. cli_.set_compress(true);
  7146. auto res = cli_.Post(
  7147. "/post", 42,
  7148. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7149. return false;
  7150. },
  7151. "text/plain");
  7152. ASSERT_TRUE(!res);
  7153. EXPECT_EQ(Error::Canceled, res.error());
  7154. }
  7155. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7156. cli_.set_compress(true);
  7157. auto res = cli_.Put(
  7158. "/put",
  7159. [](size_t /*offset*/, DataSink &sink) {
  7160. sink.os << "PUT";
  7161. sink.done();
  7162. return true;
  7163. },
  7164. "text/plain");
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::OK_200, res->status);
  7167. EXPECT_EQ("PUT", res->body);
  7168. }
  7169. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7170. cli_.set_compress(true);
  7171. auto res = cli_.Post(
  7172. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7173. "text/plain");
  7174. ASSERT_TRUE(!res);
  7175. EXPECT_EQ(Error::Canceled, res.error());
  7176. }
  7177. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7178. cli_.set_compress(true);
  7179. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7181. EXPECT_EQ(StatusCode::OK_200, res->status);
  7182. EXPECT_EQ(LARGE_DATA, res->body);
  7183. }
  7184. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7185. #ifdef CPPHTTPLIB_SSL_ENABLED
  7186. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7187. Client cli(s.c_str());
  7188. cli.enable_server_certificate_verification(false);
  7189. #else
  7190. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7191. Client cli(s.c_str());
  7192. #endif
  7193. cli.set_compress(true);
  7194. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ(LARGE_DATA, res->body);
  7198. // The compressed size should be less than a 10th of the original. May vary
  7199. // depending on the zlib library.
  7200. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7201. static_cast<uint64_t>(10 * 1024 * 1024));
  7202. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7203. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7204. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7205. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7206. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7207. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7208. #endif
  7209. }
  7210. TEST_F(ServerTest, PutContentWithDeflate) {
  7211. cli_.set_compress(false);
  7212. Headers headers;
  7213. headers.emplace("Content-Encoding", "deflate");
  7214. // PUT in deflate format:
  7215. auto res = cli_.Put("/put", headers,
  7216. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. EXPECT_EQ("PUT", res->body);
  7220. }
  7221. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7222. Headers headers;
  7223. headers.emplace("Accept-Encoding", "gzip, deflate");
  7224. auto res = cli_.Get("/streamed-chunked", headers);
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::OK_200, res->status);
  7227. EXPECT_EQ(std::string("123456789"), res->body);
  7228. }
  7229. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7230. Headers headers;
  7231. headers.emplace("Accept-Encoding", "gzip, deflate");
  7232. auto res = cli_.Get("/streamed-chunked2", headers);
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::OK_200, res->status);
  7235. EXPECT_EQ(std::string("123456789"), res->body);
  7236. }
  7237. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7238. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. }
  7242. TEST(GzipDecompressor, ChunkedDecompression) {
  7243. std::string data;
  7244. for (size_t i = 0; i < 32 * 1024; ++i) {
  7245. data.push_back(static_cast<char>('a' + i % 26));
  7246. }
  7247. std::string compressed_data;
  7248. {
  7249. httplib::detail::gzip_compressor compressor;
  7250. bool result = compressor.compress(
  7251. data.data(), data.size(),
  7252. /*last=*/true,
  7253. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7254. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7255. compressed_data_size);
  7256. return true;
  7257. });
  7258. ASSERT_TRUE(result);
  7259. }
  7260. std::string decompressed_data;
  7261. {
  7262. httplib::detail::gzip_decompressor decompressor;
  7263. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7264. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7265. size_t chunk_size = 130;
  7266. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7267. chunk_begin += chunk_size) {
  7268. size_t current_chunk_size =
  7269. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7270. bool result = decompressor.decompress(
  7271. compressed_data.data() + chunk_begin, current_chunk_size,
  7272. [&](const char *decompressed_data_chunk,
  7273. size_t decompressed_data_chunk_size) {
  7274. decompressed_data.insert(decompressed_data.size(),
  7275. decompressed_data_chunk,
  7276. decompressed_data_chunk_size);
  7277. return true;
  7278. });
  7279. ASSERT_TRUE(result);
  7280. }
  7281. }
  7282. ASSERT_EQ(data, decompressed_data);
  7283. }
  7284. TEST(GzipDecompressor, DeflateDecompression) {
  7285. std::string original_text = "Raw deflate without gzip";
  7286. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7287. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7288. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7289. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7290. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7291. std::string decompressed_data;
  7292. {
  7293. httplib::detail::gzip_decompressor decompressor;
  7294. bool result = decompressor.decompress(
  7295. compressed_data.data(), compressed_data.size(),
  7296. [&](const char *decompressed_data_chunk,
  7297. size_t decompressed_data_chunk_size) {
  7298. decompressed_data.insert(decompressed_data.size(),
  7299. decompressed_data_chunk,
  7300. decompressed_data_chunk_size);
  7301. return true;
  7302. });
  7303. ASSERT_TRUE(result);
  7304. }
  7305. ASSERT_EQ(original_text, decompressed_data);
  7306. }
  7307. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7308. std::string original_text = "Raw deflate without gzip";
  7309. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7310. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7311. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7312. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7313. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7314. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7315. std::string decompressed_data;
  7316. {
  7317. httplib::detail::gzip_decompressor decompressor;
  7318. bool result = decompressor.decompress(
  7319. compressed_data.data(), compressed_data.size(),
  7320. [&](const char *decompressed_data_chunk,
  7321. size_t decompressed_data_chunk_size) {
  7322. decompressed_data.insert(decompressed_data.size(),
  7323. decompressed_data_chunk,
  7324. decompressed_data_chunk_size);
  7325. return true;
  7326. });
  7327. ASSERT_TRUE(result);
  7328. }
  7329. ASSERT_EQ(original_text, decompressed_data);
  7330. }
  7331. #endif
  7332. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7333. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7334. Headers headers;
  7335. headers.emplace("Accept-Encoding", "br");
  7336. auto res = cli_.Get("/streamed-chunked", headers);
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. EXPECT_EQ(std::string("123456789"), res->body);
  7340. }
  7341. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7342. Headers headers;
  7343. headers.emplace("Accept-Encoding", "br");
  7344. auto res = cli_.Get("/streamed-chunked2", headers);
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. EXPECT_EQ(std::string("123456789"), res->body);
  7348. }
  7349. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7350. cli_.set_compress(true);
  7351. auto res = cli_.Put(
  7352. "/put", 3,
  7353. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7354. sink.os << "PUT";
  7355. return true;
  7356. },
  7357. "text/plain");
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. EXPECT_EQ("PUT", res->body);
  7361. }
  7362. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7363. cli_.set_compress(true);
  7364. auto res = cli_.Put(
  7365. "/put",
  7366. [](size_t /*offset*/, DataSink &sink) {
  7367. sink.os << "PUT";
  7368. sink.done();
  7369. return true;
  7370. },
  7371. "text/plain");
  7372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7373. EXPECT_EQ(StatusCode::OK_200, res->status);
  7374. EXPECT_EQ("PUT", res->body);
  7375. }
  7376. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7377. cli_.set_compress(true);
  7378. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::OK_200, res->status);
  7381. EXPECT_EQ(LARGE_DATA, res->body);
  7382. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7383. }
  7384. #endif
  7385. TEST_F(ServerTest, Patch) {
  7386. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7388. EXPECT_EQ(StatusCode::OK_200, res->status);
  7389. EXPECT_EQ("PATCH", res->body);
  7390. }
  7391. TEST_F(ServerTest, Delete) {
  7392. auto res = cli_.Delete("/delete");
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::OK_200, res->status);
  7395. EXPECT_EQ("DELETE", res->body);
  7396. }
  7397. TEST_F(ServerTest, DeleteContentReceiver) {
  7398. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_EQ(StatusCode::OK_200, res->status);
  7401. EXPECT_EQ("content", res->body);
  7402. }
  7403. TEST_F(ServerTest, Options) {
  7404. auto res = cli_.Options("*");
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ(StatusCode::OK_200, res->status);
  7407. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7408. EXPECT_TRUE(res->body.empty());
  7409. }
  7410. TEST_F(ServerTest, URL) {
  7411. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7413. EXPECT_EQ(StatusCode::OK_200, res->status);
  7414. }
  7415. TEST_F(ServerTest, ArrayParam) {
  7416. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. }
  7420. TEST_F(ServerTest, ArrayParamValues) {
  7421. auto res =
  7422. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7424. EXPECT_EQ(StatusCode::OK_200, res->status);
  7425. }
  7426. TEST_F(ServerTest, NoMultipleHeaders) {
  7427. Headers headers = {{"Content-Length", "5"}};
  7428. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7429. "text/plain");
  7430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7431. EXPECT_EQ(StatusCode::OK_200, res->status);
  7432. }
  7433. TEST_F(ServerTest, PostContentReceiver) {
  7434. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7436. ASSERT_EQ(StatusCode::OK_200, res->status);
  7437. ASSERT_EQ("content", res->body);
  7438. }
  7439. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7440. UploadFormDataItems items = {
  7441. {"text1", "text default", "", ""},
  7442. {"text2", "aωb", "", ""},
  7443. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7444. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7445. {"file3", "", "", "application/octet-stream"},
  7446. };
  7447. auto res = cli_.Post("/content_receiver", items);
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. }
  7451. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7452. UploadFormDataItems items = {
  7453. {"text1", "text default", "", ""},
  7454. {"text2", "aωb", "", ""},
  7455. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7456. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7457. {"file3", "", "", "application/octet-stream"},
  7458. };
  7459. auto boundary = std::string("+++++");
  7460. std::string body;
  7461. for (const auto &item : items) {
  7462. body += "--" + boundary + "\r\n";
  7463. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7464. if (!item.filename.empty()) {
  7465. body += "; filename=\"" + item.filename + "\"";
  7466. }
  7467. body += "\r\n";
  7468. if (!item.content_type.empty()) {
  7469. body += "Content-Type: " + item.content_type + "\r\n";
  7470. }
  7471. body += "\r\n";
  7472. body += item.content + "\r\n";
  7473. }
  7474. body += "--" + boundary + "--\r\n";
  7475. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7476. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. }
  7480. TEST(MultipartFormDataTest, FieldEscaping) {
  7481. Server svr;
  7482. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7483. const ContentReader &content_reader) {
  7484. ASSERT_TRUE(req.is_multipart_form_data());
  7485. std::vector<FormData> received;
  7486. content_reader(
  7487. [&](const FormData &file) {
  7488. received.push_back(file);
  7489. return true;
  7490. },
  7491. [&](const char *data, size_t data_length) {
  7492. received.back().content.append(data, data_length);
  7493. return true;
  7494. });
  7495. // '"', CR and LF in names and filenames are escaped following the
  7496. // WHATWG HTML standard, so each part still parses as a single part
  7497. // with no injected headers. Content types get CR/LF escaped too,
  7498. // while '"' (legal there, e.g. quoted charset) is preserved.
  7499. ASSERT_EQ(4U, received.size());
  7500. EXPECT_EQ("na%22me", received[0].name);
  7501. EXPECT_EQ("quoted name", received[0].content);
  7502. EXPECT_EQ("file", received[1].name);
  7503. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7504. received[1].filename);
  7505. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7506. EXPECT_EQ("injected", received[1].content);
  7507. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7508. EXPECT_EQ("my%22file.txt", received[2].filename);
  7509. EXPECT_EQ("cr lf name", received[2].content);
  7510. EXPECT_EQ("typed", received[3].name);
  7511. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7512. received[3].content_type);
  7513. EXPECT_EQ("typed content", received[3].content);
  7514. });
  7515. auto port = svr.bind_to_any_port("localhost");
  7516. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7517. auto se = detail::scope_exit([&] {
  7518. svr.stop();
  7519. t.join();
  7520. ASSERT_FALSE(svr.is_running());
  7521. });
  7522. svr.wait_until_ready();
  7523. Client cli("localhost", port);
  7524. UploadFormDataItems items = {
  7525. {"na\"me", "quoted name", "", ""},
  7526. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7527. "application/octet-stream"},
  7528. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7529. {"typed", "typed content", "",
  7530. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7531. };
  7532. auto res = cli.Post("/post", items);
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. }
  7536. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7537. const UploadFormDataItems items = {
  7538. {"name1", "Content 1", "", ""},
  7539. {"name2", "Content 2", "file2.txt", "text/plain"},
  7540. };
  7541. Server svr;
  7542. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7543. const ContentReader &content_reader) {
  7544. ASSERT_TRUE(req.is_multipart_form_data());
  7545. std::vector<FormData> received;
  7546. content_reader(
  7547. [&](const FormData &file) {
  7548. received.push_back(file);
  7549. return true;
  7550. },
  7551. [&](const char *data, size_t data_length) {
  7552. received.back().content.append(data, data_length);
  7553. return true;
  7554. });
  7555. ASSERT_EQ(2U, received.size());
  7556. EXPECT_EQ("name1", received[0].name);
  7557. EXPECT_EQ("Content 1", received[0].content);
  7558. EXPECT_EQ("name2", received[1].name);
  7559. EXPECT_EQ("Content 2", received[1].content);
  7560. EXPECT_EQ("file2.txt", received[1].filename);
  7561. EXPECT_EQ("text/plain", received[1].content_type);
  7562. });
  7563. auto port = svr.bind_to_any_port("localhost");
  7564. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7565. auto se = detail::scope_exit([&] {
  7566. svr.stop();
  7567. t.join();
  7568. ASSERT_FALSE(svr.is_running());
  7569. });
  7570. svr.wait_until_ready();
  7571. Client cli("localhost", port);
  7572. // Whole-body serialization with a generated boundary
  7573. {
  7574. MultipartFormDataWriter writer;
  7575. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7576. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7577. writer.content_type());
  7578. auto body = writer.serialize(items);
  7579. EXPECT_EQ(body.size(), writer.content_length(items));
  7580. auto res = cli.Post("/post", body, writer.content_type());
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::OK_200, res->status);
  7583. }
  7584. // Per-part framing with a custom boundary via a content provider
  7585. {
  7586. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7587. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7588. MultipartFormDataWriter writer("custom-boundary_123");
  7589. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7590. std::string body;
  7591. for (const auto &item : items) {
  7592. body += writer.item_begin(item);
  7593. body += item.content;
  7594. body += MultipartFormDataWriter::item_end();
  7595. }
  7596. body += writer.finish();
  7597. EXPECT_EQ(body.size(), writer.content_length(items));
  7598. auto res = cli.Post(
  7599. "/post", body.size(),
  7600. [&](size_t offset, size_t length, DataSink &sink) {
  7601. sink.write(body.data() + offset, length);
  7602. return true;
  7603. },
  7604. writer.content_type());
  7605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7606. EXPECT_EQ(StatusCode::OK_200, res->status);
  7607. }
  7608. }
  7609. TEST_F(ServerTest, PostContentReceiverGzip) {
  7610. cli_.set_compress(true);
  7611. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. ASSERT_EQ(StatusCode::OK_200, res->status);
  7614. ASSERT_EQ("content", res->body);
  7615. }
  7616. TEST_F(ServerTest, PutContentReceiver) {
  7617. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. ASSERT_EQ(StatusCode::OK_200, res->status);
  7620. ASSERT_EQ("content", res->body);
  7621. }
  7622. TEST_F(ServerTest, PatchContentReceiver) {
  7623. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7625. ASSERT_EQ(StatusCode::OK_200, res->status);
  7626. ASSERT_EQ("content", res->body);
  7627. }
  7628. template <typename ClientType>
  7629. void TestWithHeadersAndContentReceiver(
  7630. ClientType &cli,
  7631. std::function<Result(ClientType &, const std::string &, const Headers &,
  7632. const std::string &, const std::string &,
  7633. ContentReceiver, DownloadProgress)>
  7634. request_func) {
  7635. Headers headers;
  7636. headers.emplace("X-Custom-Header", "test-value");
  7637. std::string received_body;
  7638. auto res = request_func(
  7639. cli, "/content_receiver", headers, "content", "application/json",
  7640. [&](const char *data, size_t data_length) {
  7641. received_body.append(data, data_length);
  7642. return true;
  7643. },
  7644. nullptr);
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::OK_200, res->status);
  7647. EXPECT_EQ("content", received_body);
  7648. }
  7649. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7650. #ifdef CPPHTTPLIB_SSL_ENABLED
  7651. using ClientT = SSLClient;
  7652. #else
  7653. using ClientT = Client;
  7654. #endif
  7655. TestWithHeadersAndContentReceiver<ClientT>(
  7656. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7657. const std::string &body, const std::string &content_type,
  7658. ContentReceiver receiver, DownloadProgress progress) {
  7659. return cli.Post(path, headers, body, content_type, receiver, progress);
  7660. });
  7661. }
  7662. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7663. #ifdef CPPHTTPLIB_SSL_ENABLED
  7664. using ClientT = SSLClient;
  7665. #else
  7666. using ClientT = Client;
  7667. #endif
  7668. TestWithHeadersAndContentReceiver<ClientT>(
  7669. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7670. const std::string &body, const std::string &content_type,
  7671. ContentReceiver receiver, DownloadProgress progress) {
  7672. return cli.Put(path, headers, body, content_type, receiver, progress);
  7673. });
  7674. }
  7675. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7676. #ifdef CPPHTTPLIB_SSL_ENABLED
  7677. using ClientT = SSLClient;
  7678. #else
  7679. using ClientT = Client;
  7680. #endif
  7681. TestWithHeadersAndContentReceiver<ClientT>(
  7682. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7683. const std::string &body, const std::string &content_type,
  7684. ContentReceiver receiver, DownloadProgress progress) {
  7685. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7686. });
  7687. }
  7688. template <typename ClientType>
  7689. void TestWithHeadersAndContentReceiverWithProgress(
  7690. ClientType &cli,
  7691. std::function<Result(ClientType &, const std::string &, const Headers &,
  7692. const std::string &, const std::string &,
  7693. ContentReceiver, DownloadProgress)>
  7694. request_func) {
  7695. Headers headers;
  7696. headers.emplace("X-Test-Header", "progress-test");
  7697. std::string received_body;
  7698. auto progress_called = false;
  7699. auto res = request_func(
  7700. cli, "/content_receiver", headers, "content", "text/plain",
  7701. [&](const char *data, size_t data_length) {
  7702. received_body.append(data, data_length);
  7703. return true;
  7704. },
  7705. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7706. progress_called = true;
  7707. return true;
  7708. });
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::OK_200, res->status);
  7711. EXPECT_EQ("content", received_body);
  7712. EXPECT_TRUE(progress_called);
  7713. }
  7714. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7715. #ifdef CPPHTTPLIB_SSL_ENABLED
  7716. using ClientT = SSLClient;
  7717. #else
  7718. using ClientT = Client;
  7719. #endif
  7720. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7721. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7722. const std::string &body, const std::string &content_type,
  7723. ContentReceiver receiver, DownloadProgress progress) {
  7724. return cli.Post(path, headers, body, content_type, receiver, progress);
  7725. });
  7726. }
  7727. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7728. #ifdef CPPHTTPLIB_SSL_ENABLED
  7729. using ClientT = SSLClient;
  7730. #else
  7731. using ClientT = Client;
  7732. #endif
  7733. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7734. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7735. const std::string &body, const std::string &content_type,
  7736. ContentReceiver receiver, DownloadProgress progress) {
  7737. return cli.Put(path, headers, body, content_type, receiver, progress);
  7738. });
  7739. }
  7740. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7741. #ifdef CPPHTTPLIB_SSL_ENABLED
  7742. using ClientT = SSLClient;
  7743. #else
  7744. using ClientT = Client;
  7745. #endif
  7746. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7747. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7748. const std::string &body, const std::string &content_type,
  7749. ContentReceiver receiver, DownloadProgress progress) {
  7750. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7751. });
  7752. }
  7753. template <typename ClientType>
  7754. void TestWithHeadersAndContentReceiverError(
  7755. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7756. const Headers &, const std::string &,
  7757. const std::string &, ContentReceiver)>
  7758. request_func) {
  7759. Headers headers;
  7760. headers.emplace("X-Error-Test", "true");
  7761. std::string received_body;
  7762. auto receiver_failed = false;
  7763. auto res =
  7764. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7765. [&](const char *data, size_t data_length) {
  7766. received_body.append(data, data_length);
  7767. receiver_failed = true;
  7768. return false;
  7769. });
  7770. ASSERT_FALSE(res);
  7771. EXPECT_TRUE(receiver_failed);
  7772. }
  7773. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7774. #ifdef CPPHTTPLIB_SSL_ENABLED
  7775. using ClientT = SSLClient;
  7776. #else
  7777. using ClientT = Client;
  7778. #endif
  7779. TestWithHeadersAndContentReceiverError<ClientT>(
  7780. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7781. const std::string &body, const std::string &content_type,
  7782. ContentReceiver receiver) {
  7783. return cli.Post(path, headers, body, content_type, receiver);
  7784. });
  7785. }
  7786. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7787. #ifdef CPPHTTPLIB_SSL_ENABLED
  7788. using ClientT = SSLClient;
  7789. #else
  7790. using ClientT = Client;
  7791. #endif
  7792. TestWithHeadersAndContentReceiverError<ClientT>(
  7793. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7794. const std::string &body, const std::string &content_type,
  7795. ContentReceiver receiver) {
  7796. return cli.Put(path, headers, body, content_type, receiver);
  7797. });
  7798. }
  7799. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7800. #ifdef CPPHTTPLIB_SSL_ENABLED
  7801. using ClientT = SSLClient;
  7802. #else
  7803. using ClientT = Client;
  7804. #endif
  7805. TestWithHeadersAndContentReceiverError<ClientT>(
  7806. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7807. const std::string &body, const std::string &content_type,
  7808. ContentReceiver receiver) {
  7809. return cli.Patch(path, headers, body, content_type, receiver);
  7810. });
  7811. }
  7812. TEST_F(ServerTest, PostQueryStringAndBody) {
  7813. auto res =
  7814. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. ASSERT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST_F(ServerTest, HTTP2Magic) {
  7819. Request req;
  7820. req.method = "PRI";
  7821. req.path = "*";
  7822. req.body = "SM";
  7823. auto res = std::make_shared<Response>();
  7824. auto error = Error::Success;
  7825. auto ret = cli_.send(req, *res, error);
  7826. ASSERT_TRUE(ret);
  7827. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7828. }
  7829. TEST_F(ServerTest, KeepAlive) {
  7830. auto res = cli_.Get("/hi");
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ(StatusCode::OK_200, res->status);
  7833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7834. EXPECT_EQ("Hello World!", res->body);
  7835. res = cli_.Get("/hi");
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7839. EXPECT_EQ("Hello World!", res->body);
  7840. res = cli_.Get("/hi");
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7844. EXPECT_EQ("Hello World!", res->body);
  7845. res = cli_.Get("/not-exist");
  7846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7847. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7848. res = cli_.Post("/empty", "", "text/plain");
  7849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7852. EXPECT_EQ("empty", res->body);
  7853. EXPECT_EQ("close", res->get_header_value("Connection"));
  7854. res = cli_.Post(
  7855. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7856. "text/plain");
  7857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7858. EXPECT_EQ(StatusCode::OK_200, res->status);
  7859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7860. EXPECT_EQ("empty", res->body);
  7861. cli_.set_keep_alive(false);
  7862. res = cli_.Get("/last-request");
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ("close", res->get_header_value("Connection"));
  7866. }
  7867. TEST_F(ServerTest, TooManyRedirect) {
  7868. cli_.set_follow_location(true);
  7869. auto res = cli_.Get("/redirect/0");
  7870. ASSERT_TRUE(!res);
  7871. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7872. }
  7873. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7874. Request req;
  7875. req.method = "FOOBAR";
  7876. req.path = "/hi";
  7877. cli_.set_keep_alive(true);
  7878. auto res = cli_.send(req);
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7881. EXPECT_EQ("close", res->get_header_value("Connection"));
  7882. EXPECT_FALSE(cli_.is_socket_open());
  7883. }
  7884. TEST_F(ServerTest, CustomRouteReadsBody) {
  7885. const std::string xml =
  7886. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7887. Request req;
  7888. req.method = "PROPFIND";
  7889. req.path = "/dav/dir";
  7890. req.set_header("Depth", "1");
  7891. req.body = xml;
  7892. auto res = cli_.send(req);
  7893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7894. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7895. EXPECT_EQ(xml, res->body);
  7896. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7897. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7898. }
  7899. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7900. Request req;
  7901. req.method = "PROPFIND";
  7902. req.path = "/dav/42";
  7903. auto res = cli_.send(req);
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7906. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7907. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7908. }
  7909. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7910. Request req;
  7911. req.method = "PROPFIND";
  7912. req.path = "/dav-re/123";
  7913. auto res = cli_.send(req);
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7916. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7917. }
  7918. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7919. Request req;
  7920. req.method = "MKCOL";
  7921. req.path = "/dav-mkcol";
  7922. auto res = cli_.send(req);
  7923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7924. EXPECT_EQ(StatusCode::Created_201, res->status);
  7925. }
  7926. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7927. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7928. Request req;
  7929. req.method = "REPORT";
  7930. req.path = "/dav-report";
  7931. req.body = xml;
  7932. auto res = cli_.send(req);
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7935. EXPECT_EQ(xml, res->body);
  7936. }
  7937. // A content reader route must fire even when the request carries no body,
  7938. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7939. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7940. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7941. Request req;
  7942. req.method = "REPORT";
  7943. req.path = "/dav-report";
  7944. auto res = cli_.send(req);
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7947. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7948. }
  7949. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7950. Request req;
  7951. req.method = "PROPFIND";
  7952. req.path = "/not-dav";
  7953. auto res = cli_.send(req);
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7956. }
  7957. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7958. Request req;
  7959. req.method = "UNLOCK";
  7960. req.path = "/dav/dir";
  7961. cli_.set_keep_alive(true);
  7962. auto res = cli_.send(req);
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7965. EXPECT_EQ("close", res->get_header_value("Connection"));
  7966. EXPECT_FALSE(cli_.is_socket_open());
  7967. }
  7968. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7969. // The mount point serves this path, but only for GET and HEAD.
  7970. auto get_res = cli_.Get("/dir/index.html");
  7971. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7972. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7973. Request req;
  7974. req.method = "PROPFIND";
  7975. req.path = "/dir/index.html";
  7976. auto res = cli_.send(req);
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7979. }
  7980. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7981. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7982. cli_.set_keep_alive(true);
  7983. for (auto i = 0; i < 2; i++) {
  7984. Request req;
  7985. req.method = "PROPFIND";
  7986. req.path = "/dav/dir";
  7987. req.body = xml;
  7988. auto res = cli_.send(req);
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7991. EXPECT_EQ(xml, res->body);
  7992. EXPECT_TRUE(cli_.is_socket_open());
  7993. }
  7994. // A built-in method must still be served on the same connection.
  7995. cli_.set_keep_alive(false);
  7996. auto res = cli_.Get("/hi");
  7997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. EXPECT_EQ("close", res->get_header_value("Connection"));
  8000. }
  8001. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8002. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8003. Request req;
  8004. req.method = "PROPFIND";
  8005. req.path = "/dav/dir";
  8006. req.set_header("Expect", "100-continue");
  8007. req.body = xml;
  8008. auto res = cli_.send(req);
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8011. EXPECT_EQ(xml, res->body);
  8012. }
  8013. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8014. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8015. TEST_F(ServerTest, Gzip) {
  8016. Headers headers;
  8017. headers.emplace("Accept-Encoding", "gzip, deflate");
  8018. auto res = cli_.Get("/compress", headers);
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8022. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8024. "7890123456789012345678901234567890",
  8025. res->body);
  8026. EXPECT_EQ(StatusCode::OK_200, res->status);
  8027. }
  8028. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8029. Headers headers;
  8030. headers.emplace("Accept-Encoding", "gzip, deflate");
  8031. auto res = cli_.Get("/compress-with-charset", headers);
  8032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8033. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8034. EXPECT_EQ("application/json; charset=utf-8",
  8035. res->get_header_value("Content-Type"));
  8036. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8037. "7890123456789012345678901234567890",
  8038. res->body);
  8039. EXPECT_EQ(StatusCode::OK_200, res->status);
  8040. }
  8041. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8042. Headers headers;
  8043. headers.emplace("Accept-Encoding", "");
  8044. auto res = cli_.Get("/compress", headers);
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8048. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8049. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8050. "7890123456789012345678901234567890",
  8051. res->body);
  8052. EXPECT_EQ(StatusCode::OK_200, res->status);
  8053. }
  8054. TEST_F(ServerTest, GzipWithContentReceiver) {
  8055. Headers headers;
  8056. headers.emplace("Accept-Encoding", "gzip, deflate");
  8057. std::string body;
  8058. auto res = cli_.Get("/compress", headers,
  8059. [&](const char *data, uint64_t data_length) {
  8060. EXPECT_EQ(100U, data_length);
  8061. body.append(data, data_length);
  8062. return true;
  8063. });
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8067. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8068. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8069. "7890123456789012345678901234567890",
  8070. body);
  8071. EXPECT_EQ(StatusCode::OK_200, res->status);
  8072. }
  8073. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8074. Headers headers;
  8075. headers.emplace("Accept-Encoding", "gzip, deflate");
  8076. cli_.set_decompress(false);
  8077. auto res = cli_.Get("/compress", headers);
  8078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8079. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8080. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8081. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8082. EXPECT_EQ(33U, res->body.size());
  8083. EXPECT_EQ(StatusCode::OK_200, res->status);
  8084. }
  8085. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "");
  8088. std::string body;
  8089. auto res = cli_.Get("/compress", headers,
  8090. [&](const char *data, uint64_t data_length) {
  8091. EXPECT_EQ(100U, data_length);
  8092. body.append(data, data_length);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8098. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8100. "7890123456789012345678901234567890",
  8101. body);
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. }
  8104. TEST_F(ServerTest, NoGzip) {
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "gzip, deflate");
  8107. auto res = cli_.Get("/nocompress", headers);
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8110. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8111. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8112. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8113. "7890123456789012345678901234567890",
  8114. res->body);
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. }
  8117. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8118. Headers headers;
  8119. headers.emplace("Accept-Encoding", "gzip, deflate");
  8120. std::string body;
  8121. auto res = cli_.Get("/nocompress", headers,
  8122. [&](const char *data, uint64_t data_length) {
  8123. EXPECT_EQ(100U, data_length);
  8124. body.append(data, data_length);
  8125. return true;
  8126. });
  8127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8128. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8129. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8130. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8131. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8132. "7890123456789012345678901234567890",
  8133. body);
  8134. EXPECT_EQ(StatusCode::OK_200, res->status);
  8135. }
  8136. TEST_F(ServerTest, MultipartFormDataGzip) {
  8137. UploadFormDataItems items = {
  8138. {"key1", "test", "", ""},
  8139. {"key2", "--abcdefg123", "", ""},
  8140. };
  8141. cli_.set_compress(true);
  8142. auto res = cli_.Post("/compress-multipart", items);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. }
  8146. #endif
  8147. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8148. // Static file compression is opt-in, so these run their own server rather than
  8149. // flipping it on for the shared ServerTest fixture, which would silently
  8150. // rewrite what every other static file test is asserting.
  8151. class StaticFileCompressionTest : public ::testing::Test {
  8152. protected:
  8153. void TearDown() override {
  8154. if (t_.joinable()) {
  8155. svr_.stop();
  8156. t_.join();
  8157. }
  8158. }
  8159. int start(const std::function<void(Server &)> &configure = nullptr) {
  8160. // Serves the same tree as a directory of build-time compressed assets
  8161. // would be served: the mount point names the coding the files are already
  8162. // stored in. Registered before "/" so it is the one that matches.
  8163. svr_.set_mount_point("/pre-encoded", "./www",
  8164. {{"Content-Encoding", "gzip"}});
  8165. svr_.set_mount_point("/", "./www");
  8166. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8167. res.set_file_content("./www/dir/index.html", "text/html");
  8168. });
  8169. svr_.Get("/pre-encoded-file-content",
  8170. [](const Request & /*req*/, Response &res) {
  8171. res.set_header("Content-Encoding", "gzip");
  8172. res.set_file_content("./www/dir/index.html", "text/html");
  8173. });
  8174. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8175. res.set_content_provider(
  8176. 6, "text/plain",
  8177. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8178. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8179. return true;
  8180. });
  8181. });
  8182. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8183. res.set_content_provider(
  8184. 1000, "text/plain",
  8185. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8186. if (offset < 100) {
  8187. std::string data(100, 'A');
  8188. sink.write(data.data(), data.size());
  8189. return true;
  8190. }
  8191. std::this_thread::sleep_for(std::chrono::seconds(2));
  8192. std::string data(900, 'B');
  8193. sink.write(data.data(), data.size());
  8194. return true;
  8195. });
  8196. });
  8197. if (configure) { configure(svr_); }
  8198. auto port = svr_.bind_to_any_port(HOST);
  8199. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8200. svr_.wait_until_ready();
  8201. return port;
  8202. }
  8203. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8204. // Every file under ./www except 1MB.txt is smaller than the default
  8205. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8206. // it out of the way.
  8207. static void enable_without_floor(Server &svr) {
  8208. svr.set_static_file_compression(true);
  8209. svr.set_static_file_compression_min_length(0);
  8210. }
  8211. Server svr_;
  8212. std::thread t_;
  8213. };
  8214. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8215. auto port = start();
  8216. Client cli(HOST, port);
  8217. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. EXPECT_EQ(StatusCode::OK_200, res->status);
  8220. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8221. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8222. EXPECT_EQ(1048576U, res->body.size());
  8223. }
  8224. TEST_F(StaticFileCompressionTest, MountPoint) {
  8225. auto port = start(enable);
  8226. Client cli(HOST, port);
  8227. cli.set_decompress(false);
  8228. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8230. EXPECT_EQ(StatusCode::OK_200, res->status);
  8231. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8232. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8233. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8234. // The response stays self-delimiting: a length, not a chunked body.
  8235. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8236. EXPECT_EQ(std::to_string(res->body.size()),
  8237. res->get_header_value("Content-Length"));
  8238. EXPECT_LT(res->body.size(), 1048576U);
  8239. EXPECT_FALSE(res->body.empty());
  8240. }
  8241. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8242. auto port = start(enable);
  8243. Client cli(HOST, port);
  8244. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8248. EXPECT_EQ(1048576U, res->body.size());
  8249. }
  8250. TEST_F(StaticFileCompressionTest, FileContent) {
  8251. auto port = start(enable_without_floor);
  8252. Client cli(HOST, port);
  8253. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. EXPECT_EQ(StatusCode::OK_200, res->status);
  8256. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8257. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8258. EXPECT_EQ(104U, res->body.size());
  8259. }
  8260. // A handler that serves an already-encoded file names the coding itself. The
  8261. // file-backed path decided its coding from Accept-Encoding and the content
  8262. // type alone, so it compressed the stored bytes a second time and appended a
  8263. // second Content-Encoding field line.
  8264. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8265. auto port = start(enable_without_floor);
  8266. Client cli(HOST, port);
  8267. cli.set_decompress(false);
  8268. auto res = cli.Get("/pre-encoded-file-content",
  8269. Headers{{"Accept-Encoding", "gzip"}});
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8273. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8274. // Vary belongs to a coding the server chose, and it chose none here.
  8275. EXPECT_FALSE(res->has_header("Vary"));
  8276. // The file travels exactly as it is stored on disk.
  8277. EXPECT_EQ(104U, res->body.size());
  8278. }
  8279. // The 1MB file clears the default floor, so this one runs the configuration a
  8280. // deployment would actually have.
  8281. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8282. auto port = start(enable);
  8283. Client cli(HOST, port);
  8284. cli.set_decompress(false);
  8285. auto res =
  8286. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ(StatusCode::OK_200, res->status);
  8289. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8290. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8291. EXPECT_FALSE(res->has_header("Vary"));
  8292. EXPECT_EQ(1048576U, res->body.size());
  8293. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8294. }
  8295. TEST_F(StaticFileCompressionTest, Head) {
  8296. auto port = start(enable);
  8297. Client cli(HOST, port);
  8298. cli.set_decompress(false);
  8299. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8300. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8301. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8303. EXPECT_EQ(StatusCode::OK_200, res->status);
  8304. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8305. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8306. // HEAD still reports the size a GET would return.
  8307. EXPECT_EQ(get->get_header_value("Content-Length"),
  8308. res->get_header_value("Content-Length"));
  8309. EXPECT_TRUE(res->body.empty());
  8310. }
  8311. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8312. auto port = start(enable);
  8313. Client cli(HOST, port);
  8314. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8315. {"Accept-Encoding", "gzip"}});
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8318. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8319. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8320. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8321. EXPECT_EQ("cd", res->body);
  8322. }
  8323. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8324. auto port = start(enable);
  8325. Client cli(HOST, port);
  8326. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::OK_200, res->status);
  8329. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8330. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8331. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8332. }
  8333. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8334. auto port = start(enable);
  8335. Client cli(HOST, port);
  8336. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8338. EXPECT_EQ(StatusCode::OK_200, res->status);
  8339. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8340. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8341. EXPECT_TRUE(res->body.empty());
  8342. }
  8343. TEST_F(StaticFileCompressionTest, MinLength) {
  8344. auto port = start(enable);
  8345. Client cli(HOST, port);
  8346. // 104 bytes, well under the default floor. Compressing it would add the
  8347. // gzip header and trailer to a body that already fits in one packet.
  8348. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_EQ(StatusCode::OK_200, res->status);
  8351. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8352. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8353. }
  8354. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8355. auto port = start([](Server &svr) {
  8356. svr.set_static_file_compression(true);
  8357. svr.set_static_file_compression_min_length(1);
  8358. });
  8359. Client cli(HOST, port);
  8360. cli.set_decompress(false);
  8361. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8363. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8364. // A 9-byte file comes back larger than it went in, because gzip's header and
  8365. // trailer outweigh anything deflate can save. That is the end of the range
  8366. // the floor exists to keep out.
  8367. EXPECT_GT(res->body.size(), 9U);
  8368. }
  8369. TEST_F(StaticFileCompressionTest, MaxLength) {
  8370. auto port = start([](Server &svr) {
  8371. svr.set_static_file_compression(true);
  8372. svr.set_static_file_compression_min_length(0);
  8373. svr.set_static_file_compression_max_length(1024);
  8374. });
  8375. Client cli(HOST, port);
  8376. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8377. // defines `small` as a macro on Windows.
  8378. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8379. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8380. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8381. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8382. // Under it: compressed.
  8383. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8384. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8385. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8386. }
  8387. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8388. auto port = start(enable_without_floor);
  8389. Client cli(HOST, port);
  8390. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8391. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8392. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8393. auto identity_etag = identity->get_header_value("ETag");
  8394. ASSERT_FALSE(identity_etag.empty());
  8395. auto gzipped =
  8396. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8397. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8398. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8399. auto gzip_etag = gzipped->get_header_value("ETag");
  8400. ASSERT_FALSE(gzip_etag.empty());
  8401. // Two representations, two validators.
  8402. EXPECT_NE(identity_etag, gzip_etag);
  8403. // Each one revalidates against the request that would produce it...
  8404. auto fresh =
  8405. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8406. {"If-None-Match", gzip_etag}});
  8407. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8408. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8409. auto fresh_identity =
  8410. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8411. {"If-None-Match", identity_etag}});
  8412. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8413. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8414. // ...and not against the other representation.
  8415. auto crossed =
  8416. cli.Get("/dir/index.html",
  8417. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8418. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8419. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8420. }
  8421. // The opt-in covers responses the server reads off disk itself. A caller's own
  8422. // known-length provider keeps its Content-Length and, more importantly, keeps
  8423. // delivering incrementally: routing it through a compressor would hold every
  8424. // write back until zlib's window filled.
  8425. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8426. auto port = start(enable);
  8427. Client cli(HOST, port);
  8428. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ(StatusCode::OK_200, res->status);
  8431. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8432. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ("aaabbb", res->body);
  8434. }
  8435. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8436. auto port = start(enable);
  8437. Client cli(HOST, port);
  8438. cli.set_read_timeout(1, 0);
  8439. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8440. Headers{{"Accept-Encoding", "gzip"}});
  8441. ASSERT_TRUE(handle.is_valid());
  8442. // The provider writes 100 bytes and then stalls for longer than the read
  8443. // timeout. Those first bytes have to arrive anyway: run the response through
  8444. // a compressor and zlib holds them until its window fills, so the read would
  8445. // come back empty instead.
  8446. char buf[256];
  8447. auto n = handle.read(buf, sizeof(buf));
  8448. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8449. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8450. }
  8451. #endif
  8452. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8453. TEST_F(ServerTest, Brotli) {
  8454. Headers headers;
  8455. headers.emplace("Accept-Encoding", "br");
  8456. auto res = cli_.Get("/compress", headers);
  8457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8458. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8460. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8461. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8462. "7890123456789012345678901234567890",
  8463. res->body);
  8464. EXPECT_EQ(StatusCode::OK_200, res->status);
  8465. }
  8466. #endif
  8467. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8468. TEST_F(ServerTest, Zstd) {
  8469. Headers headers;
  8470. headers.emplace("Accept-Encoding", "zstd");
  8471. auto res = cli_.Get("/compress", headers);
  8472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8473. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8475. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8476. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8477. "7890123456789012345678901234567890",
  8478. res->body);
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. }
  8481. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8482. Headers headers;
  8483. headers.emplace("Accept-Encoding", "");
  8484. auto res = cli_.Get("/compress", headers);
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8487. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8488. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8489. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8490. "7890123456789012345678901234567890",
  8491. res->body);
  8492. EXPECT_EQ(StatusCode::OK_200, res->status);
  8493. }
  8494. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8495. Headers headers;
  8496. headers.emplace("Accept-Encoding", "zstd");
  8497. std::string body;
  8498. auto res = cli_.Get("/compress", headers,
  8499. [&](const char *data, uint64_t data_length) {
  8500. EXPECT_EQ(100U, data_length);
  8501. body.append(data, data_length);
  8502. return true;
  8503. });
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8507. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8508. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8509. "7890123456789012345678901234567890",
  8510. body);
  8511. EXPECT_EQ(StatusCode::OK_200, res->status);
  8512. }
  8513. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8514. Headers headers;
  8515. headers.emplace("Accept-Encoding", "zstd");
  8516. cli_.set_decompress(false);
  8517. auto res = cli_.Get("/compress", headers);
  8518. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8519. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8520. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8521. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8523. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8525. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8526. EXPECT_EQ(StatusCode::OK_200, res->status);
  8527. ASSERT_EQ(26U, res->body.size());
  8528. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8529. 0);
  8530. }
  8531. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8532. Headers headers;
  8533. headers.emplace("Accept-Encoding", "");
  8534. std::string body;
  8535. auto res = cli_.Get("/compress", headers,
  8536. [&](const char *data, uint64_t data_length) {
  8537. EXPECT_EQ(100U, data_length);
  8538. body.append(data, data_length);
  8539. return true;
  8540. });
  8541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8542. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8543. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8544. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8545. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8546. "7890123456789012345678901234567890",
  8547. body);
  8548. EXPECT_EQ(StatusCode::OK_200, res->status);
  8549. }
  8550. TEST_F(ServerTest, NoZstd) {
  8551. Headers headers;
  8552. headers.emplace("Accept-Encoding", "zstd");
  8553. auto res = cli_.Get("/nocompress", headers);
  8554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8555. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8556. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8557. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8558. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8559. "7890123456789012345678901234567890",
  8560. res->body);
  8561. EXPECT_EQ(StatusCode::OK_200, res->status);
  8562. }
  8563. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8564. Headers headers;
  8565. headers.emplace("Accept-Encoding", "zstd");
  8566. std::string body;
  8567. auto res = cli_.Get("/nocompress", headers,
  8568. [&](const char *data, uint64_t data_length) {
  8569. EXPECT_EQ(100U, data_length);
  8570. body.append(data, data_length);
  8571. return true;
  8572. });
  8573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8574. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8575. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8576. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8577. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8578. "7890123456789012345678901234567890",
  8579. body);
  8580. EXPECT_EQ(StatusCode::OK_200, res->status);
  8581. }
  8582. // TODO: How to enable zstd ??
  8583. TEST_F(ServerTest, MultipartFormDataZstd) {
  8584. UploadFormDataItems items = {
  8585. {"key1", "test", "", ""},
  8586. {"key2", "--abcdefg123", "", ""},
  8587. };
  8588. Headers headers;
  8589. headers.emplace("Accept-Encoding", "zstd");
  8590. cli_.set_compress(true);
  8591. auto res = cli_.Post("/compress-multipart", headers, items);
  8592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. }
  8595. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8596. Headers headers;
  8597. headers.emplace("Accept-Encoding", "zstd");
  8598. cli_.set_compress(true);
  8599. auto res = cli_.Put(
  8600. "/put", headers, 3,
  8601. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8602. sink.os << "PUT";
  8603. return true;
  8604. },
  8605. "text/plain");
  8606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8607. EXPECT_EQ(StatusCode::OK_200, res->status);
  8608. EXPECT_EQ("PUT", res->body);
  8609. }
  8610. // Pre-compression logging tests
  8611. TEST_F(ServerTest, PreCompressionLogging) {
  8612. // Test data for compression (matches the actual /compress endpoint content)
  8613. const std::string test_content =
  8614. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8615. "3456789012345678901234567890";
  8616. // Variables to capture logging data
  8617. std::string pre_compression_body;
  8618. std::string pre_compression_content_type;
  8619. std::string pre_compression_content_encoding;
  8620. std::string post_compression_body;
  8621. std::string post_compression_content_type;
  8622. std::string post_compression_content_encoding;
  8623. // Set up pre-compression logger
  8624. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8625. const Response &res) {
  8626. pre_compression_body = res.body;
  8627. pre_compression_content_type = res.get_header_value("Content-Type");
  8628. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8629. });
  8630. // Set up post-compression logger
  8631. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8632. post_compression_body = res.body;
  8633. post_compression_content_type = res.get_header_value("Content-Type");
  8634. post_compression_content_encoding =
  8635. res.get_header_value("Content-Encoding");
  8636. });
  8637. // Test with gzip compression
  8638. Headers headers;
  8639. headers.emplace("Accept-Encoding", "gzip");
  8640. auto res = cli_.Get("/compress", headers);
  8641. // Verify response was compressed
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8645. // Verify pre-compression logger captured uncompressed content
  8646. EXPECT_EQ(test_content, pre_compression_body);
  8647. EXPECT_EQ("text/plain", pre_compression_content_type);
  8648. EXPECT_TRUE(pre_compression_content_encoding
  8649. .empty()); // No encoding header before compression
  8650. // Verify post-compression logger captured compressed content
  8651. EXPECT_NE(test_content,
  8652. post_compression_body); // Should be different after compression
  8653. EXPECT_EQ("text/plain", post_compression_content_type);
  8654. EXPECT_EQ("gzip", post_compression_content_encoding);
  8655. // Verify compressed content is smaller
  8656. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8657. }
  8658. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8659. const std::string test_content =
  8660. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8661. "3456789012345678901234567890";
  8662. std::string pre_compression_body;
  8663. std::string post_compression_body;
  8664. svr_.set_pre_compression_logger(
  8665. [&](const Request & /*req*/, const Response &res) {
  8666. pre_compression_body = res.body;
  8667. });
  8668. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8669. post_compression_body = res.body;
  8670. });
  8671. Headers headers;
  8672. headers.emplace("Accept-Encoding", "br");
  8673. auto res = cli_.Get("/compress", headers);
  8674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8675. EXPECT_EQ(StatusCode::OK_200, res->status);
  8676. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8677. // Verify pre-compression content is uncompressed
  8678. EXPECT_EQ(test_content, pre_compression_body);
  8679. // Verify post-compression content is compressed
  8680. EXPECT_NE(test_content, post_compression_body);
  8681. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8682. }
  8683. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8684. const std::string test_content =
  8685. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8686. "3456789012345678901234567890";
  8687. std::string pre_compression_body;
  8688. std::string post_compression_body;
  8689. svr_.set_pre_compression_logger(
  8690. [&](const Request & /*req*/, const Response &res) {
  8691. pre_compression_body = res.body;
  8692. });
  8693. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8694. post_compression_body = res.body;
  8695. });
  8696. // Request without compression (use /nocompress endpoint)
  8697. Headers headers;
  8698. auto res = cli_.Get("/nocompress", headers);
  8699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8700. EXPECT_EQ(StatusCode::OK_200, res->status);
  8701. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8702. // Pre-compression logger should not be called when no compression is applied
  8703. EXPECT_TRUE(
  8704. pre_compression_body.empty()); // Pre-compression logger not called
  8705. EXPECT_EQ(
  8706. test_content,
  8707. post_compression_body); // Post-compression logger captures final content
  8708. }
  8709. TEST_F(ServerTest, LoggerSeesContentLength) {
  8710. size_t logged_content_length = 0;
  8711. std::string logged_content_length_header;
  8712. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8713. logged_content_length = res.content_length_;
  8714. logged_content_length_header = res.get_header_value("Content-Length");
  8715. });
  8716. auto res = cli_.Get("/nocompress");
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(StatusCode::OK_200, res->status);
  8719. EXPECT_EQ(res->body.size(), logged_content_length);
  8720. EXPECT_EQ(std::to_string(logged_content_length),
  8721. logged_content_length_header);
  8722. }
  8723. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8724. const std::string test_content =
  8725. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8726. "3456789012345678901234567890";
  8727. std::string pre_compression_body;
  8728. bool pre_logger_called = false;
  8729. // Set only pre-compression logger
  8730. svr_.set_pre_compression_logger(
  8731. [&](const Request & /*req*/, const Response &res) {
  8732. pre_compression_body = res.body;
  8733. pre_logger_called = true;
  8734. });
  8735. Headers headers;
  8736. headers.emplace("Accept-Encoding", "gzip");
  8737. auto res = cli_.Get("/compress", headers);
  8738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8739. EXPECT_EQ(StatusCode::OK_200, res->status);
  8740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8741. // Verify pre-compression logger was called
  8742. EXPECT_TRUE(pre_logger_called);
  8743. EXPECT_EQ(test_content, pre_compression_body);
  8744. }
  8745. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8746. {
  8747. // Test with Expect: 100-continue header - success case
  8748. // Server returns 100 Continue, client sends body, server returns 200 OK
  8749. Request req;
  8750. req.method = "POST";
  8751. req.path = "/post-large";
  8752. req.set_header("Expect", "100-continue");
  8753. req.body = LARGE_DATA;
  8754. Response res;
  8755. auto error = Error::Success;
  8756. cli_.set_keep_alive(true);
  8757. auto ret = cli_.send(req, res, error);
  8758. EXPECT_TRUE(ret);
  8759. EXPECT_EQ(StatusCode::OK_200, res.status);
  8760. EXPECT_EQ(LARGE_DATA, res.body);
  8761. }
  8762. {
  8763. // Test with Expect: 100-continue header - error case
  8764. // Client should not send the body when server returns an error
  8765. Request req;
  8766. req.method = "POST";
  8767. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8768. req.set_header("Expect", "100-continue");
  8769. req.body = LARGE_DATA;
  8770. Response res;
  8771. auto error = Error::Success;
  8772. auto start = std::chrono::high_resolution_clock::now();
  8773. cli_.set_keep_alive(true);
  8774. auto ret = cli_.send(req, res, error);
  8775. auto end = std::chrono::high_resolution_clock::now();
  8776. auto elapsed =
  8777. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8778. .count();
  8779. // With Expect: 100-continue, request completes successfully but with error
  8780. EXPECT_TRUE(ret);
  8781. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8782. EXPECT_EQ("close", res.get_header_value("Connection"));
  8783. EXPECT_FALSE(cli_.is_socket_open());
  8784. EXPECT_LE(elapsed, 2000);
  8785. }
  8786. {
  8787. // Send an extra GET request to ensure error recovery without hanging
  8788. Request req;
  8789. req.method = "GET";
  8790. req.path = "/hi";
  8791. auto start = std::chrono::high_resolution_clock::now();
  8792. auto res = cli_.send(req);
  8793. auto end = std::chrono::high_resolution_clock::now();
  8794. auto elapsed =
  8795. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8796. .count();
  8797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8798. EXPECT_EQ(StatusCode::OK_200, res->status);
  8799. EXPECT_EQ("Hello World!", res->body);
  8800. EXPECT_LE(elapsed, 500);
  8801. }
  8802. }
  8803. TEST(ZstdDecompressor, ChunkedDecompression) {
  8804. std::string data;
  8805. for (size_t i = 0; i < 32 * 1024; ++i) {
  8806. data.push_back(static_cast<char>('a' + i % 26));
  8807. }
  8808. std::string compressed_data;
  8809. {
  8810. httplib::detail::zstd_compressor compressor;
  8811. bool result = compressor.compress(
  8812. data.data(), data.size(),
  8813. /*last=*/true,
  8814. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8815. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8816. compressed_data_size);
  8817. return true;
  8818. });
  8819. ASSERT_TRUE(result);
  8820. }
  8821. std::string decompressed_data;
  8822. {
  8823. httplib::detail::zstd_decompressor decompressor;
  8824. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8825. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8826. size_t chunk_size = 130;
  8827. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8828. chunk_begin += chunk_size) {
  8829. size_t current_chunk_size =
  8830. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8831. bool result = decompressor.decompress(
  8832. compressed_data.data() + chunk_begin, current_chunk_size,
  8833. [&](const char *decompressed_data_chunk,
  8834. size_t decompressed_data_chunk_size) {
  8835. decompressed_data.insert(decompressed_data.size(),
  8836. decompressed_data_chunk,
  8837. decompressed_data_chunk_size);
  8838. return true;
  8839. });
  8840. ASSERT_TRUE(result);
  8841. }
  8842. }
  8843. ASSERT_EQ(data, decompressed_data);
  8844. }
  8845. TEST(ZstdDecompressor, Decompress) {
  8846. std::string original_text = "Compressed with ZSTD";
  8847. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8848. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8849. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8850. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8851. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8852. std::string decompressed_data;
  8853. {
  8854. httplib::detail::zstd_decompressor decompressor;
  8855. bool result = decompressor.decompress(
  8856. compressed_data.data(), compressed_data.size(),
  8857. [&](const char *decompressed_data_chunk,
  8858. size_t decompressed_data_chunk_size) {
  8859. decompressed_data.insert(decompressed_data.size(),
  8860. decompressed_data_chunk,
  8861. decompressed_data_chunk_size);
  8862. return true;
  8863. });
  8864. ASSERT_TRUE(result);
  8865. }
  8866. ASSERT_EQ(original_text, decompressed_data);
  8867. }
  8868. #endif
  8869. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8870. // separate chunks so that the server sees each part in its own read(). Used to
  8871. // place a read boundary at a specific offset of a request body.
  8872. static bool send_request_in_parts(time_t read_timeout_sec,
  8873. const std::vector<std::string> &parts,
  8874. std::string *resp = nullptr,
  8875. int port = PORT) {
  8876. auto error = Error::Success;
  8877. auto client_sock = detail::create_client_socket(
  8878. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8879. /*connection_timeout_sec=*/5, 0,
  8880. /*read_timeout_sec=*/5, 0,
  8881. /*write_timeout_sec=*/5, 0, std::string(), error);
  8882. if (client_sock == INVALID_SOCKET) { return false; }
  8883. auto ret = detail::process_client_socket(
  8884. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8885. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8886. for (size_t i = 0; i < parts.size(); i++) {
  8887. const auto &part = parts[i];
  8888. if (part.size() !=
  8889. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8890. return false;
  8891. }
  8892. if (i + 1 < parts.size()) {
  8893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8894. }
  8895. }
  8896. char buf[512];
  8897. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8898. while (line_reader.getline()) {
  8899. if (resp) { *resp += line_reader.ptr(); }
  8900. }
  8901. return true;
  8902. });
  8903. detail::close_socket(client_sock);
  8904. return ret;
  8905. }
  8906. // Sends a raw request to a server listening at HOST:PORT.
  8907. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8908. std::string *resp = nullptr, int port = PORT) {
  8909. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8910. }
  8911. #ifdef CPPHTTPLIB_SSL_ENABLED
  8912. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8914. ASSERT_TRUE(svr.is_valid());
  8915. svr.set_read_timeout(1, 0);
  8916. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. t.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.wait_until_ready();
  8923. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8924. // keeps each wait well within the read timeout. The server gives up a
  8925. // second in, so the bytes sent after that fail.
  8926. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8927. parts.resize(26, std::string(1, '\0'));
  8928. EXPECT_FALSE(send_request_in_parts(5, parts));
  8929. }
  8930. #endif
  8931. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8932. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  8933. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  8934. const std::vector<std::string> &parts,
  8935. std::string *resp = nullptr,
  8936. int port = PORT) {
  8937. auto error = Error::Success;
  8938. auto sock = detail::create_client_socket(
  8939. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8940. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  8941. /*write_timeout_sec=*/5, 0, std::string(), error);
  8942. if (sock == INVALID_SOCKET) { return false; }
  8943. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  8944. auto ctx = SSL_CTX_new(TLS_client_method());
  8945. auto ssl = SSL_new(ctx);
  8946. auto ssl_se = detail::scope_exit([&] {
  8947. SSL_free(ssl);
  8948. SSL_CTX_free(ctx);
  8949. });
  8950. SSL_set_fd(ssl, static_cast<int>(sock));
  8951. if (SSL_connect(ssl) != 1) { return false; }
  8952. for (size_t i = 0; i < parts.size(); i++) {
  8953. const auto &part = parts[i];
  8954. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  8955. static_cast<int>(part.size())) {
  8956. return false;
  8957. }
  8958. if (i + 1 < parts.size()) {
  8959. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8960. }
  8961. }
  8962. char buf[512];
  8963. int n;
  8964. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  8965. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  8966. }
  8967. return true;
  8968. }
  8969. #endif
  8970. // The request line, then a header value a byte at a time.
  8971. static std::vector<std::string> slow_request_head_parts() {
  8972. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  8973. parts.resize(26, "a");
  8974. parts.emplace_back("\r\n\r\n");
  8975. return parts;
  8976. }
  8977. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  8978. // within the one-second read timeout. The server gives up a second in, before
  8979. // the head is complete.
  8980. static void
  8981. expect_slow_request_head_dropped(Server &svr,
  8982. const std::function<std::string()> &send) {
  8983. std::atomic<bool> handled(false);
  8984. svr.Get("/", [&](const Request &, Response &res) {
  8985. handled = true;
  8986. res.set_content("ok", "text/plain");
  8987. });
  8988. svr.set_read_timeout(1, 0);
  8989. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8990. auto se = detail::scope_exit([&] {
  8991. svr.stop();
  8992. t.join();
  8993. ASSERT_FALSE(svr.is_running());
  8994. });
  8995. svr.wait_until_ready();
  8996. auto resp = send();
  8997. EXPECT_FALSE(handled);
  8998. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  8999. }
  9000. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9001. Server svr;
  9002. expect_slow_request_head_dropped(svr, [] {
  9003. std::string resp;
  9004. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9005. return resp;
  9006. });
  9007. }
  9008. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9009. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9011. ASSERT_TRUE(svr.is_valid());
  9012. expect_slow_request_head_dropped(svr, [] {
  9013. std::string resp;
  9014. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9015. return resp;
  9016. });
  9017. }
  9018. #endif
  9019. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9020. Server svr;
  9021. std::string header_value;
  9022. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9023. header_value = req.get_header_value("foo");
  9024. res.set_content("ok", "text/plain");
  9025. });
  9026. thread t = thread([&] { svr.listen(HOST, PORT); });
  9027. auto se = detail::scope_exit([&] {
  9028. svr.stop();
  9029. t.join();
  9030. ASSERT_FALSE(svr.is_running());
  9031. });
  9032. svr.wait_until_ready();
  9033. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9034. // like characters are not treated the same - use vertical tab and escape.
  9035. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9036. "foo: \t \v bar \x1B\t \r\n"
  9037. "Connection: close\r\n"
  9038. "\r\n";
  9039. std::string res;
  9040. ASSERT_TRUE(send_request(5, req, &res));
  9041. EXPECT_EQ(header_value, "");
  9042. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9043. }
  9044. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9045. Server svr;
  9046. std::string received;
  9047. svr.Get("/order", [&](const Request &req, Response &res) {
  9048. received = entries_to_string(req.headers);
  9049. res.set_content("ok", "text/plain");
  9050. });
  9051. auto port = svr.bind_to_any_port(HOST);
  9052. thread t = thread([&] { svr.listen_after_bind(); });
  9053. auto se = detail::scope_exit([&] {
  9054. svr.stop();
  9055. t.join();
  9056. ASSERT_FALSE(svr.is_running());
  9057. });
  9058. svr.wait_until_ready();
  9059. const std::string req = "GET /order HTTP/1.1\r\n"
  9060. "Host: localhost\r\n"
  9061. "X-First: 1\r\n"
  9062. "X-Dup: a\r\n"
  9063. "X-Second: 2\r\n"
  9064. "X-Dup: b\r\n"
  9065. "Connection: close\r\n"
  9066. "\r\n";
  9067. std::string res;
  9068. ASSERT_TRUE(send_request(5, req, &res, port));
  9069. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9070. EXPECT_EQ(
  9071. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9072. received);
  9073. }
  9074. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9075. Server svr;
  9076. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9077. res.set_header("Set-Cookie", "first=1");
  9078. res.set_header("X-Between", "y");
  9079. res.set_header("Set-Cookie", "second=2");
  9080. res.set_content("ok", "text/plain");
  9081. });
  9082. auto port = svr.bind_to_any_port(HOST);
  9083. thread t = thread([&] { svr.listen_after_bind(); });
  9084. auto se = detail::scope_exit([&] {
  9085. svr.stop();
  9086. t.join();
  9087. ASSERT_FALSE(svr.is_running());
  9088. });
  9089. svr.wait_until_ready();
  9090. Client cli(HOST, port);
  9091. auto res = cli.Get("/cookies");
  9092. ASSERT_TRUE(res);
  9093. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9094. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9095. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9096. }
  9097. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9098. Server svr;
  9099. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9100. auto i = new int(0);
  9101. res.set_header("Trailer", "X-Safe, X-Reflected");
  9102. res.set_chunked_content_provider(
  9103. "text/plain",
  9104. [i](size_t /*offset*/, DataSink &sink) {
  9105. if (*i == 0) {
  9106. sink.os << "body";
  9107. } else {
  9108. Headers trailer;
  9109. // A valid trailer that must survive.
  9110. trailer.emplace("X-Safe", "safe");
  9111. // Attacker-controlled value carrying CR/LF (response splitting).
  9112. trailer.emplace("X-Reflected",
  9113. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9114. // Attacker-controlled name carrying CR/LF.
  9115. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9116. sink.done_with_trailer(trailer);
  9117. }
  9118. (*i)++;
  9119. return true;
  9120. },
  9121. [i](bool /*success*/) { delete i; });
  9122. });
  9123. thread t = thread([&] { svr.listen(HOST, PORT); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. t.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. });
  9129. svr.wait_until_ready();
  9130. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9131. "Host: " + HOST +
  9132. "\r\n"
  9133. "Connection: close\r\n"
  9134. "\r\n";
  9135. std::string res;
  9136. ASSERT_TRUE(send_request(5, req, &res));
  9137. // The injected fields must not appear anywhere in the raw response.
  9138. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9139. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9140. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9141. // Invalid trailers are dropped entirely, matching set_header().
  9142. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9143. // The valid trailer still passes through.
  9144. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9145. }
  9146. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9147. Server svr;
  9148. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9149. // res.headers is a public field an application can populate directly,
  9150. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9151. // A valid header that must survive.
  9152. res.headers.emplace("X-Safe", "safe");
  9153. // Attacker-controlled value carrying CR/LF (response splitting).
  9154. res.headers.emplace("X-Reflected",
  9155. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9156. // Attacker-controlled name carrying CR/LF.
  9157. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9158. res.set_content("body", "text/plain");
  9159. });
  9160. thread t = thread([&] { svr.listen(HOST, PORT); });
  9161. auto se = detail::scope_exit([&] {
  9162. svr.stop();
  9163. t.join();
  9164. ASSERT_FALSE(svr.is_running());
  9165. });
  9166. svr.wait_until_ready();
  9167. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9168. "Host: " + HOST +
  9169. "\r\n"
  9170. "Connection: close\r\n"
  9171. "\r\n";
  9172. std::string res;
  9173. ASSERT_TRUE(send_request(5, req, &res));
  9174. // The injected fields must not appear anywhere in the raw response.
  9175. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9176. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9177. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9178. // Invalid headers are dropped entirely, matching set_header().
  9179. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9180. // The valid header still passes through.
  9181. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9182. }
  9183. // Forward declaration: in split builds split.py strips `inline` and moves the
  9184. // definition into httplib.cc, so detail::write_request_line is not visible from
  9185. // the public httplib.h. Re-declaring it here lets the tests link against the
  9186. // symbol in both header-only and split builds.
  9187. namespace httplib {
  9188. namespace detail {
  9189. ssize_t write_request_line(Stream &strm, const std::string &method,
  9190. const std::string &path);
  9191. } // namespace detail
  9192. } // namespace httplib
  9193. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9194. // A well-formed target is written verbatim.
  9195. {
  9196. detail::BufferStream strm;
  9197. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9198. EXPECT_GT(n, 0);
  9199. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9200. }
  9201. // A target carrying CR/LF, SP or other control octets must be rejected
  9202. // before anything reaches the wire, otherwise it splits the request line and
  9203. // injects a header or a whole request.
  9204. const std::string evil_targets[] = {
  9205. "/a\r\nInjected: pwned",
  9206. "/a\rInjected",
  9207. "/a\nInjected",
  9208. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9209. "/a b",
  9210. "/a\tb",
  9211. "/a\x7f",
  9212. };
  9213. for (const auto &evil : evil_targets) {
  9214. detail::BufferStream strm;
  9215. auto n = detail::write_request_line(strm, "GET", evil);
  9216. EXPECT_LT(n, 0);
  9217. EXPECT_TRUE(strm.get_buffer().empty());
  9218. }
  9219. }
  9220. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9221. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9222. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9223. // target reaches write_request. The client must fail cleanly with
  9224. // Error::Write instead of putting a request-line-less, header-injecting
  9225. // request on the wire.
  9226. Server svr;
  9227. svr.Get("/a", [](const Request &, Response &res) {
  9228. res.set_content("ok", "text/plain");
  9229. });
  9230. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9231. auto se = detail::scope_exit([&] {
  9232. svr.stop();
  9233. thread.join();
  9234. ASSERT_FALSE(svr.is_running());
  9235. });
  9236. svr.wait_until_ready();
  9237. {
  9238. Client cli(HOST, PORT);
  9239. cli.set_path_encode(false);
  9240. // The request is rejected before anything is written, so the connection
  9241. // stays silent and the subsequent response read would otherwise block for
  9242. // the full default read timeout. Shorten it -- the assertion is on the
  9243. // error, not the timeout.
  9244. cli.set_read_timeout(1, 0);
  9245. auto res = cli.Get("/a\r\nInjected: pwned");
  9246. EXPECT_FALSE(res);
  9247. EXPECT_EQ(Error::Write, res.error());
  9248. }
  9249. }
  9250. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9251. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9252. // including extension methods.
  9253. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9254. for (const auto &method : good_methods) {
  9255. detail::BufferStream strm;
  9256. auto n = detail::write_request_line(strm, method, "/");
  9257. EXPECT_GT(n, 0);
  9258. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9259. }
  9260. // A method carrying CR/LF would split the request line and smuggle a whole
  9261. // request ahead of the real one. A space or an empty method corrupts the
  9262. // request line. All must be rejected before anything reaches the wire.
  9263. const std::string evil_methods[] = {
  9264. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9265. "GET\r\nInjected: pwned",
  9266. "GET\r",
  9267. "GET\n",
  9268. "GE T",
  9269. "",
  9270. };
  9271. for (const auto &evil : evil_methods) {
  9272. detail::BufferStream strm;
  9273. auto n = detail::write_request_line(strm, evil, "/");
  9274. EXPECT_LT(n, 0);
  9275. EXPECT_TRUE(strm.get_buffer().empty());
  9276. }
  9277. }
  9278. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9279. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9280. // through Client::send must fail with Error::Write and no request, neither
  9281. // the smuggled one nor the real one, may reach the server.
  9282. Server svr;
  9283. std::atomic<int> request_count(0);
  9284. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9285. request_count++;
  9286. res.status = StatusCode::OK_200;
  9287. return Server::HandlerResponse::Handled;
  9288. });
  9289. auto port = svr.bind_to_any_port(HOST);
  9290. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9291. auto se = detail::scope_exit([&] {
  9292. svr.stop();
  9293. thread.join();
  9294. ASSERT_FALSE(svr.is_running());
  9295. });
  9296. svr.wait_until_ready();
  9297. {
  9298. Client cli(HOST, port);
  9299. const std::string evil_methods[] = {
  9300. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9301. "GE T",
  9302. "",
  9303. };
  9304. for (const auto &evil : evil_methods) {
  9305. Request req;
  9306. req.method = evil;
  9307. req.path = "/";
  9308. auto res = cli.send(req);
  9309. EXPECT_FALSE(res);
  9310. EXPECT_EQ(Error::Write, res.error());
  9311. }
  9312. auto handle =
  9313. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9314. EXPECT_FALSE(handle.is_valid());
  9315. EXPECT_EQ(Error::Write, handle.error);
  9316. // A valid request on the same client still goes through.
  9317. auto res = cli.Get("/");
  9318. ASSERT_TRUE(res);
  9319. EXPECT_EQ(StatusCode::OK_200, res->status);
  9320. }
  9321. EXPECT_EQ(1, request_count.load());
  9322. }
  9323. // Sends a raw request and verifies that there isn't a crash or exception.
  9324. static void test_raw_request(const std::string &req,
  9325. std::string *out = nullptr) {
  9326. Server svr;
  9327. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9328. res.set_content("ok", "text/plain");
  9329. });
  9330. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9331. res.set_content("ok", "text/plain");
  9332. });
  9333. svr.Get("/header_field_value_check",
  9334. [&](const Request & /*req*/, Response &res) {
  9335. res.set_content("ok", "text/plain");
  9336. });
  9337. svr.CustomRoute("PROPFIND", "/dav",
  9338. [&](const Request & /*req*/, Response &res) {
  9339. res.status = StatusCode::MultiStatus_207;
  9340. });
  9341. // Server read timeout must be longer than the client read timeout for the
  9342. // bug to reproduce, probably to force the server to process a request
  9343. // without a trailing blank line.
  9344. const time_t client_read_timeout_sec = 1;
  9345. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9346. bool listen_thread_ok = false;
  9347. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9348. auto se = detail::scope_exit([&] {
  9349. svr.stop();
  9350. t.join();
  9351. ASSERT_FALSE(svr.is_running());
  9352. EXPECT_TRUE(listen_thread_ok);
  9353. });
  9354. svr.wait_until_ready();
  9355. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9356. }
  9357. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9358. // A certain header line causes an exception if the header property is parsed
  9359. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9360. test_raw_request(
  9361. "GET /hi HTTP/1.1\r\n"
  9362. " : "
  9363. " "
  9364. " ");
  9365. }
  9366. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9367. // A certain header line causes an exception if the header property *name* is
  9368. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9369. // greedy matcher and requires backtracking when there are a lot of ":"
  9370. // characters.
  9371. // This occurs with libc++ but not libstdc++.
  9372. test_raw_request(
  9373. "GET /hi HTTP/1.1\r\n"
  9374. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9375. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9376. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9377. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9378. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9379. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9380. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9381. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9382. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9383. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9384. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9385. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9386. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9387. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9388. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9389. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9390. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9391. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9392. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9393. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9394. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9395. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9396. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9397. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9398. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9399. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9400. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9401. "&&&%%%");
  9402. }
  9403. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9404. // Make sure this doesn't crash the server.
  9405. // In a previous version of the header line regex, the "\r" rendered the line
  9406. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9407. // a new position where the leading white space ended and the field value
  9408. // began.
  9409. // The crash occurs with libc++ but not libstdc++.
  9410. test_raw_request("GET /hi HTTP/1.1\r\n"
  9411. "a:" +
  9412. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9413. "\r\n"
  9414. "\r\n");
  9415. }
  9416. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9417. const char *rejected[] = {
  9418. // RFC 9112 §3: one SP between the parts, and nothing else
  9419. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9420. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9421. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9422. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9423. // A request-target has no fragment
  9424. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9425. // An HTTP/1.1 request needs a Host
  9426. "GET /hi HTTP/1.1\r\n\r\n",
  9427. };
  9428. for (auto request : rejected) {
  9429. std::string out;
  9430. test_raw_request(request, &out);
  9431. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9432. }
  9433. std::string out;
  9434. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9435. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9436. }
  9437. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9438. // RFC 9112 §6.1
  9439. const char *requests[] = {
  9440. "PUT /put_hi HTTP/1.1\r\n"
  9441. "Host: localhost\r\n"
  9442. "Content-Length: 0\r\n"
  9443. "Transfer-Encoding: chunked\r\n"
  9444. "\r\n"
  9445. "0\r\n\r\n",
  9446. "PUT /put_hi HTTP/1.0\r\n"
  9447. "Connection: keep-alive\r\n"
  9448. "Transfer-Encoding: chunked\r\n"
  9449. "\r\n"
  9450. "0\r\n\r\n",
  9451. };
  9452. for (auto request : requests) {
  9453. std::string out;
  9454. test_raw_request(request, &out);
  9455. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9456. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9457. }
  9458. }
  9459. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9460. std::string out;
  9461. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9462. "Content-Type: text/plain\r\n"
  9463. "Transfer-Encoding: chunked\r\n"
  9464. "\r\n"
  9465. "nothex\r\n",
  9466. &out);
  9467. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9468. }
  9469. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9470. std::string out;
  9471. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9472. "Content-Type: text/plain\r\n"
  9473. "Transfer-Encoding: chunked\r\n"
  9474. "\r\n"
  9475. "3\r\n"
  9476. "xyz\r\n"
  9477. "NaN\r\n",
  9478. &out);
  9479. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9480. }
  9481. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9482. std::string out;
  9483. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9484. "Content-Type: text/plain\r\n"
  9485. "Transfer-Encoding: chunked\r\n"
  9486. "\r\n"
  9487. // Length is too large for 64 bits.
  9488. "1ffffffffffffffff\r\n"
  9489. "xyz\r\n",
  9490. &out);
  9491. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9492. }
  9493. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9494. test_raw_request("GET /hi HTTP/1.1\r\n"
  9495. "Content-Type: text/plain\r\n\r");
  9496. }
  9497. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9498. std::string out;
  9499. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9500. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9501. }
  9502. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9503. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9504. std::string out;
  9505. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9506. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9507. }
  9508. }
  9509. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9510. std::string out;
  9511. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9512. "Host: localhost\r\n"
  9513. "Connection: close\r\n\r\n",
  9514. &out);
  9515. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9516. }
  9517. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9518. Server svr;
  9519. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9520. EXPECT_TRUE(!req.remote_addr.empty());
  9521. });
  9522. thread t = thread([&] { svr.listen(HOST, PORT); });
  9523. auto se = detail::scope_exit([&] {
  9524. svr.stop();
  9525. t.join();
  9526. ASSERT_FALSE(svr.is_running());
  9527. });
  9528. svr.wait_until_ready();
  9529. // Send an invalid request line to trigger Bad Request
  9530. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9531. std::string out;
  9532. ASSERT_TRUE(send_request(5, bad_req, &out));
  9533. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9534. }
  9535. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9536. // answered right away rather than blocking on a read that waits for EOF.
  9537. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9538. std::string out;
  9539. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9540. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9541. }
  9542. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9543. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9544. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9545. for (const auto *method : methods) {
  9546. Server svr;
  9547. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9548. EXPECT_FALSE(svr.is_valid()) << method;
  9549. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9550. }
  9551. }
  9552. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9553. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9554. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9555. for (const auto *method : methods) {
  9556. Server svr;
  9557. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9558. EXPECT_FALSE(svr.is_valid()) << method;
  9559. }
  9560. }
  9561. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9562. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9563. "COPY", "MOVE", "LOCK",
  9564. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9565. Server svr;
  9566. for (const auto *method : methods) {
  9567. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9568. }
  9569. EXPECT_TRUE(svr.is_valid());
  9570. }
  9571. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9572. Server svr;
  9573. svr.CustomRoute("POST", "/x",
  9574. [](const Request &, Response &, const ContentReader &) {});
  9575. EXPECT_FALSE(svr.is_valid());
  9576. }
  9577. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9578. Server svr;
  9579. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9580. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9581. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9582. EXPECT_FALSE(svr.is_valid());
  9583. }
  9584. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9585. Server svr;
  9586. auto captured = Error::Success;
  9587. svr.set_error_logger(
  9588. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9589. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9590. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9591. }
  9592. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9593. std::string out;
  9594. std::string request(
  9595. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9596. test_raw_request(request, &out);
  9597. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9598. }
  9599. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9600. std::string out;
  9601. std::string request(
  9602. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9603. test_raw_request(request, &out);
  9604. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9605. }
  9606. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9607. std::string out;
  9608. std::string request(
  9609. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9610. test_raw_request(request, &out);
  9611. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9612. }
  9613. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9614. std::string out;
  9615. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9616. "Host: localhost\r\n"
  9617. "Test: \r\n\r\n",
  9618. &out);
  9619. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9620. }
  9621. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9622. Server svr;
  9623. std::string x_custom;
  9624. std::string cookie;
  9625. std::string xff;
  9626. std::string x_unicode;
  9627. std::string x_iis;
  9628. svr.Get("/check", [&](const Request &req, Response &res) {
  9629. x_custom = req.get_header_value("X-Custom");
  9630. cookie = req.get_header_value("Cookie");
  9631. xff = req.get_header_value("X-Forwarded-For");
  9632. x_unicode = req.get_header_value("X-Unicode");
  9633. x_iis = req.get_header_value("X-IIS");
  9634. res.set_content("ok", "text/plain");
  9635. });
  9636. thread t = thread([&] { svr.listen(HOST, PORT); });
  9637. auto se = detail::scope_exit([&] {
  9638. svr.stop();
  9639. t.join();
  9640. ASSERT_FALSE(svr.is_running());
  9641. });
  9642. svr.wait_until_ready();
  9643. const std::string req = "GET /check HTTP/1.1\r\n"
  9644. "Host: localhost\r\n"
  9645. "X-Custom: a%0D%0AInjected: b\r\n"
  9646. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9647. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9648. "X-Unicode: %E3%81%82\r\n"
  9649. "X-IIS: %u00E9\r\n"
  9650. "Connection: close\r\n"
  9651. "\r\n";
  9652. std::string res;
  9653. ASSERT_TRUE(send_request(5, req, &res));
  9654. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9655. // Every value must be returned verbatim (wire form), with no decoding.
  9656. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9657. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9658. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9659. EXPECT_EQ("%E3%81%82", x_unicode);
  9660. EXPECT_EQ("%u00E9", x_iis);
  9661. }
  9662. // Applications that previously relied on automatic percent-decoding can
  9663. // reproduce the old behavior by explicitly calling decode_path_component()
  9664. // or, for RFC 3986 conformance, decode_uri_component().
  9665. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9666. Server svr;
  9667. std::string decoded;
  9668. svr.Get("/check", [&](const Request &req, Response &res) {
  9669. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9670. res.set_content("ok", "text/plain");
  9671. });
  9672. thread t = thread([&] { svr.listen(HOST, PORT); });
  9673. auto se = detail::scope_exit([&] {
  9674. svr.stop();
  9675. t.join();
  9676. ASSERT_FALSE(svr.is_running());
  9677. });
  9678. svr.wait_until_ready();
  9679. const std::string req = "GET /check HTTP/1.1\r\n"
  9680. "Host: localhost\r\n"
  9681. "X-Custom: hello%20world\r\n"
  9682. "Connection: close\r\n"
  9683. "\r\n";
  9684. std::string res;
  9685. ASSERT_TRUE(send_request(5, req, &res));
  9686. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9687. EXPECT_EQ("hello world", decoded);
  9688. }
  9689. // Regression test for #2033. Browsers send Referer values that include
  9690. // percent-encoded characters such as %0A inside the URL. Decoding the
  9691. // header value would either trip the post-decode CR/LF/NUL guard (the
  9692. // original bug, returning 400) or, after that guard was relaxed, silently
  9693. // store a literal LF — both unacceptable. The wire form must round-trip.
  9694. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9695. Server svr;
  9696. std::string referer;
  9697. svr.Get("/check", [&](const Request &req, Response &res) {
  9698. referer = req.get_header_value("Referer");
  9699. res.set_content("ok", "text/plain");
  9700. });
  9701. thread t = thread([&] { svr.listen(HOST, PORT); });
  9702. auto se = detail::scope_exit([&] {
  9703. svr.stop();
  9704. t.join();
  9705. ASSERT_FALSE(svr.is_running());
  9706. });
  9707. svr.wait_until_ready();
  9708. const std::string req = "GET /check HTTP/1.1\r\n"
  9709. "Host: localhost\r\n"
  9710. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9711. "Connection: close\r\n"
  9712. "\r\n";
  9713. std::string res;
  9714. ASSERT_TRUE(send_request(5, req, &res));
  9715. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9716. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9717. }
  9718. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9719. Server svr;
  9720. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9721. res.set_header("Cache-Control", "no-cache");
  9722. res.set_chunked_content_provider(
  9723. "text/event-stream", [](size_t offset, DataSink &sink) {
  9724. std::string s = "data:";
  9725. s += std::to_string(offset);
  9726. s += "\n\n";
  9727. auto ret = sink.write(s.data(), s.size());
  9728. EXPECT_TRUE(ret);
  9729. std::this_thread::sleep_for(std::chrono::seconds(1));
  9730. return true;
  9731. });
  9732. });
  9733. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9734. svr.wait_until_ready();
  9735. Client client(HOST, PORT);
  9736. const Headers headers = {{"Accept", "text/event-stream"}};
  9737. auto get_thread = std::thread([&client, &headers]() {
  9738. auto res = client.Get(
  9739. "/events", headers,
  9740. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9741. });
  9742. auto se = detail::scope_exit([&] {
  9743. svr.stop();
  9744. get_thread.join();
  9745. listen_thread.join();
  9746. ASSERT_FALSE(svr.is_running());
  9747. });
  9748. // Give GET time to get a few messages.
  9749. std::this_thread::sleep_for(std::chrono::seconds(2));
  9750. }
  9751. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9752. httplib::Server svr;
  9753. svr.Post("/hi",
  9754. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9755. res.status = StatusCode::OK_200;
  9756. });
  9757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9758. svr.wait_until_ready();
  9759. Client cli(HOST, PORT);
  9760. auto res = cli.Post("/hi", "data", "text/plain");
  9761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9762. EXPECT_EQ(StatusCode::OK_200, res->status);
  9763. svr.stop();
  9764. thread.join();
  9765. ASSERT_FALSE(svr.is_running());
  9766. res = cli.Post("/hi", "data", "text/plain");
  9767. ASSERT_FALSE(res);
  9768. }
  9769. TEST(ServerStopTest, ListenFailure) {
  9770. Server svr;
  9771. auto t = thread([&]() {
  9772. auto ret = svr.listen("????", PORT);
  9773. EXPECT_FALSE(ret);
  9774. });
  9775. svr.wait_until_ready();
  9776. svr.stop();
  9777. t.join();
  9778. }
  9779. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9780. TEST(ServerStopTest, Decommision) {
  9781. Server svr;
  9782. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9783. for (int i = 0; i < 4; i++) {
  9784. auto is_even = !(i % 2);
  9785. std::thread t{[&] {
  9786. try {
  9787. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9788. if (is_even) {
  9789. throw std::runtime_error("Some thing that happens to go wrong.");
  9790. }
  9791. svr.listen(HOST, PORT);
  9792. } catch (...) { svr.decommission(); }
  9793. }};
  9794. svr.wait_until_ready();
  9795. // Server is up
  9796. {
  9797. Client cli(HOST, PORT);
  9798. auto res = cli.Get("/hi");
  9799. if (is_even) {
  9800. EXPECT_FALSE(res);
  9801. } else {
  9802. EXPECT_TRUE(res);
  9803. EXPECT_EQ("hi...", res->body);
  9804. }
  9805. }
  9806. svr.stop();
  9807. t.join();
  9808. // Server is down...
  9809. {
  9810. Client cli(HOST, PORT);
  9811. auto res = cli.Get("/hi");
  9812. EXPECT_FALSE(res);
  9813. }
  9814. }
  9815. }
  9816. #endif
  9817. // Helper function for string body upload progress tests
  9818. template <typename SetupHandler, typename ClientCall>
  9819. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9820. ClientCall &&client_call,
  9821. const string &body) {
  9822. Server svr;
  9823. setup_handler(svr);
  9824. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9825. auto se = detail::scope_exit([&] {
  9826. svr.stop();
  9827. t.join();
  9828. });
  9829. svr.wait_until_ready();
  9830. Client cli(HOST, PORT);
  9831. vector<uint64_t> progress_values;
  9832. bool progress_called = false;
  9833. auto res =
  9834. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9835. progress_values.push_back(current);
  9836. progress_called = true;
  9837. return true;
  9838. });
  9839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9840. EXPECT_EQ(200, res->status);
  9841. EXPECT_TRUE(progress_called);
  9842. }
  9843. TEST(UploadProgressTest, PostStringBodyBasic) {
  9844. TestStringBodyUploadProgress(
  9845. [](Server &svr) {
  9846. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9847. res.set_content("received", "text/plain");
  9848. });
  9849. },
  9850. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9851. return cli.Post("/test", body, "text/plain", progress_callback);
  9852. },
  9853. "test data for upload progress");
  9854. }
  9855. TEST(UploadProgressTest, PutStringBodyBasic) {
  9856. TestStringBodyUploadProgress(
  9857. [](Server &svr) {
  9858. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9859. res.set_content("put received", "text/plain");
  9860. });
  9861. },
  9862. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9863. return cli.Put("/test", body, "text/plain", progress_callback);
  9864. },
  9865. "put test data for upload progress");
  9866. }
  9867. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9868. TestStringBodyUploadProgress(
  9869. [](Server &svr) {
  9870. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9871. res.set_content("patch received", "text/plain");
  9872. });
  9873. },
  9874. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9875. return cli.Patch("/test", body, "text/plain", progress_callback);
  9876. },
  9877. "patch test data for upload progress");
  9878. }
  9879. // Helper function for content provider upload progress tests
  9880. template <typename SetupHandler, typename ClientCall>
  9881. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9882. ClientCall &&client_call) {
  9883. Server svr;
  9884. setup_handler(svr);
  9885. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9886. auto se = detail::scope_exit([&] {
  9887. svr.stop();
  9888. t.join();
  9889. });
  9890. svr.wait_until_ready();
  9891. Client cli(HOST, PORT);
  9892. vector<uint64_t> progress_values;
  9893. auto res =
  9894. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9895. progress_values.push_back(current);
  9896. return true;
  9897. });
  9898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9899. EXPECT_EQ(200, res->status);
  9900. EXPECT_FALSE(progress_values.empty());
  9901. }
  9902. TEST(UploadProgressTest, PostContentProviderProgress) {
  9903. TestContentProviderUploadProgress(
  9904. [](Server &svr) {
  9905. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9906. res.set_content("provider received", "text/plain");
  9907. });
  9908. },
  9909. [](Client &cli, UploadProgress progress_callback) {
  9910. return cli.Post(
  9911. "/test", 9,
  9912. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9913. sink.os << "test data";
  9914. return true;
  9915. },
  9916. "text/plain", progress_callback);
  9917. });
  9918. }
  9919. // Helper function for multipart upload progress tests
  9920. template <typename SetupHandler, typename ClientCall>
  9921. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9922. ClientCall &&client_call,
  9923. const string &endpoint) {
  9924. Server svr;
  9925. setup_handler(svr);
  9926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9927. auto se = detail::scope_exit([&] {
  9928. svr.stop();
  9929. t.join();
  9930. });
  9931. svr.wait_until_ready();
  9932. Client cli(HOST, PORT);
  9933. vector<uint64_t> progress_values;
  9934. UploadFormDataItems items = {
  9935. {"field1", "value1", "", ""},
  9936. {"field2", "longer value for progress tracking test", "", ""},
  9937. {"file1", "file content data for upload progress", "test.txt",
  9938. "text/plain"}};
  9939. auto res = client_call(cli, endpoint, items,
  9940. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9941. progress_values.push_back(current);
  9942. return true;
  9943. });
  9944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9945. EXPECT_EQ(200, res->status);
  9946. EXPECT_FALSE(progress_values.empty());
  9947. }
  9948. TEST(UploadProgressTest, PostMultipartProgress) {
  9949. TestMultipartUploadProgress(
  9950. [](Server &svr) {
  9951. svr.Post("/multipart", [](const Request &req, Response &res) {
  9952. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9953. res.set_content("multipart received", "text/plain");
  9954. });
  9955. },
  9956. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9957. UploadProgress progress_callback) {
  9958. return cli.Post(endpoint, items, progress_callback);
  9959. },
  9960. "/multipart");
  9961. }
  9962. // Helper function for basic download progress tests
  9963. template <typename SetupHandler, typename ClientCall>
  9964. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9965. ClientCall &&client_call, const string &endpoint,
  9966. size_t expected_content_size) {
  9967. Server svr;
  9968. setup_handler(svr);
  9969. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. });
  9974. svr.wait_until_ready();
  9975. Client cli(HOST, PORT);
  9976. vector<uint64_t> progress_values;
  9977. auto res = client_call(cli, endpoint,
  9978. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9979. progress_values.push_back(current);
  9980. return true;
  9981. });
  9982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9983. EXPECT_EQ(200, res->status);
  9984. EXPECT_FALSE(progress_values.empty());
  9985. EXPECT_EQ(expected_content_size, res->body.size());
  9986. }
  9987. TEST(DownloadProgressTest, GetBasic) {
  9988. TestBasicDownloadProgress(
  9989. [](Server &svr) {
  9990. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9991. string content(1000, 'D');
  9992. res.set_content(content, "text/plain");
  9993. });
  9994. },
  9995. [](Client &cli, const string &endpoint,
  9996. DownloadProgress progress_callback) {
  9997. return cli.Get(endpoint, progress_callback);
  9998. },
  9999. "/download", 1000u);
  10000. }
  10001. // Helper function for content receiver download progress tests
  10002. template <typename SetupHandler, typename ClientCall>
  10003. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10004. ClientCall &&client_call,
  10005. const string &endpoint,
  10006. size_t expected_content_size) {
  10007. Server svr;
  10008. setup_handler(svr);
  10009. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10010. auto se = detail::scope_exit([&] {
  10011. svr.stop();
  10012. t.join();
  10013. });
  10014. svr.wait_until_ready();
  10015. Client cli(HOST, PORT);
  10016. vector<uint64_t> progress_values;
  10017. string received_body;
  10018. auto res = client_call(
  10019. cli, endpoint,
  10020. [&](const char *data, size_t data_length) -> bool {
  10021. received_body.append(data, data_length);
  10022. return true;
  10023. },
  10024. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10025. progress_values.push_back(current);
  10026. return true;
  10027. });
  10028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10029. EXPECT_EQ(200, res->status);
  10030. EXPECT_FALSE(progress_values.empty());
  10031. EXPECT_EQ(expected_content_size, received_body.size());
  10032. EXPECT_TRUE(res->body.empty());
  10033. }
  10034. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10035. TestContentReceiverDownloadProgress(
  10036. [](Server &svr) {
  10037. svr.Get("/download-receiver",
  10038. [](const Request & /*req*/, Response &res) {
  10039. string content(2000, 'R');
  10040. res.set_content(content, "text/plain");
  10041. });
  10042. },
  10043. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10044. DownloadProgress progress_callback) {
  10045. return cli.Get(endpoint, content_receiver, progress_callback);
  10046. },
  10047. "/download-receiver", 2000u);
  10048. }
  10049. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10050. // A provider reaching a pass with nothing to hand over - an empty buffer
  10051. // popped off a queue, say - must not be taken to mean the body is finished.
  10052. // It used to end the loop with the terminating chunk unwritten while the
  10053. // server still considered the response complete, so the peer waited for an
  10054. // end that never arrived.
  10055. Server svr;
  10056. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10057. auto step = std::make_shared<int>(0);
  10058. res.set_chunked_content_provider("text/plain",
  10059. [step](size_t /*offset*/, DataSink &sink) {
  10060. switch ((*step)++) {
  10061. case 0: sink.write("", 0); break;
  10062. case 1: sink.write("hello", 5); break;
  10063. default: sink.done(); break;
  10064. }
  10065. return true;
  10066. });
  10067. });
  10068. auto port = svr.bind_to_any_port(HOST);
  10069. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10070. auto listen_se = detail::scope_exit([&] {
  10071. svr.stop();
  10072. listen_thread.join();
  10073. ASSERT_FALSE(svr.is_running());
  10074. });
  10075. svr.wait_until_ready();
  10076. Client cli(HOST, port);
  10077. // Without the fix the body is never terminated, so bound the wait rather
  10078. // than letting the test hang on the default read timeout.
  10079. cli.set_read_timeout(5, 0);
  10080. auto res = cli.Get("/stream");
  10081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10082. EXPECT_EQ(StatusCode::OK_200, res->status);
  10083. EXPECT_EQ("hello", res->body);
  10084. }
  10085. TEST(StreamingTest, NoContentLengthStreaming) {
  10086. Server svr;
  10087. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10088. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10089. if (offset < 6) {
  10090. sink.os << (offset < 3 ? "a" : "b");
  10091. } else {
  10092. sink.done();
  10093. }
  10094. return true;
  10095. });
  10096. });
  10097. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10098. auto listen_se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. listen_thread.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. Client client(HOST, PORT);
  10105. auto get_thread = std::thread([&client]() {
  10106. std::string s;
  10107. auto res =
  10108. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10109. s += std::string(data, len);
  10110. return true;
  10111. });
  10112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10113. EXPECT_EQ(StatusCode::OK_200, res->status);
  10114. EXPECT_EQ("aaabbb", s);
  10115. });
  10116. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10117. // Give GET time to get a few messages.
  10118. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10119. }
  10120. TEST(MountTest, Unmount) {
  10121. Server svr;
  10122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. listen_thread.join();
  10126. ASSERT_FALSE(svr.is_running());
  10127. });
  10128. svr.wait_until_ready();
  10129. Client cli("localhost", PORT);
  10130. svr.set_mount_point("/mount2", "./www2");
  10131. auto res = cli.Get("/");
  10132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10134. res = cli.Get("/mount2/dir/test.html");
  10135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10136. EXPECT_EQ(StatusCode::OK_200, res->status);
  10137. svr.set_mount_point("/", "./www");
  10138. res = cli.Get("/dir/");
  10139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10140. EXPECT_EQ(StatusCode::OK_200, res->status);
  10141. svr.remove_mount_point("/");
  10142. res = cli.Get("/dir/");
  10143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10145. svr.remove_mount_point("/mount2");
  10146. res = cli.Get("/mount2/dir/test.html");
  10147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10149. }
  10150. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10151. Server svr;
  10152. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10153. svr.Get("/api/hello", [](const Request &, Response &res) {
  10154. res.set_content("api", "text/plain");
  10155. });
  10156. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. listen_thread.join();
  10160. ASSERT_FALSE(svr.is_running());
  10161. });
  10162. svr.wait_until_ready();
  10163. Client cli(HOST, PORT);
  10164. auto res = cli.Get("/dir/test.html");
  10165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10166. EXPECT_EQ(StatusCode::OK_200, res->status);
  10167. res = cli.Get("/api/hello");
  10168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10169. EXPECT_EQ(StatusCode::OK_200, res->status);
  10170. EXPECT_EQ("api", res->body);
  10171. }
  10172. TEST(MountTest, PathSegmentBoundary) {
  10173. Server svr;
  10174. svr.set_mount_point("/mount2", "./www2");
  10175. svr.set_mount_point("/", "./www");
  10176. auto port = svr.bind_to_any_port(HOST);
  10177. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10178. auto se = detail::scope_exit([&] {
  10179. svr.stop();
  10180. listen_thread.join();
  10181. ASSERT_FALSE(svr.is_running());
  10182. });
  10183. svr.wait_until_ready();
  10184. Client cli(HOST, port);
  10185. auto res = cli.Get("/mount2/dir/test.html");
  10186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10187. EXPECT_EQ(StatusCode::OK_200, res->status);
  10188. // "/mount2" must not match part-way through a path segment.
  10189. res = cli.Get("/mount2dir/test.html");
  10190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10192. // A mount point ending in '/' keeps matching every path below it.
  10193. res = cli.Get("/dir/test.html");
  10194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10195. EXPECT_EQ(StatusCode::OK_200, res->status);
  10196. }
  10197. TEST(MountTest, Redicect) {
  10198. Server svr;
  10199. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. listen_thread.join();
  10203. ASSERT_FALSE(svr.is_running());
  10204. });
  10205. svr.set_mount_point("/", "./www");
  10206. svr.wait_until_ready();
  10207. Client cli("localhost", PORT);
  10208. auto res = cli.Get("/dir/");
  10209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10210. EXPECT_EQ(StatusCode::OK_200, res->status);
  10211. res = cli.Get("/dir");
  10212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10213. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10214. res = cli.Get("/file");
  10215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10216. EXPECT_EQ(StatusCode::OK_200, res->status);
  10217. res = cli.Get("/file/");
  10218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10219. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10220. cli.set_follow_location(true);
  10221. res = cli.Get("/dir");
  10222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10223. EXPECT_EQ(StatusCode::OK_200, res->status);
  10224. }
  10225. TEST(MountTest, MultibytesPathName) {
  10226. Server svr;
  10227. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. svr.stop();
  10230. listen_thread.join();
  10231. ASSERT_FALSE(svr.is_running());
  10232. });
  10233. svr.set_mount_point("/", "./www");
  10234. svr.wait_until_ready();
  10235. Client cli("localhost", PORT);
  10236. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. EXPECT_EQ(StatusCode::OK_200, res->status);
  10239. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10240. }
  10241. #ifdef _WIN32
  10242. // Issue #2435: mmap::open() must succeed even when another handle holds
  10243. // the file open for writing (e.g. an active log file).
  10244. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10245. const char *path = "mmap_concurrent_writer_test.txt";
  10246. const char *content = "hello";
  10247. {
  10248. std::ofstream f(path, std::ios::binary);
  10249. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10250. }
  10251. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10252. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10253. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10254. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10255. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10256. detail::mmap m(path);
  10257. ASSERT_TRUE(m.is_open());
  10258. EXPECT_EQ(strlen(content), m.size());
  10259. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10260. }
  10261. #endif
  10262. #ifndef _WIN32
  10263. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10264. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10265. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10266. TEST(MmapTest, FailedMappingIsNotOpen) {
  10267. const char *path = "./mmap_failed_mapping_test_dir";
  10268. ASSERT_EQ(0, ::mkdir(path, 0755));
  10269. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10270. detail::mmap m(path);
  10271. EXPECT_FALSE(m.is_open());
  10272. EXPECT_EQ(0U, m.size());
  10273. EXPECT_NE(static_cast<const void *>(m.data()),
  10274. static_cast<const void *>(MAP_FAILED));
  10275. }
  10276. #endif
  10277. TEST(KeepAliveTest, ReadTimeout) {
  10278. Server svr;
  10279. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10280. std::this_thread::sleep_for(std::chrono::seconds(2));
  10281. res.set_content("a", "text/plain");
  10282. });
  10283. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10284. res.set_content("b", "text/plain");
  10285. });
  10286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10287. auto se = detail::scope_exit([&] {
  10288. svr.stop();
  10289. listen_thread.join();
  10290. ASSERT_FALSE(svr.is_running());
  10291. });
  10292. svr.wait_until_ready();
  10293. Client cli("localhost", PORT);
  10294. cli.set_keep_alive(true);
  10295. cli.set_read_timeout(std::chrono::seconds(1));
  10296. auto resa = cli.Get("/a");
  10297. ASSERT_FALSE(resa);
  10298. EXPECT_EQ(Error::Read, resa.error());
  10299. auto resb = cli.Get("/b");
  10300. ASSERT_TRUE(resb);
  10301. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10302. EXPECT_EQ("b", resb->body);
  10303. }
  10304. TEST(KeepAliveTest, MaxCount) {
  10305. size_t keep_alive_max_count = 3;
  10306. Server svr;
  10307. svr.set_keep_alive_max_count(keep_alive_max_count);
  10308. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10309. res.set_content("Hello World!", "text/plain");
  10310. });
  10311. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. listen_thread.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. Client cli(HOST, PORT);
  10319. cli.set_keep_alive(true);
  10320. for (size_t i = 0; i < 5; i++) {
  10321. auto result = cli.Get("/hi");
  10322. ASSERT_TRUE(result);
  10323. EXPECT_EQ(StatusCode::OK_200, result->status);
  10324. if (i == keep_alive_max_count - 1) {
  10325. EXPECT_EQ("close", result->get_header_value("Connection"));
  10326. } else {
  10327. EXPECT_FALSE(result->has_header("Connection"));
  10328. }
  10329. }
  10330. }
  10331. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10332. // can pull the next one into the server's buffer. The server must serve it
  10333. // without waiting for the socket to become readable again. The keep-alive
  10334. // timeout outlasts the client's read timeout, so a request left waiting for it
  10335. // shows up as a missing response.
  10336. static void serve_pipelining_routes(Server &svr,
  10337. const std::function<void(int)> &client) {
  10338. svr.set_keep_alive_timeout(5);
  10339. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10340. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10341. });
  10342. svr.Post("/echo", [](const Request &req, Response &res) {
  10343. res.set_content("echo " + req.body, "text/plain");
  10344. });
  10345. auto port = svr.bind_to_any_port(HOST);
  10346. thread t = thread([&] { svr.listen_after_bind(); });
  10347. auto se = detail::scope_exit([&] {
  10348. svr.stop();
  10349. t.join();
  10350. });
  10351. svr.wait_until_ready();
  10352. client(port);
  10353. }
  10354. static std::string
  10355. send_pipelined_requests(const std::vector<std::string> &parts) {
  10356. Server svr;
  10357. std::string res;
  10358. serve_pipelining_routes(svr, [&](int port) {
  10359. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10360. });
  10361. return res;
  10362. }
  10363. static void expect_in_order(const std::string &res,
  10364. const std::vector<std::string> &bodies) {
  10365. size_t pos = 0;
  10366. for (const auto &body : bodies) {
  10367. pos = res.find(body, pos);
  10368. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10369. pos += body.size();
  10370. }
  10371. }
  10372. TEST(KeepAliveTest, PipelinedRequests) {
  10373. auto res = send_pipelined_requests(
  10374. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10375. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10376. "Content-Length: 4\r\n\r\nbody"
  10377. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10378. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10379. }
  10380. // The second request starts in the server's buffer and ends on the socket.
  10381. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10382. auto res =
  10383. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10384. "GET /hi/2 HTTP/1.1\r\nHo",
  10385. "st: localhost\r\nConnection: close\r\n\r\n"});
  10386. expect_in_order(res, {"hi 1", "hi 2"});
  10387. }
  10388. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10389. // CRLF after a body does not turn into a 400 for the next request.
  10390. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10391. auto res = send_pipelined_requests(
  10392. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10393. "Content-Length: 4\r\n\r\nbody\r\n"
  10394. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10395. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10396. expect_in_order(res, {"echo body", "hi 2"});
  10397. }
  10398. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10399. // must not be served as the next request.
  10400. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10401. auto res = send_pipelined_requests(
  10402. {"INVALID REQUEST LINE\r\n\r\n"
  10403. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10404. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10405. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10406. }
  10407. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10408. // Over TLS, the next request is held by the TLS library as already decrypted
  10409. // data rather than on the socket.
  10410. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. std::string res;
  10413. serve_pipelining_routes(svr, [&](int port) {
  10414. // One part, so all three requests arrive in one TLS record
  10415. EXPECT_TRUE(send_ssl_request_in_parts(
  10416. 2,
  10417. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10418. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10419. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10420. &res, port));
  10421. });
  10422. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10423. }
  10424. #endif
  10425. TEST(KeepAliveTest, Issue1041) {
  10426. Server svr;
  10427. svr.set_keep_alive_timeout(3);
  10428. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10429. res.set_content("Hello World!", "text/plain");
  10430. });
  10431. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10432. auto se = detail::scope_exit([&] {
  10433. svr.stop();
  10434. listen_thread.join();
  10435. ASSERT_FALSE(svr.is_running());
  10436. });
  10437. svr.wait_until_ready();
  10438. Client cli(HOST, PORT);
  10439. cli.set_keep_alive(true);
  10440. auto result = cli.Get("/hi");
  10441. ASSERT_TRUE(result);
  10442. EXPECT_EQ(StatusCode::OK_200, result->status);
  10443. std::this_thread::sleep_for(std::chrono::seconds(5));
  10444. result = cli.Get("/hi");
  10445. ASSERT_TRUE(result);
  10446. EXPECT_EQ(StatusCode::OK_200, result->status);
  10447. }
  10448. TEST(KeepAliveTest, Issue1959) {
  10449. Server svr;
  10450. svr.set_keep_alive_timeout(5);
  10451. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10452. res.set_content("a", "text/plain");
  10453. });
  10454. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10455. auto se = detail::scope_exit([&] {
  10456. if (!svr.is_running()) return;
  10457. svr.stop();
  10458. listen_thread.join();
  10459. ASSERT_FALSE(svr.is_running());
  10460. });
  10461. svr.wait_until_ready();
  10462. Client cli("localhost", PORT);
  10463. cli.set_keep_alive(true);
  10464. using namespace std::chrono;
  10465. auto start = steady_clock::now();
  10466. cli.Get("/a");
  10467. svr.stop();
  10468. listen_thread.join();
  10469. auto end = steady_clock::now();
  10470. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10471. EXPECT_LT(elapsed, 5000);
  10472. }
  10473. #ifdef CPPHTTPLIB_SSL_ENABLED
  10474. TEST(KeepAliveTest, SSLClientReconnection) {
  10475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10476. ASSERT_TRUE(svr.is_valid());
  10477. svr.set_keep_alive_timeout(1);
  10478. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10479. res.set_content("Hello World!", "text/plain");
  10480. });
  10481. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10482. auto se = detail::scope_exit([&] {
  10483. svr.stop();
  10484. listen_thread.join();
  10485. ASSERT_FALSE(svr.is_running());
  10486. });
  10487. svr.wait_until_ready();
  10488. SSLClient cli(HOST, PORT);
  10489. cli.enable_server_certificate_verification(false);
  10490. cli.set_keep_alive(true);
  10491. auto result = cli.Get("/hi");
  10492. ASSERT_TRUE(result);
  10493. EXPECT_EQ(StatusCode::OK_200, result->status);
  10494. result = cli.Get("/hi");
  10495. ASSERT_TRUE(result);
  10496. EXPECT_EQ(StatusCode::OK_200, result->status);
  10497. std::this_thread::sleep_for(std::chrono::seconds(2));
  10498. // Recoonect
  10499. result = cli.Get("/hi");
  10500. ASSERT_TRUE(result);
  10501. EXPECT_EQ(StatusCode::OK_200, result->status);
  10502. result = cli.Get("/hi");
  10503. ASSERT_TRUE(result);
  10504. EXPECT_EQ(StatusCode::OK_200, result->status);
  10505. }
  10506. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10508. ASSERT_TRUE(svr.is_valid());
  10509. svr.set_keep_alive_timeout(1);
  10510. std::string content = "reconnect";
  10511. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10512. res.set_content("Hello World!", "text/plain");
  10513. });
  10514. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10515. auto se = detail::scope_exit([&] {
  10516. svr.stop();
  10517. listen_thread.join();
  10518. ASSERT_FALSE(svr.is_running());
  10519. });
  10520. svr.wait_until_ready();
  10521. SSLClient cli(HOST, PORT);
  10522. cli.enable_server_certificate_verification(false);
  10523. cli.set_keep_alive(true);
  10524. auto result = cli.Post(
  10525. "/hi", content.size(),
  10526. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10527. sink.write(content.c_str(), content.size());
  10528. return true;
  10529. },
  10530. "text/plain");
  10531. ASSERT_TRUE(result);
  10532. EXPECT_EQ(200, result->status);
  10533. std::this_thread::sleep_for(std::chrono::seconds(2));
  10534. // Recoonect
  10535. result = cli.Post(
  10536. "/hi", content.size(),
  10537. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10538. sink.write(content.c_str(), content.size());
  10539. return true;
  10540. },
  10541. "text/plain");
  10542. ASSERT_TRUE(result);
  10543. EXPECT_EQ(200, result->status);
  10544. result = cli.Post(
  10545. "/hi", content.size(),
  10546. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10547. sink.write(content.c_str(), content.size());
  10548. return true;
  10549. },
  10550. "text/plain");
  10551. ASSERT_TRUE(result);
  10552. EXPECT_EQ(200, result->status);
  10553. }
  10554. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10555. using namespace httplib::tls;
  10556. {
  10557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10558. ASSERT_TRUE(svr.is_valid());
  10559. svr.Get("/sni", [&](const Request &req, Response &res) {
  10560. std::string expected = req.sni();
  10561. EXPECT_EQ(expected, req.get_param_value("expected"));
  10562. res.set_content("ok", "text/plain");
  10563. });
  10564. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10565. auto se = detail::scope_exit([&] {
  10566. svr.stop();
  10567. listen_thread.join();
  10568. ASSERT_FALSE(svr.is_running());
  10569. });
  10570. svr.wait_until_ready();
  10571. {
  10572. SSLClient cli("localhost", PORT);
  10573. cli.enable_server_certificate_verification(false);
  10574. auto res = cli.Get("/sni?expected=localhost");
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. }
  10577. {
  10578. SSLClient cli("::1", PORT);
  10579. cli.enable_server_certificate_verification(false);
  10580. auto res = cli.Get("/sni?expected=");
  10581. // NOTE: This may fail if the server is listening on IPv4 only
  10582. // (e.g., when localhost resolves to 127.0.0.1 only)
  10583. if (res) {
  10584. EXPECT_EQ(StatusCode::OK_200, res->status);
  10585. } else {
  10586. EXPECT_EQ(Error::Connection, res.error());
  10587. }
  10588. }
  10589. }
  10590. }
  10591. #endif
  10592. TEST(ClientProblemDetectionTest, ContentProvider) {
  10593. Server svr;
  10594. size_t content_length = 1024 * 1024;
  10595. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10596. res.set_content_provider(
  10597. content_length, "text/plain",
  10598. [&](size_t offset, size_t length, DataSink &sink) {
  10599. auto out_len = std::min(length, static_cast<size_t>(1024));
  10600. std::string out(out_len, '@');
  10601. sink.write(out.data(), out_len);
  10602. return offset < 4096;
  10603. },
  10604. [](bool success) { ASSERT_FALSE(success); });
  10605. });
  10606. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10607. res.set_content_provider(
  10608. 0, "text/plain",
  10609. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10610. EXPECT_TRUE(false);
  10611. return true;
  10612. },
  10613. [](bool success) { ASSERT_FALSE(success); });
  10614. });
  10615. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10616. auto se = detail::scope_exit([&] {
  10617. svr.stop();
  10618. listen_thread.join();
  10619. ASSERT_FALSE(svr.is_running());
  10620. });
  10621. svr.wait_until_ready();
  10622. Client cli("localhost", PORT);
  10623. {
  10624. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10625. size_t /*data_length*/) { return false; });
  10626. ASSERT_FALSE(res);
  10627. }
  10628. {
  10629. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10630. size_t /*data_length*/) { return false; });
  10631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10632. }
  10633. }
  10634. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10635. // A provider that reports success without writing anything and without
  10636. // calling done() used to be handed the same offset and length again on every
  10637. // pass, so it spun for as long as the peer stayed connected.
  10638. Server svr;
  10639. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10640. res.set_content("ok", "text/plain");
  10641. });
  10642. auto port = svr.bind_to_any_port(HOST);
  10643. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10644. auto se = detail::scope_exit([&] {
  10645. svr.stop();
  10646. listen_thread.join();
  10647. ASSERT_FALSE(svr.is_running());
  10648. });
  10649. svr.wait_until_ready();
  10650. std::atomic<int> call_count{0};
  10651. Client cli(HOST, port);
  10652. auto res = cli.Post(
  10653. "/", 1024,
  10654. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10655. // Give up after enough passes to show the spin, so that losing the
  10656. // check below fails this test instead of hanging it.
  10657. return ++call_count < 100;
  10658. },
  10659. "text/plain");
  10660. ASSERT_FALSE(res);
  10661. EXPECT_EQ(Error::Write, res.error());
  10662. EXPECT_EQ(1, call_count.load());
  10663. }
  10664. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10665. // A writer only has to assign `write`. The other three used to be left as
  10666. // empty std::functions, so a provider calling one threw
  10667. // std::bad_function_call out of the thread running it and took the whole
  10668. // process down.
  10669. DataSink sink;
  10670. std::string written;
  10671. sink.write = [&](const char *data, size_t data_len) {
  10672. written.append(data, data_len);
  10673. return true;
  10674. };
  10675. EXPECT_TRUE(sink.is_writable());
  10676. sink.done();
  10677. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10678. EXPECT_TRUE(written.empty());
  10679. }
  10680. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10681. // A sink that cannot carry trailers still has to finish.
  10682. DataSink sink;
  10683. auto done_count = 0;
  10684. sink.done = [&]() { done_count++; };
  10685. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10686. EXPECT_EQ(1, done_count);
  10687. }
  10688. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10689. Server svr;
  10690. const std::string body(4096, 'x');
  10691. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10692. res.set_content_provider(body.size(), "text/plain",
  10693. [&](size_t offset, size_t length, DataSink &sink) {
  10694. sink.write(body.data() + offset, length);
  10695. sink.done();
  10696. return true;
  10697. });
  10698. });
  10699. auto port = svr.bind_to_any_port(HOST);
  10700. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10701. auto se = detail::scope_exit([&] {
  10702. svr.stop();
  10703. listen_thread.join();
  10704. ASSERT_FALSE(svr.is_running());
  10705. });
  10706. svr.wait_until_ready();
  10707. Client cli(HOST, port);
  10708. auto res = cli.Get("/");
  10709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10710. EXPECT_EQ(StatusCode::OK_200, res->status);
  10711. EXPECT_EQ(body, res->body);
  10712. }
  10713. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10714. Server svr;
  10715. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10716. res.set_content_provider(
  10717. 1024, "text/plain",
  10718. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10719. sink.write("hello", 5);
  10720. sink.done(); // short of the 1024 bytes the response promised
  10721. return true;
  10722. });
  10723. });
  10724. auto port = svr.bind_to_any_port(HOST);
  10725. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10726. auto se = detail::scope_exit([&] {
  10727. svr.stop();
  10728. listen_thread.join();
  10729. ASSERT_FALSE(svr.is_running());
  10730. });
  10731. svr.wait_until_ready();
  10732. Client cli(HOST, port);
  10733. cli.set_read_timeout(5, 0);
  10734. // The response is short of its Content-Length, so the client cannot read a
  10735. // complete body. What matters is that this returns at all: a no-op done()
  10736. // would leave the writer looping over a provider that never makes progress.
  10737. auto res = cli.Get("/");
  10738. EXPECT_FALSE(res);
  10739. }
  10740. // Read as the next response by a peer that sees it after a framed body.
  10741. static const std::string smuggled_response =
  10742. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10743. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10744. Server svr;
  10745. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10746. res.set_content_provider(
  10747. 5, "text/plain",
  10748. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10749. auto data = "AAAAA" + smuggled_response;
  10750. sink.write(data.data(), data.size());
  10751. return true;
  10752. });
  10753. });
  10754. thread t = thread([&] { svr.listen(HOST, PORT); });
  10755. auto se = detail::scope_exit([&] {
  10756. svr.stop();
  10757. t.join();
  10758. ASSERT_FALSE(svr.is_running());
  10759. });
  10760. svr.wait_until_ready();
  10761. std::string resp;
  10762. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10763. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10764. resp.clear();
  10765. ASSERT_TRUE(send_request(
  10766. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10767. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10768. }
  10769. TEST(NoContentTest, BodyIsNotSent) {
  10770. Server svr;
  10771. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10772. res.status = StatusCode::NoContent_204;
  10773. res.set_content(smuggled_response, "text/plain");
  10774. });
  10775. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10776. res.status = StatusCode::NotModified_304;
  10777. res.set_chunked_content_provider(
  10778. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10779. sink.write(smuggled_response.data(), smuggled_response.size());
  10780. sink.done();
  10781. return true;
  10782. });
  10783. });
  10784. thread t = thread([&] { svr.listen(HOST, PORT); });
  10785. auto se = detail::scope_exit([&] {
  10786. svr.stop();
  10787. t.join();
  10788. ASSERT_FALSE(svr.is_running());
  10789. });
  10790. svr.wait_until_ready();
  10791. for (auto path : {"/204", "/304"}) {
  10792. std::string resp;
  10793. ASSERT_TRUE(send_request(
  10794. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10795. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10796. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10797. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10798. }
  10799. }
  10800. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10801. Server svr;
  10802. std::atomic<bool> smuggled(false);
  10803. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10804. res.set_content("ok", "text/plain");
  10805. });
  10806. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10807. smuggled = true;
  10808. });
  10809. auto port = svr.bind_to_any_port(HOST);
  10810. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. listen_thread.join();
  10814. ASSERT_FALSE(svr.is_running());
  10815. });
  10816. svr.wait_until_ready();
  10817. // What follows the body would be read as the next request.
  10818. Client cli(HOST, port);
  10819. auto res = cli.Post(
  10820. "/", 5,
  10821. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10822. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10823. sink.write(data.data(), data.size());
  10824. return true;
  10825. },
  10826. "text/plain");
  10827. ASSERT_FALSE(res);
  10828. EXPECT_EQ(Error::Write, res.error());
  10829. EXPECT_FALSE(smuggled);
  10830. }
  10831. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10832. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10833. // The compressed path builds the whole body before connecting, so this
  10834. // fails client-side and never reaches a server.
  10835. Client cli(HOST, PORT);
  10836. cli.set_compress(true);
  10837. auto res = cli.Post(
  10838. "/", 1024,
  10839. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10840. sink.write("hello", 5);
  10841. sink.done(); // short of the 1024 bytes the request announced
  10842. return true;
  10843. },
  10844. "text/plain");
  10845. ASSERT_FALSE(res);
  10846. EXPECT_EQ(Error::Write, res.error());
  10847. }
  10848. #endif
  10849. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10850. Server svr;
  10851. svr.set_error_handler([](Request const &, Response &res) -> void {
  10852. res.set_chunked_content_provider(
  10853. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10854. sink.os << "hello";
  10855. sink.os << "world";
  10856. sink.done();
  10857. return true;
  10858. });
  10859. });
  10860. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10861. auto se = detail::scope_exit([&] {
  10862. svr.stop();
  10863. listen_thread.join();
  10864. ASSERT_FALSE(svr.is_running());
  10865. });
  10866. svr.wait_until_ready();
  10867. Client cli("localhost", PORT);
  10868. auto res = cli.Get("/");
  10869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10871. EXPECT_EQ("helloworld", res->body);
  10872. }
  10873. // A body set after a content provider must replace it, not be sent through it.
  10874. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10875. Server svr;
  10876. svr.set_mount_point("/", "./www");
  10877. svr.set_file_request_handler([](const Request &req, Response &res) {
  10878. if (req.path == "/dir/test.html") {
  10879. res.status = StatusCode::Forbidden_403;
  10880. res.set_content(std::string(5000, 'D'), "text/plain");
  10881. } else if (req.path == "/file") {
  10882. res.status = StatusCode::Forbidden_403;
  10883. res.body = "Denied";
  10884. }
  10885. });
  10886. auto port = svr.bind_to_any_port(HOST);
  10887. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10888. auto se = detail::scope_exit([&] {
  10889. svr.stop();
  10890. t.join();
  10891. ASSERT_FALSE(svr.is_running());
  10892. });
  10893. svr.wait_until_ready();
  10894. Client cli(HOST, port);
  10895. {
  10896. auto res = cli.Get("/dir/test.html");
  10897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10898. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10899. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10900. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10901. }
  10902. {
  10903. auto res = cli.Get("/file");
  10904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10905. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10906. EXPECT_EQ("Denied", res->body);
  10907. }
  10908. {
  10909. auto res = cli.Get("/dir/index.html");
  10910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10911. EXPECT_EQ(StatusCode::OK_200, res->status);
  10912. EXPECT_EQ(0U, res->body.find("<html>"));
  10913. }
  10914. }
  10915. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10916. Server svr;
  10917. std::vector<bool> released;
  10918. std::mutex released_mutex;
  10919. auto releaser = [&](bool success) {
  10920. std::lock_guard<std::mutex> guard(released_mutex);
  10921. released.push_back(success);
  10922. };
  10923. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10924. return sink.write(&"hello"[offset], length);
  10925. };
  10926. svr.Get("/sized", [&](const Request &, Response &res) {
  10927. res.status = StatusCode::NotFound_404;
  10928. res.set_content_provider(5, "text/plain", provider, releaser);
  10929. });
  10930. svr.Get("/chunked", [&](const Request &, Response &res) {
  10931. res.status = StatusCode::ServiceUnavailable_503;
  10932. res.set_chunked_content_provider(
  10933. "text/plain",
  10934. [](size_t, DataSink &sink) {
  10935. sink.os << "chunk";
  10936. sink.done();
  10937. return true;
  10938. },
  10939. releaser);
  10940. });
  10941. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10942. res.set_content_provider(5, "text/plain", provider, releaser);
  10943. throw std::runtime_error("after the provider");
  10944. });
  10945. svr.set_error_handler([](const Request &req, Response &res) {
  10946. // Leave the exception handler's content to it.
  10947. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10948. res.set_content(std::string(1000, 'E'), "text/html");
  10949. return Server::HandlerResponse::Handled;
  10950. });
  10951. svr.set_exception_handler(
  10952. [](const Request &, Response &res, std::exception_ptr) {
  10953. res.status = StatusCode::InternalServerError_500;
  10954. res.set_content(std::string(1000, 'X'), "text/html");
  10955. });
  10956. auto port = svr.bind_to_any_port(HOST);
  10957. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10958. auto se = detail::scope_exit([&] {
  10959. svr.stop();
  10960. t.join();
  10961. ASSERT_FALSE(svr.is_running());
  10962. });
  10963. svr.wait_until_ready();
  10964. Client cli(HOST, port);
  10965. {
  10966. auto res = cli.Get("/sized");
  10967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10968. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10969. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10970. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10971. }
  10972. {
  10973. auto res = cli.Get("/chunked");
  10974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10975. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10976. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10977. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10978. }
  10979. {
  10980. auto res = cli.Get("/throw");
  10981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10982. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10983. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10984. }
  10985. std::lock_guard<std::mutex> guard(released_mutex);
  10986. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10987. }
  10988. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10989. Server svr;
  10990. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10991. return sink.write(&"abc"[offset], length);
  10992. };
  10993. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10994. res.set_file_content("./www/dir/test.html");
  10995. res.set_content("body", "text/plain");
  10996. });
  10997. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10998. res.set_content(std::string(100, 'B'), "text/plain");
  10999. res.set_file_content("./www/dir/test.html");
  11000. });
  11001. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11002. res.set_content(std::string(100, 'B'), "text/plain");
  11003. res.set_content_provider(3, "text/plain", abc);
  11004. });
  11005. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11006. res.set_content_provider(3, "text/plain", abc);
  11007. res.set_content(std::string(100, 'B'), "text/plain");
  11008. });
  11009. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11010. res.set_content_provider(3, "text/plain", abc);
  11011. res.body = "direct";
  11012. });
  11013. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11014. res.set_file_content("./www/dir/test.html");
  11015. res.body = "direct";
  11016. });
  11017. auto port = svr.bind_to_any_port(HOST);
  11018. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11019. auto se = detail::scope_exit([&] {
  11020. svr.stop();
  11021. t.join();
  11022. ASSERT_FALSE(svr.is_running());
  11023. });
  11024. svr.wait_until_ready();
  11025. Client cli(HOST, port);
  11026. auto expect_body = [&](const char *path, const std::string &body) {
  11027. // Uncompressed, so Content-Length can be compared with the body.
  11028. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11029. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11030. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11031. EXPECT_EQ(body, res->body) << path;
  11032. EXPECT_EQ(std::to_string(body.size()),
  11033. res->get_header_value("Content-Length"))
  11034. << path;
  11035. };
  11036. expect_body("/file-then-body", "body");
  11037. expect_body("/body-then-file", "test.html");
  11038. expect_body("/body-then-provider", "abc");
  11039. expect_body("/provider-then-body", std::string(100, 'B'));
  11040. expect_body("/provider-then-direct-body", "direct");
  11041. expect_body("/file-then-direct-body", "direct");
  11042. // Ranges are checked against the body, not the dropped provider.
  11043. {
  11044. auto res = cli.Get("/provider-then-direct-body",
  11045. Headers{{make_range_header({{1, 2}})}});
  11046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11048. EXPECT_EQ("ir", res->body);
  11049. }
  11050. {
  11051. auto res = cli.Get("/file-then-direct-body",
  11052. Headers{{make_range_header({{7, 8}})}});
  11053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11055. }
  11056. }
  11057. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11058. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11059. const char *path = "./truncated_while_served.txt";
  11060. const size_t size = 32 * 1024 * 1024;
  11061. {
  11062. std::ofstream f(path, std::ios::binary);
  11063. f << std::string(size, 'x');
  11064. }
  11065. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11066. // Over TLS, where the bytes are encrypted in this process rather than
  11067. // copied by send().
  11068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11069. svr.Get("/file", [&](const Request &, Response &res) {
  11070. res.set_file_content(path, "text/plain");
  11071. });
  11072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11073. auto se = detail::scope_exit([&] {
  11074. svr.stop();
  11075. thread.join();
  11076. ASSERT_FALSE(svr.is_running());
  11077. });
  11078. svr.wait_until_ready();
  11079. // The file shrinks once the first bytes are in, as a rewrite in place
  11080. // would, and reading the mapping past its new end used to raise SIGBUS.
  11081. SSLClient cli(HOST, PORT);
  11082. cli.enable_server_certificate_verification(false);
  11083. size_t received = 0;
  11084. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11085. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11086. received += len;
  11087. return true;
  11088. });
  11089. EXPECT_FALSE(res);
  11090. EXPECT_LT(received, size);
  11091. }
  11092. #endif
  11093. // Forward declaration (see the base64_encode note).
  11094. namespace httplib {
  11095. namespace detail {
  11096. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11097. const std::string &content_type,
  11098. EncodingType encoding);
  11099. } // namespace detail
  11100. } // namespace httplib
  11101. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11102. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11103. ASSERT_TRUE(mm->is_open());
  11104. Response res;
  11105. detail::set_file_content_provider(res, mm, "text/html",
  11106. detail::EncodingType::None);
  11107. std::string out;
  11108. DataSink sink;
  11109. sink.write = [&](const char *d, size_t l) {
  11110. out.append(d, l);
  11111. return true;
  11112. };
  11113. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11114. EXPECT_EQ("test.html", out);
  11115. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11116. EXPECT_EQ("test.html", out);
  11117. }
  11118. TEST(LongPollingTest, ClientCloseDetection) {
  11119. Server svr;
  11120. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11121. res.set_chunked_content_provider(
  11122. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11123. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11124. sink.os << "hello";
  11125. auto count = 10;
  11126. while (count > 0 && sink.is_writable()) {
  11127. this_thread::sleep_for(chrono::milliseconds(10));
  11128. count--;
  11129. }
  11130. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11131. return true;
  11132. });
  11133. });
  11134. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11135. auto se = detail::scope_exit([&] {
  11136. svr.stop();
  11137. listen_thread.join();
  11138. ASSERT_FALSE(svr.is_running());
  11139. });
  11140. svr.wait_until_ready();
  11141. Client cli("localhost", PORT);
  11142. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11143. EXPECT_EQ("hello", string(data, data_length));
  11144. return false; // close the socket immediately.
  11145. });
  11146. ASSERT_FALSE(res);
  11147. }
  11148. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11149. Server svr;
  11150. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11151. res.set_chunked_content_provider(
  11152. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11153. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11154. sink.os << "hello";
  11155. EXPECT_TRUE(sink.os.good());
  11156. // Wait for the client to close the connection
  11157. auto count = 10;
  11158. while (count > 0 && sink.is_writable()) {
  11159. this_thread::sleep_for(chrono::milliseconds(10));
  11160. count--;
  11161. }
  11162. // After client disconnect, write repeatedly until the socket
  11163. // write actually fails (small writes may be absorbed by the
  11164. // kernel buffer)
  11165. std::string chunk(1024, 'x');
  11166. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11167. sink.os << chunk;
  11168. }
  11169. EXPECT_TRUE(sink.os.fail());
  11170. return true;
  11171. });
  11172. });
  11173. auto port = svr.bind_to_any_port("localhost");
  11174. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11175. auto se = detail::scope_exit([&] {
  11176. svr.stop();
  11177. listen_thread.join();
  11178. ASSERT_FALSE(svr.is_running());
  11179. });
  11180. svr.wait_until_ready();
  11181. Client cli("localhost", port);
  11182. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11183. EXPECT_EQ("hello", string(data, data_length));
  11184. return false; // close the socket immediately.
  11185. });
  11186. ASSERT_FALSE(res);
  11187. }
  11188. TEST(GetWithParametersTest, GetWithParameters) {
  11189. Server svr;
  11190. svr.Get("/", [&](const Request &req, Response &) {
  11191. EXPECT_EQ("world", req.get_param_value("hello"));
  11192. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11193. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11194. });
  11195. svr.Get("/params", [&](const Request &req, Response &) {
  11196. EXPECT_EQ("world", req.get_param_value("hello"));
  11197. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11198. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11199. });
  11200. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11201. EXPECT_EQ("resource-id", req.matches[1]);
  11202. EXPECT_EQ("foo", req.get_param_value("param1"));
  11203. EXPECT_EQ("bar", req.get_param_value("param2"));
  11204. });
  11205. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11206. EXPECT_EQ("user-id", req.path_params.at("id"));
  11207. EXPECT_EQ("foo", req.get_param_value("param1"));
  11208. EXPECT_EQ("bar", req.get_param_value("param2"));
  11209. });
  11210. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11211. auto se = detail::scope_exit([&] {
  11212. svr.stop();
  11213. listen_thread.join();
  11214. ASSERT_FALSE(svr.is_running());
  11215. });
  11216. svr.wait_until_ready();
  11217. {
  11218. Client cli(HOST, PORT);
  11219. Params params;
  11220. params.emplace("hello", "world");
  11221. params.emplace("hello2", "world2");
  11222. params.emplace("hello3", "world3");
  11223. auto res = cli.Get("/", params, Headers{});
  11224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11225. EXPECT_EQ(StatusCode::OK_200, res->status);
  11226. }
  11227. {
  11228. Client cli(HOST, PORT);
  11229. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. EXPECT_EQ(StatusCode::OK_200, res->status);
  11232. }
  11233. {
  11234. Client cli(HOST, PORT);
  11235. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11237. EXPECT_EQ(StatusCode::OK_200, res->status);
  11238. }
  11239. {
  11240. Client cli(HOST, PORT);
  11241. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11243. EXPECT_EQ(StatusCode::OK_200, res->status);
  11244. }
  11245. }
  11246. TEST(GetWithParametersTest, GetWithParameters2) {
  11247. Server svr;
  11248. svr.Get("/", [&](const Request &req, Response &res) {
  11249. auto text = req.get_param_value("hello");
  11250. res.set_content(text, "text/plain");
  11251. });
  11252. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11253. auto se = detail::scope_exit([&] {
  11254. svr.stop();
  11255. listen_thread.join();
  11256. ASSERT_FALSE(svr.is_running());
  11257. });
  11258. svr.wait_until_ready();
  11259. Client cli("localhost", PORT);
  11260. Params params;
  11261. params.emplace("hello", "world");
  11262. std::string body;
  11263. auto res = cli.Get("/", params, Headers{},
  11264. [&](const char *data, size_t data_length) {
  11265. body.append(data, data_length);
  11266. return true;
  11267. });
  11268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11269. EXPECT_EQ(StatusCode::OK_200, res->status);
  11270. EXPECT_EQ("world", body);
  11271. }
  11272. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11273. Server svr;
  11274. svr.Get("/search", [&](const Request &req, Response &res) {
  11275. auto q = req.get_param_value("q");
  11276. res.set_content(q, "text/plain");
  11277. });
  11278. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11279. auto se = detail::scope_exit([&] {
  11280. svr.stop();
  11281. listen_thread.join();
  11282. ASSERT_FALSE(svr.is_running());
  11283. });
  11284. svr.wait_until_ready();
  11285. Client cli("localhost", PORT);
  11286. // Verify that Get(path, params) works without requiring Headers argument
  11287. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11289. EXPECT_EQ(StatusCode::OK_200, res->status);
  11290. EXPECT_EQ("cpp-httplib", res->body);
  11291. }
  11292. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11293. auto host = "httpbingo.org";
  11294. auto path = std::string{"/range/32"};
  11295. #ifdef CPPHTTPLIB_SSL_ENABLED
  11296. SSLClient cli(host);
  11297. #else
  11298. Client cli(host);
  11299. #endif
  11300. cli.set_default_headers({make_range_header({{1, 10}})});
  11301. cli.set_connection_timeout(5);
  11302. {
  11303. auto res = cli.Get(path);
  11304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11305. EXPECT_EQ("bcdefghijk", res->body);
  11306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11307. }
  11308. {
  11309. auto res = cli.Get(path);
  11310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11311. EXPECT_EQ("bcdefghijk", res->body);
  11312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11313. }
  11314. }
  11315. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11316. Server svr;
  11317. svr.set_default_headers({{"Hello", "World"}});
  11318. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11319. res.set_content("ok", "text/plain");
  11320. });
  11321. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11322. auto se = detail::scope_exit([&] {
  11323. svr.stop();
  11324. listen_thread.join();
  11325. ASSERT_FALSE(svr.is_running());
  11326. });
  11327. svr.wait_until_ready();
  11328. Client cli("localhost", PORT);
  11329. auto res = cli.Get("/");
  11330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11331. EXPECT_EQ(StatusCode::OK_200, res->status);
  11332. EXPECT_EQ("ok", res->body);
  11333. EXPECT_EQ("World", res->get_header_value("Hello"));
  11334. }
  11335. #ifdef CPPHTTPLIB_SSL_ENABLED
  11336. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11338. ASSERT_TRUE(svr.is_valid());
  11339. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11340. std::this_thread::sleep_for(std::chrono::seconds(2));
  11341. res.set_content("a", "text/plain");
  11342. });
  11343. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11344. res.set_content("b", "text/plain");
  11345. });
  11346. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11347. auto se = detail::scope_exit([&] {
  11348. svr.stop();
  11349. listen_thread.join();
  11350. ASSERT_FALSE(svr.is_running());
  11351. });
  11352. svr.wait_until_ready();
  11353. SSLClient cli("localhost", PORT);
  11354. cli.enable_server_certificate_verification(false);
  11355. cli.set_keep_alive(true);
  11356. cli.set_read_timeout(std::chrono::seconds(1));
  11357. auto resa = cli.Get("/a");
  11358. ASSERT_TRUE(!resa);
  11359. EXPECT_EQ(Error::Read, resa.error());
  11360. auto resb = cli.Get("/b");
  11361. ASSERT_TRUE(resb);
  11362. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11363. EXPECT_EQ("b", resb->body);
  11364. }
  11365. // Closing an idle keep-alive connection sends close_notify and returns. The
  11366. // server must not wait for the client's close_notify: an idle client never
  11367. // sends one, so the worker would be held until the read timeout expires, and
  11368. // stop() would wait for it.
  11369. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11371. ASSERT_TRUE(svr.is_valid());
  11372. svr.set_keep_alive_timeout(1);
  11373. svr.set_read_timeout(10, 0);
  11374. svr.Get("/", [](const Request &, Response &res) {
  11375. res.set_content("ok", "text/plain");
  11376. });
  11377. auto port = svr.bind_to_any_port(HOST);
  11378. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11379. auto se = detail::scope_exit([&] {
  11380. if (listen_thread.joinable()) {
  11381. svr.stop();
  11382. listen_thread.join();
  11383. }
  11384. });
  11385. svr.wait_until_ready();
  11386. SSLClient cli(HOST, port);
  11387. cli.enable_server_certificate_verification(false);
  11388. cli.set_keep_alive(true);
  11389. auto res = cli.Get("/");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. // Stay idle past the keep-alive timeout so the server closes the connection.
  11393. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11394. auto start = std::chrono::steady_clock::now();
  11395. svr.stop();
  11396. listen_thread.join();
  11397. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11398. std::chrono::steady_clock::now() - start)
  11399. .count();
  11400. EXPECT_LT(elapsed, 3000);
  11401. }
  11402. #endif
  11403. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11404. protected:
  11405. ServerTestWithAI_PASSIVE()
  11406. : cli_(HOST, PORT)
  11407. #ifdef CPPHTTPLIB_SSL_ENABLED
  11408. ,
  11409. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11410. #endif
  11411. {
  11412. #ifdef CPPHTTPLIB_SSL_ENABLED
  11413. cli_.enable_server_certificate_verification(false);
  11414. #endif
  11415. }
  11416. virtual void SetUp() {
  11417. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11418. res.set_content("Hello World!", "text/plain");
  11419. });
  11420. t_ = thread(
  11421. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11422. svr_.wait_until_ready();
  11423. }
  11424. virtual void TearDown() {
  11425. svr_.stop();
  11426. t_.join();
  11427. }
  11428. #ifdef CPPHTTPLIB_SSL_ENABLED
  11429. SSLClient cli_;
  11430. SSLServer svr_;
  11431. #else
  11432. Client cli_;
  11433. Server svr_;
  11434. #endif
  11435. thread t_;
  11436. };
  11437. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11438. auto res = cli_.Get("/hi");
  11439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11440. EXPECT_EQ(StatusCode::OK_200, res->status);
  11441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11442. EXPECT_EQ("Hello World!", res->body);
  11443. }
  11444. class ServerUpDownTest : public ::testing::Test {
  11445. protected:
  11446. ServerUpDownTest() : cli_(HOST, PORT) {}
  11447. virtual void SetUp() {
  11448. t_ = thread([&]() {
  11449. svr_.bind_to_any_port(HOST);
  11450. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11451. ASSERT_TRUE(svr_.listen_after_bind());
  11452. });
  11453. svr_.wait_until_ready();
  11454. }
  11455. virtual void TearDown() {
  11456. svr_.stop();
  11457. t_.join();
  11458. }
  11459. Client cli_;
  11460. Server svr_;
  11461. thread t_;
  11462. };
  11463. TEST_F(ServerUpDownTest, QuickStartStop) {
  11464. // Should not crash, especially when run with
  11465. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11466. }
  11467. class PayloadMaxLengthTest : public ::testing::Test {
  11468. protected:
  11469. PayloadMaxLengthTest()
  11470. : cli_(HOST, PORT)
  11471. #ifdef CPPHTTPLIB_SSL_ENABLED
  11472. ,
  11473. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11474. #endif
  11475. {
  11476. #ifdef CPPHTTPLIB_SSL_ENABLED
  11477. cli_.enable_server_certificate_verification(false);
  11478. #endif
  11479. }
  11480. virtual void SetUp() {
  11481. svr_.set_payload_max_length(8);
  11482. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11483. res.set_content("test", "text/plain");
  11484. });
  11485. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11486. svr_.wait_until_ready();
  11487. }
  11488. virtual void TearDown() {
  11489. svr_.stop();
  11490. t_.join();
  11491. }
  11492. #ifdef CPPHTTPLIB_SSL_ENABLED
  11493. SSLClient cli_;
  11494. SSLServer svr_;
  11495. #else
  11496. Client cli_;
  11497. Server svr_;
  11498. #endif
  11499. thread t_;
  11500. };
  11501. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11502. auto res = cli_.Post("/test", "123456789", "text/plain");
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11505. res = cli_.Post("/test", "12345678", "text/plain");
  11506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11507. EXPECT_EQ(StatusCode::OK_200, res->status);
  11508. }
  11509. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11510. // Test chunked encoding with payload exceeding the 8-byte limit
  11511. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11512. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11514. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11515. }
  11516. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11517. // Test chunked encoding with payload within the 8-byte limit
  11518. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11519. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11521. EXPECT_EQ(StatusCode::OK_200, res->status);
  11522. }
  11523. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11524. // Test using send_request to send chunked data exceeding payload limit
  11525. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11526. "Host: " +
  11527. std::string(HOST) + ":" + std::to_string(PORT) +
  11528. "\r\n"
  11529. "Transfer-Encoding: chunked\r\n"
  11530. "Connection: close\r\n"
  11531. "\r\n"
  11532. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11533. "0123456789\r\n"
  11534. "0\r\n" // End chunk
  11535. "\r\n";
  11536. std::string response;
  11537. bool result = send_request(1, chunked_request, &response);
  11538. if (!result) {
  11539. // If send_request fails, it might be because the server closed the
  11540. // connection due to payload limit enforcement, which is acceptable
  11541. SUCCEED()
  11542. << "Server rejected oversized chunked request (connection closed)";
  11543. } else {
  11544. // If we got a response, check if it's an error response or connection was
  11545. // closed early Short response length indicates connection was closed due to
  11546. // payload limit
  11547. if (response.length() <= 10) {
  11548. SUCCEED() << "Server closed connection for oversized chunked request";
  11549. } else {
  11550. // Check for error status codes
  11551. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11552. response.find("Payload Too Large") != std::string::npos ||
  11553. response.find("400") != std::string::npos);
  11554. }
  11555. }
  11556. }
  11557. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11558. // Test request without Content-Length header exceeding payload limit
  11559. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11560. "Host: " +
  11561. std::string(HOST) + ":" +
  11562. std::to_string(PORT) +
  11563. "\r\n"
  11564. "Connection: close\r\n"
  11565. "\r\n";
  11566. // Add payload exceeding the 8-byte limit
  11567. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11568. request_without_content_length += large_payload;
  11569. std::string response;
  11570. bool result = send_request(1, request_without_content_length, &response);
  11571. if (!result) {
  11572. // If send_request fails, server likely closed connection due to payload
  11573. // limit
  11574. SUCCEED() << "Server rejected oversized request without Content-Length "
  11575. "(connection closed)";
  11576. } else {
  11577. // Check if server responded with error or closed connection early
  11578. if (response.length() <= 10) {
  11579. SUCCEED() << "Server closed connection for oversized request without "
  11580. "Content-Length";
  11581. } else {
  11582. // Check for error status codes
  11583. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11584. response.find("Payload Too Large") != std::string::npos ||
  11585. response.find("400") != std::string::npos);
  11586. }
  11587. }
  11588. }
  11589. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11590. // Test request without Content-Length header within payload limit
  11591. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11592. "Host: " +
  11593. std::string(HOST) + ":" +
  11594. std::to_string(PORT) +
  11595. "\r\n"
  11596. "Connection: close\r\n"
  11597. "\r\n";
  11598. // Add payload within the 8-byte limit
  11599. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11600. request_without_content_length += small_payload;
  11601. std::string response;
  11602. bool result = send_request(1, request_without_content_length, &response);
  11603. // For requests without Content-Length, the server may have different behavior
  11604. // The key is that it should not reject due to payload limit for small
  11605. // payloads
  11606. if (result) {
  11607. // Check for any HTTP response (success or error, but not connection closed)
  11608. if (response.length() > 10) {
  11609. SUCCEED()
  11610. << "Server processed request without Content-Length within limit";
  11611. } else {
  11612. // Short response might indicate connection closed, which is acceptable
  11613. SUCCEED() << "Server closed connection for request without "
  11614. "Content-Length (acceptable behavior)";
  11615. }
  11616. } else {
  11617. // Connection failure might be due to protocol requirements
  11618. SUCCEED() << "Connection issue with request without Content-Length "
  11619. "(environment-specific)";
  11620. }
  11621. }
  11622. class LargePayloadMaxLengthTest : public ::testing::Test {
  11623. protected:
  11624. LargePayloadMaxLengthTest()
  11625. : cli_(HOST, PORT)
  11626. #ifdef CPPHTTPLIB_SSL_ENABLED
  11627. ,
  11628. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11629. #endif
  11630. {
  11631. #ifdef CPPHTTPLIB_SSL_ENABLED
  11632. cli_.enable_server_certificate_verification(false);
  11633. #endif
  11634. }
  11635. virtual void SetUp() {
  11636. // Set 10MB payload limit
  11637. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11638. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11639. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11640. res.set_content("Large payload test", "text/plain");
  11641. });
  11642. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11643. svr_.wait_until_ready();
  11644. }
  11645. virtual void TearDown() {
  11646. svr_.stop();
  11647. t_.join();
  11648. }
  11649. #ifdef CPPHTTPLIB_SSL_ENABLED
  11650. SSLClient cli_;
  11651. SSLServer svr_;
  11652. #else
  11653. Client cli_;
  11654. Server svr_;
  11655. #endif
  11656. thread t_;
  11657. };
  11658. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11659. // Test chunked encoding with payload within 10MB limit
  11660. std::string medium_payload(5 * 1024 * 1024,
  11661. 'A'); // 5MB payload, within 10MB limit
  11662. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. EXPECT_EQ(StatusCode::OK_200, res->status);
  11665. }
  11666. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11667. // Test chunked encoding with payload exceeding 10MB limit
  11668. std::string large_payload(12 * 1024 * 1024,
  11669. 'B'); // 12MB payload, exceeds 10MB limit
  11670. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11671. // Server may either return 413 or close the connection
  11672. if (res) {
  11673. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11674. } else {
  11675. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11676. }
  11677. }
  11678. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11679. // Test request without Content-Length header within 10MB limit
  11680. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11681. "Host: " +
  11682. std::string(HOST) + ":" +
  11683. std::to_string(PORT) +
  11684. "\r\n"
  11685. "Connection: close\r\n"
  11686. "\r\n";
  11687. // Add 1MB payload (within 10MB limit)
  11688. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11689. request_without_content_length += medium_payload;
  11690. std::string response;
  11691. bool result = send_request(5, request_without_content_length, &response);
  11692. if (result) {
  11693. // Should get a proper HTTP response for payloads within limit
  11694. if (response.length() > 10) {
  11695. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11696. "10MB limit";
  11697. } else {
  11698. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11699. "Content-Length)";
  11700. }
  11701. } else {
  11702. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11703. }
  11704. }
  11705. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11706. // Test request without Content-Length header exceeding 10MB limit
  11707. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11708. "Host: " +
  11709. std::string(HOST) + ":" +
  11710. std::to_string(PORT) +
  11711. "\r\n"
  11712. "Connection: close\r\n"
  11713. "\r\n";
  11714. // Add 12MB payload (exceeds 10MB limit)
  11715. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11716. request_without_content_length += large_payload;
  11717. std::string response;
  11718. bool result = send_request(10, request_without_content_length, &response);
  11719. if (!result) {
  11720. // Server should close connection due to payload limit
  11721. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11722. "(connection closed)";
  11723. } else {
  11724. // Check for error response
  11725. if (response.length() <= 10) {
  11726. SUCCEED()
  11727. << "Server closed connection for 12MB request exceeding 10MB limit";
  11728. } else {
  11729. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11730. response.find("Payload Too Large") != std::string::npos ||
  11731. response.find("400") != std::string::npos);
  11732. }
  11733. }
  11734. }
  11735. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11736. Server svr;
  11737. svr.Get("/", [](const Request &, Response &res) {
  11738. // Claims far more than it sends, then drops the connection.
  11739. res.set_content_provider(size_t(1) << 41, "text/plain",
  11740. [](size_t, size_t, DataSink &sink) {
  11741. sink.write("abc", 3);
  11742. return false;
  11743. });
  11744. });
  11745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11746. auto se = detail::scope_exit([&] {
  11747. svr.stop();
  11748. thread.join();
  11749. ASSERT_FALSE(svr.is_running());
  11750. });
  11751. svr.wait_until_ready();
  11752. Client cli(HOST, PORT);
  11753. cli.set_payload_max_length(0);
  11754. EXPECT_FALSE(cli.Get("/"));
  11755. }
  11756. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11757. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11758. // path.
  11759. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11760. Server svr;
  11761. const size_t LIMIT = 64 * 1024; // 64KB
  11762. svr.set_payload_max_length(LIMIT);
  11763. size_t total = 0;
  11764. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11765. const ContentReader &content_reader) {
  11766. content_reader([&](const char * /*data*/, size_t len) {
  11767. total += len;
  11768. return true;
  11769. });
  11770. res.status = 200;
  11771. res.set_content("stream_ok", "text/plain");
  11772. });
  11773. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11774. auto se = detail::scope_exit([&] {
  11775. svr.stop();
  11776. thread.join();
  11777. ASSERT_FALSE(svr.is_running());
  11778. });
  11779. svr.wait_until_ready();
  11780. // Prepare 256KB raw data and gzip-compress it
  11781. std::string raw(256 * 1024, 'A');
  11782. std::string gz;
  11783. {
  11784. z_stream zs{};
  11785. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11786. Z_DEFAULT_STRATEGY);
  11787. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11788. zs.avail_in = static_cast<uInt>(raw.size());
  11789. char outbuf[4096];
  11790. int ret;
  11791. do {
  11792. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11793. zs.avail_out = sizeof(outbuf);
  11794. ret = deflate(&zs, Z_FINISH);
  11795. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11796. } while (ret != Z_STREAM_END);
  11797. deflateEnd(&zs);
  11798. }
  11799. Client cli(HOST, PORT);
  11800. cli.set_connection_timeout(std::chrono::seconds(5));
  11801. Headers headers = {{"Content-Encoding", "gzip"}};
  11802. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11803. "application/octet-stream");
  11804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11805. // Server must reject oversized decompressed payloads with 413.
  11806. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11807. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11808. EXPECT_LE(total, LIMIT);
  11809. }
  11810. #ifndef CPPHTTPLIB_SSL_ENABLED
  11811. // For a request with neither Content-Length nor Transfer-Encoding, the
  11812. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11813. // compressed wire bytes straight to the ContentReader without ever routing
  11814. // them through the decompressor, so payload_max_length_ only bounded the
  11815. // compressed size on the wire, not the decompressed size.
  11816. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11817. Server svr;
  11818. const size_t LIMIT = 64 * 1024; // 64KB
  11819. svr.set_payload_max_length(LIMIT);
  11820. size_t total = 0;
  11821. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11822. const ContentReader &content_reader) {
  11823. content_reader([&](const char * /*data*/, size_t len) {
  11824. total += len;
  11825. return true;
  11826. });
  11827. res.status = 200;
  11828. res.set_content("stream_ok", "text/plain");
  11829. });
  11830. auto port = svr.bind_to_any_port(HOST);
  11831. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11832. auto se = detail::scope_exit([&] {
  11833. svr.stop();
  11834. thread.join();
  11835. ASSERT_FALSE(svr.is_running());
  11836. });
  11837. svr.wait_until_ready();
  11838. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11839. // StreamingGzipDecompression test above.
  11840. std::string raw(256 * 1024, 'A');
  11841. std::string gz;
  11842. {
  11843. httplib::detail::gzip_compressor compressor;
  11844. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11845. [&](const char *chunk, size_t len) {
  11846. gz.append(chunk, len);
  11847. return true;
  11848. });
  11849. ASSERT_TRUE(result);
  11850. }
  11851. // Send the gzip body over raw TCP with neither Content-Length nor
  11852. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11853. // kicks in.
  11854. std::string req = "POST /stream HTTP/1.1\r\n"
  11855. "Host: " +
  11856. std::string(HOST) + ":" + std::to_string(port) +
  11857. "\r\n"
  11858. "Content-Encoding: gzip\r\n"
  11859. "Connection: close\r\n"
  11860. "\r\n" +
  11861. gz;
  11862. std::string response;
  11863. ASSERT_TRUE(send_request(5, req, &response, port));
  11864. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11865. EXPECT_LE(total, LIMIT);
  11866. }
  11867. #endif
  11868. #endif
  11869. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11870. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11871. // the payload must be passed through untouched instead of being rejected.
  11872. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11873. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11874. Server svr;
  11875. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11876. res.set_content(body, "image/jpeg");
  11877. res.set_header("Content-Encoding", "UTF-8");
  11878. });
  11879. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11880. res.set_content(body, "image/jpeg");
  11881. res.set_header("Content-Encoding", "identity");
  11882. });
  11883. svr.Post("/echo", [](const Request &req, Response &res) {
  11884. res.set_content(req.body, "image/jpeg");
  11885. });
  11886. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11887. auto se = detail::scope_exit([&] {
  11888. svr.stop();
  11889. t.join();
  11890. ASSERT_FALSE(svr.is_running());
  11891. });
  11892. svr.wait_until_ready();
  11893. Client cli(HOST, PORT);
  11894. {
  11895. auto res = cli.Get("/image");
  11896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11897. EXPECT_EQ(StatusCode::OK_200, res->status);
  11898. EXPECT_EQ(body, res->body);
  11899. }
  11900. {
  11901. auto res = cli.Get("/identity");
  11902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11903. EXPECT_EQ(StatusCode::OK_200, res->status);
  11904. EXPECT_EQ(body, res->body);
  11905. }
  11906. {
  11907. // The same applies to a request body reaching the server.
  11908. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11909. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. EXPECT_EQ(StatusCode::OK_200, res->status);
  11912. EXPECT_EQ(body, res->body);
  11913. }
  11914. }
  11915. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11916. // gzip-encoded response even when the build has no zlib support.
  11917. static const char GZIPPED_HELLO_WORLD[] = {
  11918. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11919. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11920. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11921. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11922. // A content coding is a whole token, not something the field value merely
  11923. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11924. // as "fibre" look like Brotli, and turned a multi-coding value like
  11925. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11926. // it was never meant to see.
  11927. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11928. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11929. Server svr;
  11930. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11931. res.set_content(body, "image/jpeg");
  11932. res.set_header("Content-Encoding", "fibre");
  11933. });
  11934. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11935. res.set_content(body, "image/jpeg");
  11936. res.set_header("Content-Encoding", "gzip, br");
  11937. });
  11938. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11939. res.set_content(body, "image/jpeg");
  11940. res.set_header("Content-Encoding", "x-zstd-ish");
  11941. });
  11942. auto port = svr.bind_to_any_port(HOST);
  11943. thread t = thread([&]() { svr.listen_after_bind(); });
  11944. auto se = detail::scope_exit([&] {
  11945. svr.stop();
  11946. t.join();
  11947. ASSERT_FALSE(svr.is_running());
  11948. });
  11949. svr.wait_until_ready();
  11950. Client cli(HOST, port);
  11951. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11952. auto res = cli.Get(path);
  11953. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11954. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11955. // Not a coding we recognize, so the payload comes back untouched
  11956. EXPECT_EQ(body, res->body) << path;
  11957. }
  11958. }
  11959. // A content coding cpp-httplib recognizes but was not built with must be
  11960. // reported as such. Handing the still-compressed payload back to the caller
  11961. // would silently corrupt it.
  11962. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11963. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11964. Server svr;
  11965. // "image/jpeg" keeps the server from applying a content coding of its own,
  11966. // so the hand-crafted Content-Encoding below survives.
  11967. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11968. res.set_content(gzipped, "image/jpeg");
  11969. res.set_header("Content-Encoding", "gzip");
  11970. });
  11971. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11972. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11973. res.set_content(gzipped, "image/jpeg");
  11974. res.set_header("Content-Encoding", "GZIP");
  11975. });
  11976. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11977. auto se = detail::scope_exit([&] {
  11978. svr.stop();
  11979. t.join();
  11980. ASSERT_FALSE(svr.is_running());
  11981. });
  11982. svr.wait_until_ready();
  11983. Client cli(HOST, PORT);
  11984. {
  11985. auto res = cli.Get("/gzipped");
  11986. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11988. EXPECT_EQ("Hello World!", res->body);
  11989. #else
  11990. ASSERT_FALSE(res);
  11991. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11992. #endif
  11993. }
  11994. {
  11995. // open_stream() must behave the same way.
  11996. auto handle = cli.open_stream("GET", "/gzipped");
  11997. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11998. ASSERT_TRUE(handle.is_valid());
  11999. std::string received;
  12000. char buf[256];
  12001. ssize_t n;
  12002. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12003. received.append(buf, static_cast<size_t>(n));
  12004. }
  12005. EXPECT_EQ("Hello World!", received);
  12006. #else
  12007. EXPECT_FALSE(handle.is_valid());
  12008. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12009. #endif
  12010. }
  12011. {
  12012. // A differently-cased coding must not be mistaken for an unknown one, or
  12013. // the body would be handed back still compressed.
  12014. auto res = cli.Get("/gzipped-uppercase");
  12015. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12017. EXPECT_EQ("Hello World!", res->body);
  12018. #else
  12019. ASSERT_FALSE(res);
  12020. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12021. #endif
  12022. }
  12023. }
  12024. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12025. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12026. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12027. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12028. // body a second time and appending a second Content-Encoding field line, so
  12029. // clients that decode one coding per listed value handed back raw gzip bytes.
  12030. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12031. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12032. Server svr;
  12033. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12034. // keeps the server from applying a coding of its own.
  12035. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12036. res.set_content(gzipped, "text/plain");
  12037. res.set_header("Content-Encoding", "gzip");
  12038. });
  12039. auto port = svr.bind_to_any_port(HOST);
  12040. thread t = thread([&]() { svr.listen_after_bind(); });
  12041. auto se = detail::scope_exit([&] {
  12042. svr.stop();
  12043. t.join();
  12044. ASSERT_FALSE(svr.is_running());
  12045. });
  12046. svr.wait_until_ready();
  12047. Client cli(HOST, port);
  12048. Headers headers = {{"Accept-Encoding", "gzip"}};
  12049. auto res = cli.Get("/pre-gzipped", headers);
  12050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12051. EXPECT_EQ(StatusCode::OK_200, res->status);
  12052. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12053. EXPECT_EQ("Hello World!", res->body);
  12054. }
  12055. // A chunked provider settles its coding where the headers are written and
  12056. // reuses it at write time. Both ends of that have to hold: a handler's own
  12057. // Content-Encoding suppresses the coding, and a response without one is still
  12058. // compressed as it always was.
  12059. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12060. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12061. const std::string plain = "Hello World! Hello World! Hello World!";
  12062. Server svr;
  12063. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12064. res.set_header("Content-Encoding", "gzip");
  12065. res.set_chunked_content_provider(
  12066. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12067. sink.write(gzipped.data(), gzipped.size());
  12068. sink.done();
  12069. return true;
  12070. });
  12071. });
  12072. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12073. res.set_chunked_content_provider(
  12074. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12075. sink.write(plain.data(), plain.size());
  12076. sink.done();
  12077. return true;
  12078. });
  12079. });
  12080. auto port = svr.bind_to_any_port(HOST);
  12081. thread t = thread([&]() { svr.listen_after_bind(); });
  12082. auto se = detail::scope_exit([&] {
  12083. svr.stop();
  12084. t.join();
  12085. ASSERT_FALSE(svr.is_running());
  12086. });
  12087. svr.wait_until_ready();
  12088. Client cli(HOST, port);
  12089. Headers headers = {{"Accept-Encoding", "gzip"}};
  12090. {
  12091. auto res = cli.Get("/pre-gzipped", headers);
  12092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12093. EXPECT_EQ(StatusCode::OK_200, res->status);
  12094. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12095. EXPECT_EQ("Hello World!", res->body);
  12096. }
  12097. {
  12098. auto res = cli.Get("/negotiated", headers);
  12099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12100. EXPECT_EQ(StatusCode::OK_200, res->status);
  12101. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12102. EXPECT_EQ(plain, res->body);
  12103. }
  12104. }
  12105. #endif
  12106. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12107. // the same message as the comma-joined one, so both have to be read the same
  12108. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12109. // single gzip coding, and a body the sender says was encoded twice was handed
  12110. // back after one pass, still compressed but presented as decoded.
  12111. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12112. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12113. Server svr;
  12114. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12115. res.set_content(body, "image/jpeg");
  12116. res.headers.emplace("Content-Encoding", "gzip");
  12117. res.headers.emplace("Content-Encoding", "gzip");
  12118. });
  12119. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12120. res.set_content(body, "image/jpeg");
  12121. res.set_header("Content-Encoding", "gzip, gzip");
  12122. });
  12123. auto port = svr.bind_to_any_port(HOST);
  12124. thread t = thread([&]() { svr.listen_after_bind(); });
  12125. auto se = detail::scope_exit([&] {
  12126. svr.stop();
  12127. t.join();
  12128. ASSERT_FALSE(svr.is_running());
  12129. });
  12130. svr.wait_until_ready();
  12131. Client cli(HOST, port);
  12132. // Two codings is not something cpp-httplib decodes, so both representations
  12133. // take the pass-through path rather than one of them being gunzipped once.
  12134. for (const char *path : {"/split", "/joined"}) {
  12135. auto res = cli.Get(path);
  12136. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12137. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12138. EXPECT_EQ(body, res->body) << path;
  12139. }
  12140. }
  12141. // Regression test for DoS vulnerability: a malicious server sending a response
  12142. // without Content-Length header must not cause unbounded memory consumption on
  12143. // the client side. The client should stop reading after a reasonable limit,
  12144. // similar to the server-side set_payload_max_length protection.
  12145. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12146. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12147. #ifndef _WIN32
  12148. signal(SIGPIPE, SIG_IGN);
  12149. #endif
  12150. auto server_thread = std::thread([] {
  12151. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12152. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12153. default_socket_options(srv);
  12154. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12155. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12156. sockaddr_in addr{};
  12157. addr.sin_family = AF_INET;
  12158. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12159. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12160. int opt = 1;
  12161. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12162. #ifdef _WIN32
  12163. reinterpret_cast<const char *>(&opt),
  12164. #else
  12165. &opt,
  12166. #endif
  12167. sizeof(opt));
  12168. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12169. ::listen(srv, 1);
  12170. sockaddr_in cli_addr{};
  12171. socklen_t cli_len = sizeof(cli_addr);
  12172. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12173. if (cli != INVALID_SOCKET) {
  12174. char buf[4096];
  12175. ::recv(cli, buf, sizeof(buf), 0);
  12176. // Malicious response: no Content-Length, no chunked encoding
  12177. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12178. "Connection: close\r\n"
  12179. "\r\n";
  12180. ::send(cli,
  12181. #ifdef _WIN32
  12182. static_cast<const char *>(response_header.c_str()),
  12183. static_cast<int>(response_header.size()),
  12184. #else
  12185. response_header.c_str(), response_header.size(),
  12186. #endif
  12187. 0);
  12188. // Send 10MB of data
  12189. std::string chunk(64 * 1024, 'A');
  12190. size_t total_sent = 0;
  12191. while (total_sent < MALICIOUS_DATA_SIZE) {
  12192. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12193. auto sent = ::send(cli,
  12194. #ifdef _WIN32
  12195. static_cast<const char *>(chunk.c_str()),
  12196. static_cast<int>(to_send),
  12197. #else
  12198. chunk.c_str(), to_send,
  12199. #endif
  12200. 0);
  12201. if (sent <= 0) break;
  12202. total_sent += static_cast<size_t>(sent);
  12203. }
  12204. detail::close_socket(cli);
  12205. }
  12206. detail::close_socket(srv);
  12207. });
  12208. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12209. size_t total_read = 0;
  12210. {
  12211. Client cli("127.0.0.1", PORT + 2);
  12212. cli.set_read_timeout(5, 0);
  12213. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12214. auto stream = cli.open_stream("GET", "/malicious");
  12215. ASSERT_TRUE(stream.is_valid());
  12216. char buffer[64 * 1024];
  12217. ssize_t n;
  12218. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12219. total_read += static_cast<size_t>(n);
  12220. }
  12221. } // StreamHandle and Client destroyed here, closing the socket
  12222. server_thread.join();
  12223. // With set_payload_max_length, the client must stop reading before consuming
  12224. // all 10MB. The read loop should be cut off at or near the configured limit.
  12225. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12226. << "Client read " << total_read << " bytes, exceeding the configured "
  12227. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12228. }
  12229. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12230. // the entire response body without truncation.
  12231. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12232. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12233. #ifndef _WIN32
  12234. signal(SIGPIPE, SIG_IGN);
  12235. #endif
  12236. auto server_thread = std::thread([] {
  12237. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12238. default_socket_options(srv);
  12239. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12240. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12241. sockaddr_in addr{};
  12242. addr.sin_family = AF_INET;
  12243. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12244. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12245. int opt = 1;
  12246. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12247. #ifdef _WIN32
  12248. reinterpret_cast<const char *>(&opt),
  12249. #else
  12250. &opt,
  12251. #endif
  12252. sizeof(opt));
  12253. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12254. ::listen(srv, 1);
  12255. sockaddr_in cli_addr{};
  12256. socklen_t cli_len = sizeof(cli_addr);
  12257. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12258. if (cli != INVALID_SOCKET) {
  12259. char buf[4096];
  12260. ::recv(cli, buf, sizeof(buf), 0);
  12261. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12262. "Connection: close\r\n"
  12263. "\r\n";
  12264. ::send(cli,
  12265. #ifdef _WIN32
  12266. static_cast<const char *>(response_header.c_str()),
  12267. static_cast<int>(response_header.size()),
  12268. #else
  12269. response_header.c_str(), response_header.size(),
  12270. #endif
  12271. 0);
  12272. std::string chunk(64 * 1024, 'A');
  12273. size_t total_sent = 0;
  12274. while (total_sent < DATA_SIZE) {
  12275. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12276. auto sent = ::send(cli,
  12277. #ifdef _WIN32
  12278. static_cast<const char *>(chunk.c_str()),
  12279. static_cast<int>(to_send),
  12280. #else
  12281. chunk.c_str(), to_send,
  12282. #endif
  12283. 0);
  12284. if (sent <= 0) break;
  12285. total_sent += static_cast<size_t>(sent);
  12286. }
  12287. #ifdef _WIN32
  12288. ::shutdown(cli, SD_SEND);
  12289. #else
  12290. ::shutdown(cli, SHUT_WR);
  12291. #endif
  12292. // Drain until the client closes its end, ensuring all data is delivered
  12293. char drain[1024];
  12294. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12295. detail::close_socket(cli);
  12296. }
  12297. detail::close_socket(srv);
  12298. });
  12299. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12300. size_t total_read = 0;
  12301. {
  12302. Client cli("127.0.0.1", PORT + 2);
  12303. cli.set_read_timeout(5, 0);
  12304. cli.set_payload_max_length(0); // 0 means no limit
  12305. auto stream = cli.open_stream("GET", "/data");
  12306. ASSERT_TRUE(stream.is_valid());
  12307. char buffer[64 * 1024];
  12308. ssize_t n;
  12309. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12310. total_read += static_cast<size_t>(n);
  12311. }
  12312. }
  12313. server_thread.join();
  12314. EXPECT_EQ(total_read, DATA_SIZE)
  12315. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12316. << " bytes without truncation, but only read " << total_read << " bytes.";
  12317. }
  12318. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12319. // enormous Content-Length must not cause the client to pre-allocate a huge
  12320. // response body buffer. The reservation is capped at payload_max_length_, and
  12321. // the read itself fails when the body exceeds the limit.
  12322. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12323. #ifndef _WIN32
  12324. signal(SIGPIPE, SIG_IGN);
  12325. #endif
  12326. auto server_thread = std::thread([] {
  12327. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12328. default_socket_options(srv);
  12329. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12330. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12331. sockaddr_in addr{};
  12332. addr.sin_family = AF_INET;
  12333. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12334. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12335. int opt = 1;
  12336. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12337. #ifdef _WIN32
  12338. reinterpret_cast<const char *>(&opt),
  12339. #else
  12340. &opt,
  12341. #endif
  12342. sizeof(opt));
  12343. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12344. ::listen(srv, 1);
  12345. sockaddr_in cli_addr{};
  12346. socklen_t cli_len = sizeof(cli_addr);
  12347. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12348. if (cli != INVALID_SOCKET) {
  12349. char buf[4096];
  12350. ::recv(cli, buf, sizeof(buf), 0);
  12351. // Malicious response: claim a 20GB body but send only a tiny payload.
  12352. std::string response = "HTTP/1.1 200 OK\r\n"
  12353. "Content-Length: 20000000000\r\n"
  12354. "\r\n"
  12355. "abc";
  12356. ::send(cli,
  12357. #ifdef _WIN32
  12358. static_cast<const char *>(response.c_str()),
  12359. static_cast<int>(response.size()),
  12360. #else
  12361. response.c_str(), response.size(),
  12362. #endif
  12363. 0);
  12364. detail::close_socket(cli);
  12365. }
  12366. detail::close_socket(srv);
  12367. });
  12368. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12369. {
  12370. Client cli("127.0.0.1", PORT + 2);
  12371. cli.set_read_timeout(5, 0);
  12372. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12373. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12374. // (server claims more bytes than payload_max_length permits), but it must
  12375. // not exhaust memory before getting there.
  12376. auto res = cli.Get("/malicious");
  12377. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12378. }
  12379. server_thread.join();
  12380. }
  12381. // Verify that content_receiver bypasses the default payload_max_length,
  12382. // allowing streaming downloads larger than 100MB without requiring an explicit
  12383. // set_payload_max_length call.
  12384. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12385. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12386. #ifndef _WIN32
  12387. signal(SIGPIPE, SIG_IGN);
  12388. #endif
  12389. auto server_thread = std::thread([] {
  12390. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12391. default_socket_options(srv);
  12392. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12393. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12394. sockaddr_in addr{};
  12395. addr.sin_family = AF_INET;
  12396. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12398. int opt = 1;
  12399. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12400. #ifdef _WIN32
  12401. reinterpret_cast<const char *>(&opt),
  12402. #else
  12403. &opt,
  12404. #endif
  12405. sizeof(opt));
  12406. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12407. ::listen(srv, 1);
  12408. sockaddr_in cli_addr{};
  12409. socklen_t cli_len = sizeof(cli_addr);
  12410. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12411. if (cli != INVALID_SOCKET) {
  12412. char buf[4096];
  12413. ::recv(cli, buf, sizeof(buf), 0);
  12414. // Response with Content-Length larger than default 100MB limit
  12415. auto content_length = std::to_string(DATA_SIZE);
  12416. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12417. "Content-Length: " +
  12418. content_length +
  12419. "\r\n"
  12420. "Connection: close\r\n"
  12421. "\r\n";
  12422. ::send(cli,
  12423. #ifdef _WIN32
  12424. static_cast<const char *>(response_header.c_str()),
  12425. static_cast<int>(response_header.size()),
  12426. #else
  12427. response_header.c_str(), response_header.size(),
  12428. #endif
  12429. 0);
  12430. std::string chunk(64 * 1024, 'A');
  12431. size_t total_sent = 0;
  12432. while (total_sent < DATA_SIZE) {
  12433. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12434. auto sent = ::send(cli,
  12435. #ifdef _WIN32
  12436. static_cast<const char *>(chunk.c_str()),
  12437. static_cast<int>(to_send),
  12438. #else
  12439. chunk.c_str(), to_send,
  12440. #endif
  12441. 0);
  12442. if (sent <= 0) break;
  12443. total_sent += static_cast<size_t>(sent);
  12444. }
  12445. detail::close_socket(cli);
  12446. }
  12447. detail::close_socket(srv);
  12448. });
  12449. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12450. size_t total_received = 0;
  12451. {
  12452. Client cli("127.0.0.1", PORT + 2);
  12453. cli.set_read_timeout(10, 0);
  12454. // Do NOT call set_payload_max_length — use the default 100MB limit
  12455. auto res =
  12456. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12457. total_received += data_length;
  12458. return true;
  12459. });
  12460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12461. EXPECT_EQ(StatusCode::OK_200, res->status);
  12462. }
  12463. server_thread.join();
  12464. EXPECT_EQ(total_received, DATA_SIZE)
  12465. << "With content_receiver, the client should read all " << DATA_SIZE
  12466. << " bytes despite the default 100MB payload_max_length, but only read "
  12467. << total_received << " bytes.";
  12468. }
  12469. // Verify that an explicit set_payload_max_length smaller than the response is
  12470. // enforced even when a content_receiver is used.
  12471. TEST(ClientVulnerabilityTest,
  12472. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12473. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12474. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12475. #ifndef _WIN32
  12476. signal(SIGPIPE, SIG_IGN);
  12477. #endif
  12478. auto server_thread = std::thread([] {
  12479. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12480. default_socket_options(srv);
  12481. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12482. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12483. sockaddr_in addr{};
  12484. addr.sin_family = AF_INET;
  12485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12487. int opt = 1;
  12488. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12489. #ifdef _WIN32
  12490. reinterpret_cast<const char *>(&opt),
  12491. #else
  12492. &opt,
  12493. #endif
  12494. sizeof(opt));
  12495. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12496. ::listen(srv, 1);
  12497. sockaddr_in cli_addr{};
  12498. socklen_t cli_len = sizeof(cli_addr);
  12499. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12500. if (cli != INVALID_SOCKET) {
  12501. char buf[4096];
  12502. ::recv(cli, buf, sizeof(buf), 0);
  12503. auto content_length = std::to_string(DATA_SIZE);
  12504. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12505. "Content-Length: " +
  12506. content_length +
  12507. "\r\n"
  12508. "Connection: close\r\n"
  12509. "\r\n";
  12510. ::send(cli,
  12511. #ifdef _WIN32
  12512. static_cast<const char *>(response_header.c_str()),
  12513. static_cast<int>(response_header.size()),
  12514. #else
  12515. response_header.c_str(), response_header.size(),
  12516. #endif
  12517. 0);
  12518. std::string chunk(64 * 1024, 'A');
  12519. size_t total_sent = 0;
  12520. while (total_sent < DATA_SIZE) {
  12521. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12522. auto sent = ::send(cli,
  12523. #ifdef _WIN32
  12524. static_cast<const char *>(chunk.c_str()),
  12525. static_cast<int>(to_send),
  12526. #else
  12527. chunk.c_str(), to_send,
  12528. #endif
  12529. 0);
  12530. if (sent <= 0) break;
  12531. total_sent += static_cast<size_t>(sent);
  12532. }
  12533. detail::close_socket(cli);
  12534. }
  12535. detail::close_socket(srv);
  12536. });
  12537. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12538. size_t total_received = 0;
  12539. {
  12540. Client cli("127.0.0.1", PORT + 2);
  12541. cli.set_read_timeout(10, 0);
  12542. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12543. auto res =
  12544. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12545. total_received += data_length;
  12546. return true;
  12547. });
  12548. // Should fail because 200MB exceeds the explicit 150MB limit
  12549. EXPECT_FALSE(res);
  12550. }
  12551. server_thread.join();
  12552. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12553. << "Client with content_receiver should respect the explicit "
  12554. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12555. << total_received << " bytes.";
  12556. }
  12557. // Verify that an explicit set_payload_max_length larger than the response
  12558. // allows the content_receiver to read all data successfully.
  12559. TEST(ClientVulnerabilityTest,
  12560. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12561. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12562. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12563. #ifndef _WIN32
  12564. signal(SIGPIPE, SIG_IGN);
  12565. #endif
  12566. auto server_thread = std::thread([] {
  12567. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12568. default_socket_options(srv);
  12569. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12570. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12571. sockaddr_in addr{};
  12572. addr.sin_family = AF_INET;
  12573. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12574. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12575. int opt = 1;
  12576. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12577. #ifdef _WIN32
  12578. reinterpret_cast<const char *>(&opt),
  12579. #else
  12580. &opt,
  12581. #endif
  12582. sizeof(opt));
  12583. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12584. ::listen(srv, 1);
  12585. sockaddr_in cli_addr{};
  12586. socklen_t cli_len = sizeof(cli_addr);
  12587. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12588. if (cli != INVALID_SOCKET) {
  12589. char buf[4096];
  12590. ::recv(cli, buf, sizeof(buf), 0);
  12591. auto content_length = std::to_string(DATA_SIZE);
  12592. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12593. "Content-Length: " +
  12594. content_length +
  12595. "\r\n"
  12596. "Connection: close\r\n"
  12597. "\r\n";
  12598. ::send(cli,
  12599. #ifdef _WIN32
  12600. static_cast<const char *>(response_header.c_str()),
  12601. static_cast<int>(response_header.size()),
  12602. #else
  12603. response_header.c_str(), response_header.size(),
  12604. #endif
  12605. 0);
  12606. std::string chunk(64 * 1024, 'A');
  12607. size_t total_sent = 0;
  12608. while (total_sent < DATA_SIZE) {
  12609. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12610. auto sent = ::send(cli,
  12611. #ifdef _WIN32
  12612. static_cast<const char *>(chunk.c_str()),
  12613. static_cast<int>(to_send),
  12614. #else
  12615. chunk.c_str(), to_send,
  12616. #endif
  12617. 0);
  12618. if (sent <= 0) break;
  12619. total_sent += static_cast<size_t>(sent);
  12620. }
  12621. #ifdef _WIN32
  12622. ::shutdown(cli, SD_SEND);
  12623. #else
  12624. ::shutdown(cli, SHUT_WR);
  12625. #endif
  12626. char drain[1024];
  12627. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12628. detail::close_socket(cli);
  12629. }
  12630. detail::close_socket(srv);
  12631. });
  12632. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12633. size_t total_received = 0;
  12634. {
  12635. Client cli("127.0.0.1", PORT + 2);
  12636. cli.set_read_timeout(10, 0);
  12637. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12638. auto res =
  12639. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12640. total_received += data_length;
  12641. return true;
  12642. });
  12643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12644. EXPECT_EQ(StatusCode::OK_200, res->status);
  12645. }
  12646. server_thread.join();
  12647. EXPECT_EQ(total_received, DATA_SIZE)
  12648. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12649. << " bytes (larger than " << DATA_SIZE
  12650. << " bytes response), content_receiver should read all data, but only "
  12651. "read "
  12652. << total_received << " bytes.";
  12653. }
  12654. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12655. // Regression test for "zip bomb" attack on the client side: a malicious server
  12656. // sends a small gzip-compressed response that decompresses to a huge payload.
  12657. // The client must enforce payload_max_length on the decompressed size.
  12658. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12659. constexpr size_t DECOMPRESSED_SIZE =
  12660. 10 * 1024 * 1024; // 10MB after decompression
  12661. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12662. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12663. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12664. std::string compressed;
  12665. {
  12666. httplib::detail::gzip_compressor compressor;
  12667. bool ok =
  12668. compressor.compress(uncompressed.data(), uncompressed.size(),
  12669. /*last=*/true, [&](const char *buf, size_t len) {
  12670. compressed.append(buf, len);
  12671. return true;
  12672. });
  12673. ASSERT_TRUE(ok);
  12674. }
  12675. // Sanity: compressed data should be much smaller than the decompressed size
  12676. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12677. #ifndef _WIN32
  12678. signal(SIGPIPE, SIG_IGN);
  12679. #endif
  12680. // Set up the listening socket in the main thread so the server is guaranteed
  12681. // to be ready before the client connects (eliminates race condition).
  12682. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12683. default_socket_options(srv);
  12684. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12685. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12686. sockaddr_in addr{};
  12687. addr.sin_family = AF_INET;
  12688. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12689. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12690. int opt = 1;
  12691. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12692. #ifdef _WIN32
  12693. reinterpret_cast<const char *>(&opt),
  12694. #else
  12695. &opt,
  12696. #endif
  12697. sizeof(opt));
  12698. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12699. ASSERT_EQ(0, ::listen(srv, 1));
  12700. auto server_thread = std::thread([&compressed, srv] {
  12701. sockaddr_in cli_addr{};
  12702. socklen_t cli_len = sizeof(cli_addr);
  12703. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12704. if (cli != INVALID_SOCKET) {
  12705. // Read the full HTTP request (until \r\n\r\n)
  12706. char buf[4096];
  12707. size_t total = 0;
  12708. while (total < sizeof(buf)) {
  12709. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12710. if (n <= 0) break;
  12711. total += static_cast<size_t>(n);
  12712. // Check for end of headers
  12713. if (total >= 4) {
  12714. std::string req(buf, total);
  12715. if (req.find("\r\n\r\n") != std::string::npos) break;
  12716. }
  12717. }
  12718. // Malicious response: gzip-compressed body, no Content-Length
  12719. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12720. "Content-Encoding: gzip\r\n"
  12721. "Connection: close\r\n"
  12722. "\r\n";
  12723. ::send(cli,
  12724. #ifdef _WIN32
  12725. static_cast<const char *>(response_header.c_str()),
  12726. static_cast<int>(response_header.size()),
  12727. #else
  12728. response_header.c_str(), response_header.size(),
  12729. #endif
  12730. 0);
  12731. // Send the compressed payload (small on the wire, huge when decompressed)
  12732. size_t total_sent = 0;
  12733. while (total_sent < compressed.size()) {
  12734. auto to_send = std::min(compressed.size() - total_sent,
  12735. static_cast<size_t>(64 * 1024));
  12736. auto sent =
  12737. ::send(cli,
  12738. #ifdef _WIN32
  12739. static_cast<const char *>(compressed.c_str() + total_sent),
  12740. static_cast<int>(to_send),
  12741. #else
  12742. compressed.c_str() + total_sent, to_send,
  12743. #endif
  12744. 0);
  12745. if (sent <= 0) break;
  12746. total_sent += static_cast<size_t>(sent);
  12747. }
  12748. detail::close_socket(cli);
  12749. }
  12750. });
  12751. auto se = detail::scope_exit([&] {
  12752. detail::close_socket(srv);
  12753. server_thread.join();
  12754. });
  12755. size_t total_decompressed = 0;
  12756. {
  12757. Client cli("127.0.0.1", PORT + 3);
  12758. cli.set_read_timeout(5, 0);
  12759. cli.set_decompress(true);
  12760. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12761. auto stream = cli.open_stream("GET", "/zipbomb");
  12762. ASSERT_TRUE(stream.is_valid());
  12763. char buffer[64 * 1024];
  12764. ssize_t n;
  12765. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12766. total_decompressed += static_cast<size_t>(n);
  12767. }
  12768. }
  12769. // The decompressed size must be capped by payload_max_length. Without
  12770. // protection, the client would decompress the full 10MB from a tiny
  12771. // compressed payload, enabling a zip bomb DoS attack.
  12772. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12773. << "Client decompressed " << total_decompressed
  12774. << " bytes from a gzip response. The decompressed size should be "
  12775. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12776. }
  12777. #endif
  12778. TEST(HostAndPortPropertiesTest, NoSSL) {
  12779. httplib::Client cli("www.google.com", 1234);
  12780. ASSERT_EQ("www.google.com", cli.host());
  12781. ASSERT_EQ(1234, cli.port());
  12782. }
  12783. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12784. httplib::Client cli("www.google.com:1234");
  12785. ASSERT_EQ("www.google.com", cli.host());
  12786. ASSERT_EQ(1234, cli.port());
  12787. }
  12788. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12789. // Port number that overflows int — should not crash, client becomes invalid
  12790. httplib::Client cli("http://www.google.com:99999999999999999999");
  12791. ASSERT_FALSE(cli.is_valid());
  12792. }
  12793. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12794. // Port 99999 exceeds valid range (1-65535) — should not crash
  12795. httplib::Client cli("http://www.google.com:99999");
  12796. ASSERT_FALSE(cli.is_valid());
  12797. auto res = cli.Get("/");
  12798. EXPECT_FALSE(res);
  12799. EXPECT_EQ(Error::Connection, res.error());
  12800. }
  12801. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12802. httplib::Client cli("http://user:pass@localhost:1234");
  12803. ASSERT_FALSE(cli.is_valid());
  12804. EXPECT_FALSE(cli.Get("/"));
  12805. }
  12806. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12807. httplib::Client cli("http://www.google.com:80abc");
  12808. ASSERT_FALSE(cli.is_valid());
  12809. }
  12810. #ifdef CPPHTTPLIB_SSL_ENABLED
  12811. TEST(HostAndPortPropertiesTest, SSL) {
  12812. httplib::SSLClient cli("www.google.com");
  12813. ASSERT_EQ("www.google.com", cli.host());
  12814. ASSERT_EQ(443, cli.port());
  12815. }
  12816. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12817. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12818. std::string cert;
  12819. read_file(CA_CERT_FILE, cert);
  12820. httplib::SSLClient httplib_client("www.google.com");
  12821. // Load CA store first time
  12822. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12823. // Load CA store second time (update)
  12824. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12825. // Verify client is still valid and can make connections
  12826. httplib_client.enable_server_certificate_verification(true);
  12827. auto res = httplib_client.Get("/");
  12828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12829. // Google may return 200 or 301 depending on various factors
  12830. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12831. res->status == StatusCode::MovedPermanently_301);
  12832. }
  12833. TEST(SSLClientTest, ServerNameIndication_Online) {
  12834. auto host = "httpbingo.org";
  12835. auto path = std::string{"/get"};
  12836. SSLClient cli(host, 443);
  12837. auto res = cli.Get(path);
  12838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12839. ASSERT_EQ(StatusCode::OK_200, res->status);
  12840. }
  12841. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12842. // Use a site that will cause SSL verification failure due to self-signed cert
  12843. SSLClient cli("self-signed.badssl.com", 443);
  12844. cli.enable_server_certificate_verification(true);
  12845. auto res = cli.Get("/");
  12846. ASSERT_TRUE(!res);
  12847. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12848. // Verify backend error is captured for SSLServerVerification
  12849. // This occurs when certificate verification fails
  12850. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12851. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12852. EXPECT_NE(0UL, res.ssl_backend_error());
  12853. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12854. // For OpenSSL, ssl_error is 0 for verification errors
  12855. EXPECT_EQ(0, res.ssl_error());
  12856. #if !defined(_WIN32) || \
  12857. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12858. // On non-Windows or when Windows Schannel is disabled, the error comes
  12859. // from OpenSSL's verification
  12860. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12861. res.ssl_backend_error());
  12862. #endif
  12863. #endif
  12864. }
  12865. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12866. // Use a site where hostname doesn't match the certificate
  12867. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12868. SSLClient cli("wrong.host.badssl.com", 443);
  12869. cli.enable_server_certificate_verification(true);
  12870. cli.enable_server_hostname_verification(true);
  12871. auto res = cli.Get("/");
  12872. ASSERT_TRUE(!res);
  12873. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12874. // Verify backend error is captured for hostname verification failure
  12875. EXPECT_NE(0UL, res.ssl_backend_error());
  12876. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12877. // For OpenSSL, ssl_error is 0 for verification errors
  12878. EXPECT_EQ(0, res.ssl_error());
  12879. #if !defined(_WIN32) || \
  12880. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12881. // On non-Windows or when Windows Schannel is disabled, the error comes
  12882. // from OpenSSL's hostname verification
  12883. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12884. res.ssl_backend_error());
  12885. #endif
  12886. #endif
  12887. }
  12888. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12889. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12890. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12891. SSLClient cli("www.google.com", 443);
  12892. cli.enable_server_certificate_verification(true);
  12893. auto res = cli.Get("/");
  12894. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12895. }
  12896. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12897. SSLClient cli("www.google.com", 443);
  12898. cli.enable_server_certificate_verification(true);
  12899. cli.enable_windows_certificate_verification(false);
  12900. auto res = cli.Get("/");
  12901. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12902. }
  12903. // The server sends an intermediate cross-signed by a root Windows trusts,
  12904. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12905. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12906. SSLClient cli("accounts.spotify.com", 443);
  12907. auto res = cli.Get("/");
  12908. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12909. << " ssl_backend_error=" << res.ssl_backend_error();
  12910. }
  12911. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12912. // policy status, which no backend reports for a self-signed certificate.
  12913. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12914. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12915. ASSERT_TRUE(svr.is_valid());
  12916. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12917. auto se = detail::scope_exit([&] {
  12918. svr.stop();
  12919. t.join();
  12920. ASSERT_FALSE(svr.is_running());
  12921. });
  12922. svr.wait_until_ready();
  12923. SSLClient cli("127.0.0.1", PORT);
  12924. cli.set_connection_timeout(30);
  12925. auto res = cli.Get("/");
  12926. ASSERT_FALSE(res);
  12927. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12928. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12929. }
  12930. #endif
  12931. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12932. Client cli("https://google.com");
  12933. auto res = cli.Get("/");
  12934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12935. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12936. }
  12937. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12938. SSLClient cli("google.com");
  12939. cli.set_ca_cert_path(CA_CERT_FILE);
  12940. auto res = cli.Get("/");
  12941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12942. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12943. }
  12944. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12945. SSLClient cli("google.com");
  12946. cli.enable_server_certificate_verification(true);
  12947. cli.set_ca_cert_path("hello");
  12948. auto res = cli.Get("/");
  12949. ASSERT_TRUE(!res);
  12950. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12951. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12952. // should be set
  12953. EXPECT_EQ(0, res.ssl_error());
  12954. // Verify backend error is captured for SSLLoadingCerts
  12955. // This error occurs when loading CA certificates fails
  12956. EXPECT_NE(0UL, res.ssl_backend_error());
  12957. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12958. // OpenSSL specific error codes:
  12959. // > openssl errstr 0x80000002
  12960. // error:80000002:system library::No such file or directory
  12961. // > openssl errstr 0xA000126
  12962. // error:0A000126:SSL routines::unexpected eof while reading
  12963. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12964. res.ssl_backend_error() == 0xA000126);
  12965. #endif
  12966. }
  12967. TEST(SSLClientTest, ServerCertificateVerification4) {
  12968. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12969. ASSERT_TRUE(svr.is_valid());
  12970. svr.Get("/test", [&](const Request &, Response &res) {
  12971. res.set_content("test", "text/plain");
  12972. svr.stop();
  12973. ASSERT_TRUE(true);
  12974. });
  12975. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12976. auto se = detail::scope_exit([&] {
  12977. t.join();
  12978. ASSERT_FALSE(svr.is_running());
  12979. });
  12980. svr.wait_until_ready();
  12981. SSLClient cli("127.0.0.1", PORT);
  12982. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12983. cli.enable_server_certificate_verification(true);
  12984. cli.set_connection_timeout(30);
  12985. auto res = cli.Get("/test");
  12986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12987. ASSERT_EQ(StatusCode::OK_200, res->status);
  12988. }
  12989. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12990. std::string cert;
  12991. read_file(CA_CERT_FILE, cert);
  12992. SSLClient cli("google.com");
  12993. cli.load_ca_cert_store(cert.data(), cert.size());
  12994. const auto res = cli.Get("/");
  12995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12996. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12997. }
  12998. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12999. // clang-format off
  13000. static constexpr char cert[] =
  13001. "GlobalSign Root CA\n"
  13002. "==================\n"
  13003. "-----BEGIN CERTIFICATE-----\n"
  13004. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13005. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13006. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13007. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13008. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13009. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13010. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13011. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13012. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13013. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13014. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13015. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13016. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13017. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13018. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13019. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13020. "-----END CERTIFICATE-----\n";
  13021. // clang-format on
  13022. SSLClient cli("google.com");
  13023. cli.load_ca_cert_store(cert, sizeof(cert));
  13024. const auto res = cli.Get("/");
  13025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13026. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13027. }
  13028. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13029. SSLClient cli("www.youtube.com");
  13030. cli.set_ca_cert_path(CA_CERT_FILE);
  13031. cli.enable_server_certificate_verification(true);
  13032. cli.set_follow_location(true);
  13033. auto res = cli.Get("/");
  13034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13035. ASSERT_EQ(StatusCode::OK_200, res->status);
  13036. }
  13037. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13038. SSLClient cli("wWw.YouTube.Com");
  13039. cli.set_ca_cert_path(CA_CERT_FILE);
  13040. cli.enable_server_certificate_verification(true);
  13041. cli.enable_server_hostname_verification(true);
  13042. cli.set_follow_location(true);
  13043. auto res = cli.Get("/");
  13044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13045. ASSERT_EQ(StatusCode::OK_200, res->status);
  13046. }
  13047. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13048. SSLClient cli("gOoGlE.COm");
  13049. cli.enable_server_certificate_verification(true);
  13050. cli.enable_server_hostname_verification(true);
  13051. cli.set_follow_location(true);
  13052. auto res = cli.Get("/");
  13053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13054. ASSERT_EQ(StatusCode::OK_200, res->status);
  13055. }
  13056. TEST(SSLClientTest, Issue2004_Online) {
  13057. Client client("https://google.com");
  13058. client.set_follow_location(true);
  13059. auto res = client.Get("/");
  13060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13061. ASSERT_EQ(StatusCode::OK_200, res->status);
  13062. auto body = res->body;
  13063. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13064. }
  13065. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13066. // Create SSLClient with invalid cert/key to make is_valid() return false
  13067. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13068. "nonexistent_key.pem");
  13069. // is_valid() should be false due to cert loading failure
  13070. ASSERT_FALSE(cli.is_valid());
  13071. auto res = cli.Get("/");
  13072. ASSERT_FALSE(res);
  13073. EXPECT_EQ(Error::SSLConnection, res.error());
  13074. }
  13075. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13076. // Test for Issue #2251: SSL error not properly reported when client cert
  13077. // and key paths are swapped or mismatched
  13078. // This simulates the scenario where user accidentally swaps the cert and key
  13079. // files
  13080. // Using client cert file as private key and vice versa (completely wrong)
  13081. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13082. // Should fail validation due to cert/key mismatch
  13083. ASSERT_FALSE(cli.is_valid());
  13084. // Attempt to make a request should fail with proper error
  13085. auto res = cli.Get("/");
  13086. ASSERT_FALSE(res);
  13087. EXPECT_EQ(Error::SSLConnection, res.error());
  13088. // SSL error should be recorded in the Result object (this is the key fix for
  13089. // Issue #2251)
  13090. auto backend_error = res.ssl_backend_error();
  13091. EXPECT_NE(0u, backend_error);
  13092. }
  13093. // Tests cert/key mismatch detection at the TLS context level
  13094. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13095. // Test that using mismatched cert/key causes connection failure.
  13096. // We verify this at the SSLClient level rather than through internal
  13097. // TLS API functions.
  13098. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13099. cli.enable_server_certificate_verification(false);
  13100. cli.set_connection_timeout(2);
  13101. // The mismatch should cause a connection or handshake error
  13102. auto res = cli.Get("/test");
  13103. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13104. // Either way, the request should fail
  13105. EXPECT_FALSE(res);
  13106. }
  13107. #endif
  13108. #if 0
  13109. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13110. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13111. ASSERT_TRUE(cli != nullptr);
  13112. cli->set_address_family(AF_INET6);
  13113. cli->set_interface("en0");
  13114. auto res = cli->Get("/get");
  13115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13116. ASSERT_EQ(StatusCode::OK_200, res->status);
  13117. }
  13118. #endif
  13119. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13120. #ifdef CPPHTTPLIB_SSL_ENABLED
  13121. void ClientCertPresent(
  13122. const std::string &client_cert_file,
  13123. const std::string &client_private_key_file,
  13124. const std::string &client_encrypted_private_key_pass = std::string()) {
  13125. using namespace httplib::tls;
  13126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13127. CLIENT_CA_CERT_DIR);
  13128. ASSERT_TRUE(svr.is_valid());
  13129. svr.Get("/test", [&](const Request &req, Response &res) {
  13130. res.set_content("test", "text/plain");
  13131. auto cert = req.peer_cert();
  13132. ASSERT_TRUE(static_cast<bool>(cert));
  13133. std::string common_name = cert.subject_cn();
  13134. EXPECT_EQ("Common Name", common_name);
  13135. });
  13136. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13137. auto se = detail::scope_exit([&] {
  13138. svr.stop();
  13139. t.join();
  13140. ASSERT_FALSE(svr.is_running());
  13141. });
  13142. svr.wait_until_ready();
  13143. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13144. client_encrypted_private_key_pass);
  13145. cli.enable_server_certificate_verification(false);
  13146. cli.set_connection_timeout(30);
  13147. auto res = cli.Get("/test");
  13148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13149. ASSERT_EQ(StatusCode::OK_200, res->status);
  13150. }
  13151. TEST(SSLClientServerTest, ClientCertPresent) {
  13152. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13153. }
  13154. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13155. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13156. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13157. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13158. }
  13159. // PEM memory-based constructor tests (works with all TLS backends)
  13160. void PemMemoryClientCertPresent(
  13161. const std::string &client_cert_file,
  13162. const std::string &client_private_key_file,
  13163. const std::string &client_encrypted_private_key_pass = std::string()) {
  13164. // Read PEM files into memory
  13165. std::string server_cert_pem, server_key_pem;
  13166. std::string client_ca_pem;
  13167. std::string client_cert_pem, client_key_pem;
  13168. read_file(SERVER_CERT_FILE, server_cert_pem);
  13169. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13170. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13171. read_file(client_cert_file, client_cert_pem);
  13172. read_file(client_private_key_file, client_key_pem);
  13173. // Create server with PEM memory
  13174. SSLServer::PemMemory server_pem = {
  13175. server_cert_pem.c_str(),
  13176. server_cert_pem.size(),
  13177. server_key_pem.c_str(),
  13178. server_key_pem.size(),
  13179. client_ca_pem.c_str(),
  13180. client_ca_pem.size(),
  13181. nullptr // no password for server key
  13182. };
  13183. SSLServer svr(server_pem);
  13184. ASSERT_TRUE(svr.is_valid());
  13185. svr.Get("/test", [&](const Request &, Response &res) {
  13186. res.set_content("test", "text/plain");
  13187. });
  13188. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13189. auto se = detail::scope_exit([&] {
  13190. svr.stop();
  13191. t.join();
  13192. ASSERT_FALSE(svr.is_running());
  13193. });
  13194. svr.wait_until_ready();
  13195. // Create client with PEM memory
  13196. const char *password = client_encrypted_private_key_pass.empty()
  13197. ? nullptr
  13198. : client_encrypted_private_key_pass.c_str();
  13199. SSLClient::PemMemory client_pem = {
  13200. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13201. client_key_pem.size(), password};
  13202. SSLClient cli(HOST, PORT, client_pem);
  13203. cli.enable_server_certificate_verification(false);
  13204. cli.set_connection_timeout(30);
  13205. auto res = cli.Get("/test");
  13206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13207. ASSERT_EQ(StatusCode::OK_200, res->status);
  13208. }
  13209. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13210. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13211. }
  13212. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13213. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13214. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13215. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13216. }
  13217. TEST(SSLClientServerTest, ClientCertMissing) {
  13218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13219. CLIENT_CA_CERT_DIR);
  13220. ASSERT_TRUE(svr.is_valid());
  13221. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13222. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. t.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. SSLClient cli(HOST, PORT);
  13230. cli.set_connection_timeout(30);
  13231. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13232. // the chain check on Windows, so the result does not depend on the order.
  13233. cli.enable_server_hostname_verification(false);
  13234. auto res = cli.Get("/test");
  13235. ASSERT_TRUE(!res);
  13236. // When client cert is missing and server requires it, connection fails
  13237. // Error type depends on backend implementation
  13238. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13239. res.error() == Error::SSLConnection);
  13240. // Verify backend error is captured
  13241. // Note: This test may have different error codes depending on the exact
  13242. // verification failure
  13243. EXPECT_NE(0UL, res.ssl_backend_error());
  13244. }
  13245. TEST(SSLClientServerTest, TrustDirOptional) {
  13246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13247. ASSERT_TRUE(svr.is_valid());
  13248. svr.Get("/test", [&](const Request &, Response &res) {
  13249. res.set_content("test", "text/plain");
  13250. });
  13251. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13252. auto se = detail::scope_exit([&] {
  13253. svr.stop();
  13254. t.join();
  13255. ASSERT_FALSE(svr.is_running());
  13256. });
  13257. svr.wait_until_ready();
  13258. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13259. cli.enable_server_certificate_verification(false);
  13260. cli.set_connection_timeout(30);
  13261. auto res = cli.Get("/test");
  13262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13263. ASSERT_EQ(StatusCode::OK_200, res->status);
  13264. }
  13265. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13266. class NoListenSSLServer : public SSLServer {
  13267. public:
  13268. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13269. const char *client_ca_cert_file_path,
  13270. const char *client_ca_cert_dir_path = nullptr)
  13271. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13272. client_ca_cert_dir_path),
  13273. stop_(false) {}
  13274. std::atomic_bool stop_;
  13275. private:
  13276. bool process_and_close_socket(socket_t /*sock*/) override {
  13277. // Don't create SSL context
  13278. while (!stop_.load()) {
  13279. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13280. }
  13281. return true;
  13282. }
  13283. };
  13284. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13285. CLIENT_CA_CERT_FILE);
  13286. ASSERT_TRUE(svr.is_valid());
  13287. svr.Get("/test", [&](const Request &, Response &res) {
  13288. res.set_content("test", "text/plain");
  13289. });
  13290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13291. auto se = detail::scope_exit([&] {
  13292. svr.stop_ = true;
  13293. svr.stop();
  13294. t.join();
  13295. ASSERT_FALSE(svr.is_running());
  13296. });
  13297. svr.wait_until_ready();
  13298. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13299. cli.enable_server_certificate_verification(false);
  13300. cli.set_connection_timeout(1);
  13301. auto res = cli.Get("/test");
  13302. ASSERT_TRUE(!res);
  13303. EXPECT_EQ(Error::SSLConnection, res.error());
  13304. // Timeout results in WantRead error code (maps to backend-specific value)
  13305. EXPECT_NE(0, res.ssl_error());
  13306. }
  13307. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13308. // Test SSLServer with client certificate verification using the standard
  13309. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13311. CLIENT_CA_CERT_DIR);
  13312. ASSERT_TRUE(svr.is_valid());
  13313. svr.Get("/test", [&](const Request &req, Response &res) {
  13314. res.set_content("test", "text/plain");
  13315. auto cert = req.peer_cert();
  13316. ASSERT_TRUE(static_cast<bool>(cert));
  13317. auto common_name = cert.subject_cn();
  13318. EXPECT_EQ("Common Name", common_name);
  13319. });
  13320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13321. auto se = detail::scope_exit([&] {
  13322. svr.stop();
  13323. t.join();
  13324. ASSERT_FALSE(svr.is_running());
  13325. });
  13326. svr.wait_until_ready();
  13327. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13328. cli.enable_server_certificate_verification(false);
  13329. cli.set_connection_timeout(30);
  13330. auto res = cli.Get("/test");
  13331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13332. ASSERT_EQ(StatusCode::OK_200, res->status);
  13333. }
  13334. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13335. // Verifies that wildcard matching and exact matching work consistently
  13336. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13337. using namespace httplib::tls;
  13338. // We need a running server to test against
  13339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13340. ASSERT_TRUE(svr.is_valid());
  13341. svr.Get("/test", [](const Request &, Response &res) {
  13342. res.set_content("ok", "text/plain");
  13343. });
  13344. thread t([&]() { svr.listen(HOST, PORT); });
  13345. auto se = detail::scope_exit([&] {
  13346. svr.stop();
  13347. t.join();
  13348. });
  13349. svr.wait_until_ready();
  13350. bool verify_callback_called = false;
  13351. bool verify_result_wrong = false;
  13352. SSLClient cli(HOST, PORT);
  13353. cli.enable_server_certificate_verification(true);
  13354. cli.set_ca_cert_path(CA_CERT_FILE);
  13355. cli.set_connection_timeout(5);
  13356. // Note: Test certificate has CN="Common Name", not "localhost"
  13357. bool verify_result_cn = false;
  13358. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13359. verify_callback_called = true;
  13360. if (!ctx.cert) return false;
  13361. // Test 1: "Common Name" should match (our test server cert CN)
  13362. verify_result_cn = ctx.check_hostname("Common Name");
  13363. // Test 2: wrong hostname should not match
  13364. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13365. return true; // Accept for the purpose of this test
  13366. });
  13367. auto res = cli.Get("/test");
  13368. // The request may succeed or fail depending on cert configuration
  13369. // but the callback should have been called
  13370. ASSERT_TRUE(verify_callback_called)
  13371. << "Verify callback should have been called";
  13372. // CN="Common Name" should match our test certificate
  13373. //
  13374. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13375. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13376. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13377. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13378. // <openssl/base.h>, which is included transitively when
  13379. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13380. #if defined(OPENSSL_IS_BORINGSSL)
  13381. EXPECT_FALSE(verify_result_cn)
  13382. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13383. #else
  13384. EXPECT_TRUE(verify_result_cn)
  13385. << "verify_hostname should match 'Common Name' (certificate CN)";
  13386. #endif
  13387. // Wrong hostname should not match
  13388. EXPECT_FALSE(verify_result_wrong)
  13389. << "verify_hostname should not match 'wronghost.example.com'";
  13390. }
  13391. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13392. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13393. // X509_check_ip behavior and must hold for every backend.
  13394. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13395. using namespace httplib::tls;
  13396. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13397. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13398. ASSERT_TRUE(svr.is_valid());
  13399. svr.Get("/test", [](const Request &, Response &res) {
  13400. res.set_content("ok", "text/plain");
  13401. });
  13402. thread t([&]() { svr.listen(HOST, PORT); });
  13403. auto se = detail::scope_exit([&] {
  13404. svr.stop();
  13405. t.join();
  13406. });
  13407. svr.wait_until_ready();
  13408. bool verify_callback_called = false;
  13409. bool ip_matched_via_cn = true;
  13410. SSLClient cli(HOST, PORT);
  13411. cli.enable_server_certificate_verification(true);
  13412. cli.set_ca_cert_path(CA_CERT_FILE);
  13413. cli.set_connection_timeout(5);
  13414. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13415. verify_callback_called = true;
  13416. if (!ctx.cert) return false;
  13417. // The IP appears only in the CN, so it must NOT be accepted.
  13418. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13419. return true; // Accept for the purpose of this test
  13420. });
  13421. cli.Get("/test");
  13422. ASSERT_TRUE(verify_callback_called)
  13423. << "Verify callback should have been called";
  13424. EXPECT_FALSE(ip_matched_via_cn)
  13425. << "An IP host must not be authenticated via the certificate CN";
  13426. }
  13427. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13428. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13429. using namespace httplib::tls;
  13430. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13431. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13432. ASSERT_TRUE(svr.is_valid());
  13433. svr.Get("/test", [](const Request &, Response &res) {
  13434. res.set_content("ok", "text/plain");
  13435. });
  13436. thread t([&]() { svr.listen(HOST, PORT); });
  13437. auto se = detail::scope_exit([&] {
  13438. svr.stop();
  13439. t.join();
  13440. });
  13441. svr.wait_until_ready();
  13442. bool verify_callback_called = false;
  13443. bool san_matched = false;
  13444. bool wrong_ipv6_matched = true;
  13445. bool cn_ipv6_matched = true;
  13446. SSLClient cli(HOST, PORT);
  13447. cli.enable_server_certificate_verification(true);
  13448. cli.set_ca_cert_path(CA_CERT_FILE);
  13449. cli.set_connection_timeout(5);
  13450. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13451. verify_callback_called = true;
  13452. if (!ctx.cert) return false;
  13453. // Matches the IPv6 iPAddress SAN.
  13454. san_matched = ctx.check_hostname("2001:db8::1");
  13455. // A different IPv6 address must not match.
  13456. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13457. // "::1" lives only in the CN, so it must not be accepted.
  13458. cn_ipv6_matched = ctx.check_hostname("::1");
  13459. return true; // Accept for the purpose of this test
  13460. });
  13461. cli.Get("/test");
  13462. ASSERT_TRUE(verify_callback_called)
  13463. << "Verify callback should have been called";
  13464. EXPECT_TRUE(san_matched)
  13465. << "verify_hostname should match an IPv6 iPAddress SAN";
  13466. EXPECT_FALSE(wrong_ipv6_matched)
  13467. << "verify_hostname should not match a non-matching IPv6 address";
  13468. EXPECT_FALSE(cn_ipv6_matched)
  13469. << "An IPv6 host must not be authenticated via the certificate CN";
  13470. }
  13471. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13472. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13473. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13474. using namespace httplib::tls;
  13475. // SANs: DNS:a.zz, IP:42.46.122.122
  13476. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13477. ASSERT_TRUE(svr.is_valid());
  13478. svr.Get("/test", [](const Request &, Response &res) {
  13479. res.set_content("ok", "text/plain");
  13480. });
  13481. auto port = svr.bind_to_any_port(HOST);
  13482. thread t([&]() { svr.listen_after_bind(); });
  13483. auto se = detail::scope_exit([&] {
  13484. svr.stop();
  13485. t.join();
  13486. });
  13487. svr.wait_until_ready();
  13488. bool verify_callback_called = false;
  13489. bool dns_san_matched = false;
  13490. bool ip_san_matched = false;
  13491. bool ip_matched_via_dns_san = true;
  13492. bool dns_matched_via_ip_san = true;
  13493. SSLClient cli(HOST, port);
  13494. cli.enable_server_certificate_verification(true);
  13495. cli.set_ca_cert_path(CA_CERT_FILE);
  13496. cli.set_connection_timeout(5);
  13497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13498. verify_callback_called = true;
  13499. if (!ctx.cert) return false;
  13500. dns_san_matched = ctx.check_hostname("a.zz");
  13501. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13502. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13503. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13504. return true; // Accept for the purpose of this test
  13505. });
  13506. cli.Get("/test");
  13507. ASSERT_TRUE(verify_callback_called)
  13508. << "Verify callback should have been called";
  13509. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13510. EXPECT_TRUE(ip_san_matched)
  13511. << "verify_hostname should match an iPAddress SAN";
  13512. EXPECT_FALSE(ip_matched_via_dns_san)
  13513. << "An IP host must not be authenticated via a dNSName SAN";
  13514. EXPECT_FALSE(dns_matched_via_ip_san)
  13515. << "A DNS host must not be authenticated via an iPAddress SAN";
  13516. }
  13517. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13518. // "www.*.example.test" names one host and not every host under example.test.
  13519. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13520. using namespace httplib::tls;
  13521. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13522. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13523. ASSERT_TRUE(svr.is_valid());
  13524. svr.Get("/test", [](const Request &, Response &res) {
  13525. res.set_content("ok", "text/plain");
  13526. });
  13527. auto port = svr.bind_to_any_port(HOST);
  13528. thread t([&]() { svr.listen_after_bind(); });
  13529. auto se = detail::scope_exit([&] {
  13530. svr.stop();
  13531. t.join();
  13532. });
  13533. svr.wait_until_ready();
  13534. bool verify_callback_called = false;
  13535. bool leftmost_wildcard_matched = false;
  13536. bool wildcard_spanned_labels = true;
  13537. bool inner_wildcard_matched = true;
  13538. SSLClient cli(HOST, port);
  13539. cli.enable_server_certificate_verification(true);
  13540. cli.set_ca_cert_path(CA_CERT_FILE);
  13541. cli.set_connection_timeout(5);
  13542. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13543. verify_callback_called = true;
  13544. if (!ctx.cert) return false;
  13545. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13546. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13547. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13548. return true; // Accept for the purpose of this test
  13549. });
  13550. cli.Get("/test");
  13551. ASSERT_TRUE(verify_callback_called)
  13552. << "Verify callback should have been called";
  13553. EXPECT_TRUE(leftmost_wildcard_matched)
  13554. << "A leftmost wildcard should match a single label";
  13555. EXPECT_FALSE(wildcard_spanned_labels)
  13556. << "A wildcard label must not match more than one label";
  13557. EXPECT_FALSE(inner_wildcard_matched)
  13558. << "A wildcard outside the leftmost label must not be honoured";
  13559. }
  13560. // sans() must report each SAN entry under its own type.
  13561. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13562. using namespace httplib::tls;
  13563. // SANs: DNS:a.zz, IP:42.46.122.122
  13564. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13565. ASSERT_TRUE(svr.is_valid());
  13566. svr.Get("/test", [](const Request &, Response &res) {
  13567. res.set_content("ok", "text/plain");
  13568. });
  13569. auto port = svr.bind_to_any_port(HOST);
  13570. thread t([&]() { svr.listen_after_bind(); });
  13571. auto se = detail::scope_exit([&] {
  13572. svr.stop();
  13573. t.join();
  13574. });
  13575. svr.wait_until_ready();
  13576. bool verify_callback_called = false;
  13577. std::vector<SanEntry> sans;
  13578. SSLClient cli(HOST, port);
  13579. cli.enable_server_certificate_verification(true);
  13580. cli.set_ca_cert_path(CA_CERT_FILE);
  13581. cli.set_connection_timeout(5);
  13582. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13583. verify_callback_called = true;
  13584. if (!ctx.cert) return false;
  13585. sans = ctx.sans();
  13586. return true; // Accept for the purpose of this test
  13587. });
  13588. cli.Get("/test");
  13589. ASSERT_TRUE(verify_callback_called)
  13590. << "Verify callback should have been called";
  13591. auto has_san = [&](SanType type, const std::string &value) {
  13592. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13593. return san.type == type && san.value == value;
  13594. });
  13595. };
  13596. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13597. << "sans() should report the dNSName SAN";
  13598. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13599. << "sans() should report the iPAddress SAN";
  13600. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13601. << "sans() must not report the dNSName SAN as an address";
  13602. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13603. << "sans() must not report the iPAddress SAN as a DNS name";
  13604. }
  13605. #endif
  13606. // mbedTLS-specific callback constructor test
  13607. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13608. #ifdef CPPHTTPLIB_SSL_ENABLED
  13609. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13611. ASSERT_TRUE(svr.is_valid());
  13612. // Set up a handler to verify client certificate is present
  13613. bool client_cert_verified = false;
  13614. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13615. // Verify that client certificate was provided
  13616. client_cert_verified = true;
  13617. res.set_content("success", "text/plain");
  13618. });
  13619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13620. auto se = detail::scope_exit([&] {
  13621. svr.stop();
  13622. t.join();
  13623. ASSERT_FALSE(svr.is_running());
  13624. });
  13625. svr.wait_until_ready();
  13626. // Client with certificate
  13627. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13628. cli.enable_server_certificate_verification(false);
  13629. cli.set_connection_timeout(30);
  13630. auto res = cli.Get("/test");
  13631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13632. ASSERT_EQ(StatusCode::OK_200, res->status);
  13633. ASSERT_TRUE(client_cert_verified);
  13634. EXPECT_EQ("success", res->body);
  13635. }
  13636. #endif
  13637. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13638. // backends
  13639. #ifdef CPPHTTPLIB_SSL_ENABLED
  13640. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13641. using namespace httplib::tls;
  13642. // Test that when client CA cert file is provided,
  13643. // the server properly requests and validates client certificates
  13644. // Create a server with client authentication
  13645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13646. ASSERT_TRUE(svr.is_valid());
  13647. bool handler_called = false;
  13648. svr.Get("/test", [&](const Request &req, Response &res) {
  13649. handler_called = true;
  13650. // Verify that a client certificate was provided
  13651. auto cert = req.peer_cert();
  13652. ASSERT_TRUE(static_cast<bool>(cert));
  13653. // Get the issuer name
  13654. std::string issuer_str = cert.issuer_name();
  13655. ASSERT_FALSE(issuer_str.empty());
  13656. // The client certificate should be issued by our test CA
  13657. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13658. res.set_content("authenticated", "text/plain");
  13659. });
  13660. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13661. auto se = detail::scope_exit([&] {
  13662. svr.stop();
  13663. t.join();
  13664. ASSERT_FALSE(svr.is_running());
  13665. });
  13666. svr.wait_until_ready();
  13667. // Connect with a client certificate issued by the CA
  13668. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13669. cli.enable_server_certificate_verification(false);
  13670. cli.set_connection_timeout(30);
  13671. auto res = cli.Get("/test");
  13672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13673. ASSERT_EQ(StatusCode::OK_200, res->status);
  13674. ASSERT_TRUE(handler_called);
  13675. EXPECT_EQ("authenticated", res->body);
  13676. }
  13677. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13678. using namespace httplib::tls;
  13679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13680. ASSERT_TRUE(svr.is_valid());
  13681. svr.Get("/test", [](const Request &, Response &res) {
  13682. res.set_content("ok", "text/plain");
  13683. });
  13684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13685. auto se = detail::scope_exit([&] {
  13686. svr.stop();
  13687. t.join();
  13688. });
  13689. svr.wait_until_ready();
  13690. SSLClient cli(HOST, PORT);
  13691. cli.enable_server_certificate_verification(false);
  13692. cli.set_connection_timeout(30);
  13693. bool cert_checked = false;
  13694. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13695. if (ctx.cert) {
  13696. auto sans = ctx.sans();
  13697. // Test certificate may or may not have SANs - just verify the API
  13698. // works If SANs exist, verify the types are valid
  13699. for (const auto &san : sans) {
  13700. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13701. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13702. san.type == SanType::OTHER);
  13703. EXPECT_FALSE(san.value.empty());
  13704. }
  13705. cert_checked = true;
  13706. }
  13707. return true;
  13708. });
  13709. auto res = cli.Get("/test");
  13710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13711. EXPECT_TRUE(cert_checked);
  13712. }
  13713. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13714. using namespace httplib::tls;
  13715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13716. ASSERT_TRUE(svr.is_valid());
  13717. svr.Get("/test", [](const Request &, Response &res) {
  13718. res.set_content("ok", "text/plain");
  13719. });
  13720. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13721. auto se = detail::scope_exit([&] {
  13722. svr.stop();
  13723. t.join();
  13724. });
  13725. svr.wait_until_ready();
  13726. SSLClient cli(HOST, PORT);
  13727. cli.enable_server_certificate_verification(false);
  13728. cli.set_connection_timeout(30);
  13729. bool validity_checked = false;
  13730. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13731. if (ctx.cert) {
  13732. time_t not_before = 0, not_after = 0;
  13733. bool result = ctx.validity(not_before, not_after);
  13734. EXPECT_TRUE(result);
  13735. // Verify that not_before < now < not_after for a valid cert
  13736. time_t now = time(nullptr);
  13737. EXPECT_LT(not_before, now);
  13738. EXPECT_GT(not_after, now);
  13739. validity_checked = true;
  13740. }
  13741. return true;
  13742. });
  13743. auto res = cli.Get("/test");
  13744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13745. EXPECT_TRUE(validity_checked);
  13746. }
  13747. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13748. using namespace httplib::tls;
  13749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13750. ASSERT_TRUE(svr.is_valid());
  13751. svr.Get("/test", [](const Request &, Response &res) {
  13752. res.set_content("ok", "text/plain");
  13753. });
  13754. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. });
  13759. svr.wait_until_ready();
  13760. SSLClient cli(HOST, PORT);
  13761. cli.enable_server_certificate_verification(false);
  13762. cli.set_connection_timeout(30);
  13763. bool serial_checked = false;
  13764. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13765. if (ctx.cert) {
  13766. std::string serial = ctx.serial();
  13767. EXPECT_FALSE(serial.empty());
  13768. // Serial should be a hex string
  13769. for (char c : serial) {
  13770. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13771. (c >= 'a' && c <= 'f'));
  13772. }
  13773. serial_checked = true;
  13774. }
  13775. return true;
  13776. });
  13777. auto res = cli.Get("/test");
  13778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13779. EXPECT_TRUE(serial_checked);
  13780. }
  13781. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13782. // Test 1: Valid CA file - no error should be recorded
  13783. {
  13784. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13785. CLIENT_CA_CERT_FILE);
  13786. ASSERT_TRUE(svr.is_valid());
  13787. // With valid setup, last_ssl_error should be 0
  13788. EXPECT_EQ(0, svr.ssl_last_error());
  13789. }
  13790. // Test 2: Invalid CA file content
  13791. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13792. {
  13793. // Create a temporary file with completely invalid content
  13794. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13795. {
  13796. std::ofstream ofs(temp_invalid_ca);
  13797. ofs << "This is not a certificate file at all\n";
  13798. ofs << "Just plain text content\n";
  13799. }
  13800. // Create server with invalid CA file
  13801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13802. // Clean up temporary file
  13803. std::remove(temp_invalid_ca);
  13804. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13805. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13806. // Note: SSL_CTX_load_verify_locations typically fails first,
  13807. // but our error handling code path is still exercised
  13808. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13809. }
  13810. }
  13811. TEST(VerifyCallbackTest, VerifyContextFields) {
  13812. using namespace httplib::tls;
  13813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13814. ASSERT_TRUE(svr.is_valid());
  13815. svr.Get("/test", [](const Request &, Response &res) {
  13816. res.set_content("ok", "text/plain");
  13817. });
  13818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13819. auto se = detail::scope_exit([&] {
  13820. svr.stop();
  13821. t.join();
  13822. });
  13823. svr.wait_until_ready();
  13824. SSLClient cli(HOST, PORT);
  13825. cli.enable_server_certificate_verification(false);
  13826. cli.set_connection_timeout(30);
  13827. int callback_count = 0;
  13828. bool saw_leaf_cert = false;
  13829. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13830. if (ctx.cert) {
  13831. callback_count++;
  13832. // We should see at least one certificate (the leaf)
  13833. std::string cn = ctx.subject_cn();
  13834. if (!cn.empty()) { saw_leaf_cert = true; }
  13835. // Verify context fields are populated
  13836. EXPECT_NE(ctx.session, nullptr);
  13837. EXPECT_GE(ctx.depth, 0);
  13838. }
  13839. return true;
  13840. });
  13841. auto res = cli.Get("/test");
  13842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13843. EXPECT_GT(callback_count, 0);
  13844. EXPECT_TRUE(saw_leaf_cert);
  13845. }
  13846. // A verifier belongs to the client that set it, not to the thread that set it.
  13847. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13848. using namespace httplib::tls;
  13849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13850. ASSERT_TRUE(svr.is_valid());
  13851. svr.Get("/test", [](const Request &, Response &res) {
  13852. res.set_content("ok", "text/plain");
  13853. });
  13854. auto port = svr.bind_to_any_port(HOST);
  13855. thread t([&]() { svr.listen_after_bind(); });
  13856. auto se = detail::scope_exit([&] {
  13857. svr.stop();
  13858. t.join();
  13859. });
  13860. svr.wait_until_ready();
  13861. auto rejecting_calls = 0;
  13862. SSLClient rejecting(HOST, port);
  13863. rejecting.enable_server_certificate_verification(false);
  13864. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13865. rejecting_calls++;
  13866. return false;
  13867. });
  13868. auto accepting_calls = 0;
  13869. SSLClient accepting(HOST, port);
  13870. accepting.enable_server_certificate_verification(false);
  13871. // Set on another thread than the requests below.
  13872. thread([&]() {
  13873. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13874. accepting_calls++;
  13875. return true;
  13876. });
  13877. }).join();
  13878. // Requested on another thread than the verifier was set on.
  13879. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13880. EXPECT_GT(rejecting_calls, 0);
  13881. auto res = accepting.Get("/test");
  13882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13883. EXPECT_GT(accepting_calls, 0);
  13884. }
  13885. // VerifyContext::session is the same handle the other tls:: functions take.
  13886. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13887. using namespace httplib::tls;
  13888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13889. ASSERT_TRUE(svr.is_valid());
  13890. svr.Get("/test", [](const Request &, Response &res) {
  13891. res.set_content("ok", "text/plain");
  13892. });
  13893. auto port = svr.bind_to_any_port(HOST);
  13894. thread t([&]() { svr.listen_after_bind(); });
  13895. auto se = detail::scope_exit([&] {
  13896. svr.stop();
  13897. t.join();
  13898. });
  13899. svr.wait_until_ready();
  13900. SSLClient cli(HOST, port);
  13901. cli.enable_server_certificate_verification(false);
  13902. session_t verifier_session = nullptr;
  13903. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13904. verifier_session = ctx.session;
  13905. return true;
  13906. });
  13907. session_t session_verifier_session = nullptr;
  13908. cli.set_session_verifier([&](session_t session) {
  13909. session_verifier_session = session;
  13910. return SSLVerifierResponse::NoDecisionMade;
  13911. });
  13912. auto res = cli.Get("/test");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. EXPECT_NE(nullptr, verifier_session);
  13915. EXPECT_EQ(session_verifier_session, verifier_session);
  13916. }
  13917. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13918. using httplib::tls::TlsError;
  13919. // Test that verify_error_to_string returns empty for success
  13920. std::string success_str = TlsError::verify_error_to_string(0);
  13921. EXPECT_TRUE(success_str.empty());
  13922. // Test that verify_error_to_string returns non-empty for error codes
  13923. // Using a common error code (certificate expired)
  13924. std::string error_str =
  13925. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13926. EXPECT_FALSE(error_str.empty());
  13927. }
  13928. TEST(SessionVerifierTest, CertificateAccepted) {
  13929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13930. ASSERT_TRUE(svr.is_valid());
  13931. svr.Get("/test", [](const Request &, Response &res) {
  13932. res.set_content("ok", "text/plain");
  13933. });
  13934. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13935. auto se = detail::scope_exit([&] {
  13936. svr.stop();
  13937. t.join();
  13938. });
  13939. svr.wait_until_ready();
  13940. SSLClient cli(HOST, PORT);
  13941. cli.enable_server_certificate_verification(false);
  13942. cli.set_connection_timeout(30);
  13943. bool callback_called = false;
  13944. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13945. EXPECT_NE(session, nullptr);
  13946. callback_called = true;
  13947. return SSLVerifierResponse::CertificateAccepted;
  13948. });
  13949. auto res = cli.Get("/test");
  13950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13951. EXPECT_EQ(200, res->status);
  13952. EXPECT_TRUE(callback_called);
  13953. }
  13954. TEST(SessionVerifierTest, CertificateRejected) {
  13955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13956. ASSERT_TRUE(svr.is_valid());
  13957. svr.Get("/test", [](const Request &, Response &res) {
  13958. res.set_content("ok", "text/plain");
  13959. });
  13960. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. });
  13965. svr.wait_until_ready();
  13966. SSLClient cli(HOST, PORT);
  13967. cli.enable_server_certificate_verification(false);
  13968. cli.set_connection_timeout(30);
  13969. bool callback_called = false;
  13970. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13971. EXPECT_NE(session, nullptr);
  13972. callback_called = true;
  13973. return SSLVerifierResponse::CertificateRejected;
  13974. });
  13975. auto res = cli.Get("/test");
  13976. EXPECT_FALSE(res);
  13977. EXPECT_TRUE(callback_called);
  13978. }
  13979. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13981. ASSERT_TRUE(svr.is_valid());
  13982. svr.Get("/test", [](const Request &, Response &res) {
  13983. res.set_content("ok", "text/plain");
  13984. });
  13985. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13986. auto se = detail::scope_exit([&] {
  13987. svr.stop();
  13988. t.join();
  13989. });
  13990. svr.wait_until_ready();
  13991. // NoDecisionMade with verification disabled should succeed (no default check)
  13992. SSLClient cli(HOST, PORT);
  13993. cli.enable_server_certificate_verification(false);
  13994. cli.set_connection_timeout(30);
  13995. bool callback_called = false;
  13996. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13997. EXPECT_NE(session, nullptr);
  13998. callback_called = true;
  13999. return SSLVerifierResponse::NoDecisionMade;
  14000. });
  14001. auto res = cli.Get("/test");
  14002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14003. EXPECT_EQ(200, res->status);
  14004. EXPECT_TRUE(callback_called);
  14005. }
  14006. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14008. ASSERT_TRUE(svr.is_valid());
  14009. svr.Get("/test", [](const Request &, Response &res) {
  14010. res.set_content("ok", "text/plain");
  14011. });
  14012. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14013. auto se = detail::scope_exit([&] {
  14014. svr.stop();
  14015. t.join();
  14016. });
  14017. svr.wait_until_ready();
  14018. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14019. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14020. // so we only check that the request fails, not whether the callback was
  14021. // called.
  14022. SSLClient cli(HOST, PORT);
  14023. cli.enable_server_certificate_verification(true);
  14024. cli.set_connection_timeout(30);
  14025. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14026. EXPECT_NE(session, nullptr);
  14027. return SSLVerifierResponse::NoDecisionMade;
  14028. });
  14029. auto res = cli.Get("/test");
  14030. EXPECT_FALSE(res);
  14031. }
  14032. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14033. // Test SSL server using PemMemory constructor with client CA certificates
  14034. // Read PEM files
  14035. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14036. read_file(SERVER_CERT_FILE, server_cert_pem);
  14037. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14038. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14039. // Create SSLServer with PemMemory constructor including client CA
  14040. SSLServer::PemMemory server_pem = {
  14041. server_cert_pem.c_str(),
  14042. server_cert_pem.size(),
  14043. server_key_pem.c_str(),
  14044. server_key_pem.size(),
  14045. client_ca_pem.c_str(),
  14046. client_ca_pem.size(),
  14047. nullptr // no password for server key
  14048. };
  14049. SSLServer svr(server_pem);
  14050. ASSERT_TRUE(svr.is_valid());
  14051. // No SSL error should be recorded for valid setup
  14052. EXPECT_EQ(0, svr.ssl_last_error());
  14053. // Set up server endpoints
  14054. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14055. res.set_content("ok", "text/plain");
  14056. });
  14057. // Start server in a thread
  14058. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14059. svr.wait_until_ready();
  14060. // Connect with client certificate (using constructor with paths)
  14061. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14062. cli.enable_server_certificate_verification(false);
  14063. auto res = cli.Get("/test-pem-ca");
  14064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14065. EXPECT_EQ(200, res->status);
  14066. EXPECT_EQ("ok", res->body);
  14067. svr.stop();
  14068. server_thread.join();
  14069. }
  14070. #endif
  14071. #ifdef _WIN32
  14072. TEST(CleanupTest, WSACleanup) {
  14073. int ret = WSACleanup();
  14074. ASSERT_EQ(0, ret);
  14075. }
  14076. #endif
  14077. #ifndef CPPHTTPLIB_SSL_ENABLED
  14078. TEST(NoSSLSupport, SimpleInterface) {
  14079. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14080. }
  14081. #endif
  14082. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14083. TEST(InvalidScheme, SimpleInterface) {
  14084. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14085. }
  14086. #endif
  14087. TEST(NoScheme, SimpleInterface) {
  14088. Client cli("yahoo.com:80");
  14089. ASSERT_TRUE(cli.is_valid());
  14090. }
  14091. TEST(SendAPI, SimpleInterface_Online) {
  14092. Client cli("http://yahoo.com");
  14093. Request req;
  14094. req.method = "GET";
  14095. req.path = "/";
  14096. auto res = cli.send(req);
  14097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14098. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14099. }
  14100. TEST(SendAPI, WithParamsInRequest) {
  14101. Server svr;
  14102. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14103. EXPECT_TRUE(req.has_param("test"));
  14104. EXPECT_EQ("test_value", req.get_param_value("test"));
  14105. });
  14106. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14107. auto se = detail::scope_exit([&] {
  14108. svr.stop();
  14109. t.join();
  14110. ASSERT_FALSE(svr.is_running());
  14111. });
  14112. svr.wait_until_ready();
  14113. Client cli(HOST, PORT);
  14114. {
  14115. Request req;
  14116. req.method = "GET";
  14117. req.path = "/";
  14118. req.params.emplace("test", "test_value");
  14119. auto res = cli.send(req);
  14120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14121. }
  14122. {
  14123. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14125. }
  14126. }
  14127. TEST(ClientImplMethods, GetSocketTest) {
  14128. httplib::Server svr;
  14129. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14130. res.status = StatusCode::OK_200;
  14131. });
  14132. auto port = svr.bind_to_any_port("127.0.0.1");
  14133. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14134. auto se = detail::scope_exit([&] {
  14135. svr.stop();
  14136. thread.join();
  14137. ASSERT_FALSE(svr.is_running());
  14138. });
  14139. svr.wait_until_ready();
  14140. {
  14141. httplib::Client cli("127.0.0.1", port);
  14142. cli.set_keep_alive(true);
  14143. // Use the behavior of cpp-httplib of opening the connection
  14144. // only when the first request happens. If that changes,
  14145. // this test would be obsolete.
  14146. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14147. // This also implicitly tests the server. But other tests would fail much
  14148. // earlier than this one to be considered.
  14149. auto res = cli.Get("/");
  14150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14151. EXPECT_EQ(StatusCode::OK_200, res->status);
  14152. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14153. }
  14154. }
  14155. #ifdef CPPHTTPLIB_SSL_ENABLED
  14156. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14157. Client cli("http://yahoo.com");
  14158. auto res = cli.Get("/");
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14161. cli.set_follow_location(true);
  14162. res = cli.Get("/");
  14163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14164. EXPECT_EQ(StatusCode::OK_200, res->status);
  14165. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14166. }
  14167. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14168. Client cli("https://yahoo.com");
  14169. auto res = cli.Get("/");
  14170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14171. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14172. cli.set_follow_location(true);
  14173. res = cli.Get("/");
  14174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14175. EXPECT_EQ(StatusCode::OK_200, res->status);
  14176. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14177. }
  14178. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14179. Client cli("https://yahoo.com");
  14180. auto res = cli.Get("/");
  14181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14182. ASSERT_FALSE(!res);
  14183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14184. ASSERT_FALSE(res == nullptr);
  14185. ASSERT_TRUE(res != nullptr);
  14186. EXPECT_EQ(Error::Success, res.error());
  14187. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14188. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14189. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14190. cli.set_follow_location(true);
  14191. res = cli.Get("/");
  14192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14193. EXPECT_EQ(Error::Success, res.error());
  14194. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14195. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14196. EXPECT_EQ(StatusCode::OK_200, res->status);
  14197. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14198. }
  14199. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14200. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14201. Client cli("https://cdnjs.cloudflare.com");
  14202. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14203. Headers{{"Accept-Encoding", "br"}});
  14204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14205. EXPECT_EQ(StatusCode::OK_200, res->status);
  14206. EXPECT_EQ(287630U, res->body.size());
  14207. EXPECT_EQ("application/javascript; charset=utf-8",
  14208. res->get_header_value("Content-Type"));
  14209. }
  14210. #endif
  14211. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14212. #undef REDIR_HOST // Silence compiler warning
  14213. #define REDIR_HOST "https://httpbingo.org"
  14214. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14215. Client cli(REDIR_HOST);
  14216. cli.set_follow_location(true);
  14217. auto res =
  14218. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14220. EXPECT_EQ(StatusCode::OK_200, res->status);
  14221. }
  14222. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14223. Client cli(REDIR_HOST);
  14224. cli.set_follow_location(true);
  14225. Params params;
  14226. params.emplace("url", "http://example.com");
  14227. params.emplace("status_code", "302");
  14228. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14230. EXPECT_EQ(StatusCode::OK_200, res->status);
  14231. }
  14232. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14233. Client cli(REDIR_HOST);
  14234. cli.set_follow_location(true);
  14235. Params params;
  14236. params.emplace("url", "http://example.com");
  14237. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14239. EXPECT_EQ(StatusCode::OK_200, res->status);
  14240. }
  14241. TEST(HttpToHttpsRedirectTest, CertFile) {
  14242. auto ssl_port = PORT + 1;
  14243. Server svr;
  14244. ASSERT_TRUE(svr.is_valid());
  14245. svr.Get("/index", [&](const Request &, Response &res) {
  14246. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14247. "/index");
  14248. svr.stop();
  14249. });
  14250. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14251. ASSERT_TRUE(ssl_svr.is_valid());
  14252. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14253. res.set_content("test", "text/plain");
  14254. ssl_svr.stop();
  14255. });
  14256. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14257. thread t2 =
  14258. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14259. auto se = detail::scope_exit([&] {
  14260. t2.join();
  14261. t.join();
  14262. ASSERT_FALSE(svr.is_running());
  14263. });
  14264. svr.wait_until_ready();
  14265. ssl_svr.wait_until_ready();
  14266. Client cli("127.0.0.1", PORT);
  14267. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14268. cli.enable_server_certificate_verification(true);
  14269. cli.set_follow_location(true);
  14270. cli.set_connection_timeout(30);
  14271. auto res = cli.Get("/index");
  14272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14273. ASSERT_EQ(StatusCode::OK_200, res->status);
  14274. }
  14275. TEST(SSLClientRedirectTest, CertFile) {
  14276. auto ssl_port = PORT + 1;
  14277. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14278. ASSERT_TRUE(ssl_svr1.is_valid());
  14279. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14280. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14281. "/index");
  14282. ssl_svr1.stop();
  14283. });
  14284. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14285. ASSERT_TRUE(ssl_svr2.is_valid());
  14286. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14287. res.set_content("test", "text/plain");
  14288. ssl_svr2.stop();
  14289. });
  14290. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14291. thread t2 =
  14292. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14293. auto se = detail::scope_exit([&] {
  14294. t2.join();
  14295. t.join();
  14296. ASSERT_FALSE(ssl_svr1.is_running());
  14297. });
  14298. ssl_svr1.wait_until_ready();
  14299. ssl_svr2.wait_until_ready();
  14300. SSLClient cli("127.0.0.1", PORT);
  14301. std::string cert;
  14302. read_file(SERVER_CERT2_FILE, cert);
  14303. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14304. cli.enable_server_certificate_verification(true);
  14305. cli.set_follow_location(true);
  14306. cli.set_connection_timeout(30);
  14307. auto res = cli.Get("/index");
  14308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14309. ASSERT_EQ(StatusCode::OK_200, res->status);
  14310. }
  14311. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14312. // another port, so the client follows it with a new client.
  14313. static Result GetThroughTlsRedirectToDifferentPort(
  14314. const std::function<void(SSLClient &)> &setup,
  14315. const char *target_cert = SERVER_CERT2_FILE) {
  14316. auto ssl_port = PORT + 1;
  14317. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14318. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14319. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14320. "/index");
  14321. });
  14322. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14323. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14324. res.set_content("test", "text/plain");
  14325. });
  14326. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14327. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14328. auto se = detail::scope_exit([&] {
  14329. ssl_svr2.stop();
  14330. ssl_svr1.stop();
  14331. t2.join();
  14332. t.join();
  14333. });
  14334. ssl_svr1.wait_until_ready();
  14335. ssl_svr2.wait_until_ready();
  14336. SSLClient cli("127.0.0.1", PORT);
  14337. cli.set_follow_location(true);
  14338. cli.set_connection_timeout(30);
  14339. setup(cli);
  14340. return cli.Get("/index");
  14341. }
  14342. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14343. auto calls = 0;
  14344. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14345. cli.enable_server_certificate_verification(false);
  14346. // Accept the first server only.
  14347. cli.set_session_verifier([&](tls::session_t) {
  14348. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14349. : SSLVerifierResponse::CertificateRejected;
  14350. });
  14351. });
  14352. EXPECT_FALSE(res);
  14353. EXPECT_EQ(2, calls);
  14354. }
  14355. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14356. std::string pinned;
  14357. auto res = GetThroughTlsRedirectToDifferentPort(
  14358. [&](SSLClient &cli) {
  14359. cli.enable_server_certificate_verification(false);
  14360. // Pin the first certificate seen.
  14361. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14362. if (pinned.empty()) { pinned = ctx.serial(); }
  14363. return ctx.serial() == pinned;
  14364. });
  14365. },
  14366. // A certificate other than the first server's.
  14367. SERVER_CERT_FILE);
  14368. EXPECT_FALSE(res);
  14369. EXPECT_FALSE(pinned.empty());
  14370. }
  14371. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14372. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14373. std::string cert;
  14374. read_file(SERVER_CERT2_FILE, cert);
  14375. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14376. });
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::OK_200, res->status);
  14379. }
  14380. #endif
  14381. #ifdef CPPHTTPLIB_SSL_ENABLED
  14382. // Test that set_ca_cert_store() skips system certs (consistent with
  14383. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14384. // should be trusted - system certs should NOT be loaded.
  14385. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14386. // Load a specific cert that is NOT a system CA cert
  14387. std::string cert;
  14388. read_file(SERVER_CERT2_FILE, cert);
  14389. SSLClient cli("google.com");
  14390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14391. cli.enable_server_certificate_verification(true);
  14392. // This should FAIL because:
  14393. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14394. // 2. System certs should NOT be loaded when custom store is set
  14395. // If system certs WERE loaded, this would succeed
  14396. auto res = cli.Get("/");
  14397. ASSERT_FALSE(res);
  14398. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14399. }
  14400. // Same as above, but through the native store handle path. Regression test:
  14401. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14402. // merged system certs into the user-provided store.
  14403. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14404. std::string cert;
  14405. read_file(SERVER_CERT2_FILE, cert);
  14406. SSLClient cli("google.com");
  14407. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14408. cli.enable_server_certificate_verification(true);
  14409. auto res = cli.Get("/");
  14410. ASSERT_FALSE(res);
  14411. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14412. }
  14413. // A custom store set via the native handle must still verify a server whose
  14414. // cert it does contain.
  14415. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14416. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14417. ASSERT_TRUE(svr.is_valid());
  14418. svr.Get("/test", [&](const Request &, Response &res) {
  14419. res.set_content("test", "text/plain");
  14420. });
  14421. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14422. auto se = detail::scope_exit([&] {
  14423. svr.stop();
  14424. t.join();
  14425. ASSERT_FALSE(svr.is_running());
  14426. });
  14427. svr.wait_until_ready();
  14428. SSLClient cli("127.0.0.1", PORT);
  14429. std::string cert;
  14430. read_file(SERVER_CERT2_FILE, cert);
  14431. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14432. cli.enable_server_certificate_verification(true);
  14433. cli.set_connection_timeout(30);
  14434. auto res = cli.Get("/test");
  14435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14436. ASSERT_EQ(StatusCode::OK_200, res->status);
  14437. }
  14438. // CA certs loaded through the universal Client must be transferred to the
  14439. // client created internally for following an HTTPS redirect. Regression test:
  14440. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14441. // the CA data for redirect transfer.
  14442. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14443. auto ssl_port = PORT + 1;
  14444. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14445. ASSERT_TRUE(ssl_svr1.is_valid());
  14446. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14447. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14448. "/index");
  14449. });
  14450. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14451. ASSERT_TRUE(ssl_svr2.is_valid());
  14452. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14453. res.set_content("test", "text/plain");
  14454. });
  14455. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14456. thread t2 =
  14457. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14458. auto se = detail::scope_exit([&] {
  14459. ssl_svr2.stop();
  14460. ssl_svr1.stop();
  14461. t2.join();
  14462. t.join();
  14463. ASSERT_FALSE(ssl_svr1.is_running());
  14464. });
  14465. ssl_svr1.wait_until_ready();
  14466. ssl_svr2.wait_until_ready();
  14467. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14468. std::string cert;
  14469. read_file(SERVER_CERT2_FILE, cert);
  14470. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14471. cli.enable_server_certificate_verification(true);
  14472. cli.set_follow_location(true);
  14473. cli.set_connection_timeout(30);
  14474. auto res = cli.Get("/index");
  14475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14476. ASSERT_EQ(StatusCode::OK_200, res->status);
  14477. }
  14478. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14479. // so a host signed by a system CA verifies even though a custom CA is set
  14480. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14481. std::string cert;
  14482. read_file(SERVER_CERT2_FILE, cert);
  14483. SSLClient cli("google.com");
  14484. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14485. cli.enable_system_ca(true);
  14486. cli.enable_server_certificate_verification(true);
  14487. auto res = cli.Get("/");
  14488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14489. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14490. }
  14491. // The custom CA remains effective when combined with the system CA
  14492. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14493. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14494. ASSERT_TRUE(svr.is_valid());
  14495. svr.Get("/test", [&](const Request &, Response &res) {
  14496. res.set_content("test", "text/plain");
  14497. });
  14498. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14499. auto se = detail::scope_exit([&] {
  14500. svr.stop();
  14501. t.join();
  14502. ASSERT_FALSE(svr.is_running());
  14503. });
  14504. svr.wait_until_ready();
  14505. SSLClient cli("127.0.0.1", PORT);
  14506. std::string cert;
  14507. read_file(SERVER_CERT2_FILE, cert);
  14508. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14509. cli.enable_system_ca(true);
  14510. cli.enable_server_certificate_verification(true);
  14511. cli.set_connection_timeout(30);
  14512. auto res = cli.Get("/test");
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. ASSERT_EQ(StatusCode::OK_200, res->status);
  14515. }
  14516. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14517. // skip chain verification entirely (only the certificate identity was
  14518. // checked), so a server presenting an untrusted certificate with a matching
  14519. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14520. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14521. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14522. ASSERT_TRUE(svr.is_valid());
  14523. svr.Get("/test", [&](const Request &, Response &res) {
  14524. res.set_content("test", "text/plain");
  14525. });
  14526. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14527. auto se = detail::scope_exit([&] {
  14528. svr.stop();
  14529. t.join();
  14530. ASSERT_FALSE(svr.is_running());
  14531. });
  14532. svr.wait_until_ready();
  14533. SSLClient cli("127.0.0.1", PORT);
  14534. std::string cert;
  14535. // A trusted CA that did not sign the server certificate. The server cert
  14536. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14537. // this connection.
  14538. read_file(CLIENT_CA_CERT_FILE, cert);
  14539. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14540. cli.enable_server_certificate_verification(true);
  14541. cli.set_connection_timeout(30);
  14542. auto res = cli.Get("/test");
  14543. ASSERT_FALSE(res);
  14544. }
  14545. // enable_system_ca(false) prevents system CA loading entirely
  14546. TEST(SSLClientTest, DisableSystemCa_Online) {
  14547. SSLClient cli("google.com");
  14548. cli.enable_system_ca(false);
  14549. cli.enable_server_certificate_verification(true);
  14550. auto res = cli.Get("/");
  14551. ASSERT_FALSE(res);
  14552. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14553. // itself when the CA chain is empty
  14554. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14555. res.error() == Error::SSLConnection);
  14556. }
  14557. // The universal Client forwards enable_system_ca()
  14558. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14559. std::string cert;
  14560. read_file(SERVER_CERT2_FILE, cert);
  14561. Client cli("https://google.com");
  14562. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14563. cli.enable_system_ca(true);
  14564. cli.enable_server_certificate_verification(true);
  14565. auto res = cli.Get("/");
  14566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14567. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14568. }
  14569. // The system CA policy must carry over to the client created internally for
  14570. // following a cross-host HTTPS redirect
  14571. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14572. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14573. ASSERT_TRUE(svr.is_valid());
  14574. svr.Get("/index", [&](const Request &, Response &res) {
  14575. res.set_redirect("https://www.google.com/");
  14576. });
  14577. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14578. auto se = detail::scope_exit([&] {
  14579. svr.stop();
  14580. t.join();
  14581. ASSERT_FALSE(svr.is_running());
  14582. });
  14583. svr.wait_until_ready();
  14584. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14585. std::string cert;
  14586. read_file(SERVER_CERT2_FILE, cert);
  14587. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14588. cli.enable_system_ca(true);
  14589. cli.enable_server_certificate_verification(true);
  14590. cli.set_follow_location(true);
  14591. cli.set_connection_timeout(30);
  14592. // Receiving any response proves the redirect client completed the TLS
  14593. // handshake with a system-CA-signed host
  14594. auto res = cli.Get("/index");
  14595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14596. }
  14597. TEST(MultipartFormDataTest, LargeData) {
  14598. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14599. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14600. const ContentReader &content_reader) {
  14601. if (req.is_multipart_form_data()) {
  14602. std::vector<FormData> items;
  14603. content_reader(
  14604. [&](const FormData &file) {
  14605. items.push_back(file);
  14606. return true;
  14607. },
  14608. [&](const char *data, size_t data_length) {
  14609. items.back().content.append(data, data_length);
  14610. return true;
  14611. });
  14612. EXPECT_TRUE(std::string(items[0].name) == "document");
  14613. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14614. EXPECT_TRUE(items[0].filename == "2MB_data");
  14615. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14616. EXPECT_TRUE(items[1].name == "hello");
  14617. EXPECT_TRUE(items[1].content == "world");
  14618. EXPECT_TRUE(items[1].filename == "");
  14619. EXPECT_TRUE(items[1].content_type == "");
  14620. } else {
  14621. std::string body;
  14622. content_reader([&](const char *data, size_t data_length) {
  14623. body.append(data, data_length);
  14624. return true;
  14625. });
  14626. }
  14627. });
  14628. auto port = svr.bind_to_any_port(HOST);
  14629. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14630. auto se = detail::scope_exit([&] {
  14631. svr.stop();
  14632. t.join();
  14633. ASSERT_FALSE(svr.is_running());
  14634. });
  14635. svr.wait_until_ready();
  14636. {
  14637. std::string data(1024 * 1024 * 2, '.');
  14638. std::stringstream buffer;
  14639. buffer << data;
  14640. SSLClient cli(HOST, port);
  14641. cli.enable_server_certificate_verification(false);
  14642. UploadFormDataItems items{
  14643. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14644. {"hello", "world", "", ""},
  14645. };
  14646. auto res = cli.Post("/post", items);
  14647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14648. ASSERT_EQ(StatusCode::OK_200, res->status);
  14649. }
  14650. }
  14651. TEST(MultipartFormDataTest, DataProviderItems) {
  14652. std::random_device seed_gen;
  14653. std::mt19937 random(seed_gen());
  14654. std::string rand1;
  14655. rand1.resize(1000);
  14656. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14657. std::string rand2;
  14658. rand2.resize(3000);
  14659. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14661. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14662. const ContentReader &content_reader) {
  14663. ASSERT_FALSE(req.is_multipart_form_data());
  14664. std::string body;
  14665. content_reader([&](const char *data, size_t data_length) {
  14666. body.append(data, data_length);
  14667. return true;
  14668. });
  14669. EXPECT_EQ(body, "");
  14670. });
  14671. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14672. const ContentReader &content_reader) {
  14673. ASSERT_TRUE(req.is_multipart_form_data());
  14674. std::vector<FormData> items;
  14675. content_reader(
  14676. [&](const FormData &file) {
  14677. items.push_back(file);
  14678. return true;
  14679. },
  14680. [&](const char *data, size_t data_length) {
  14681. items.back().content.append(data, data_length);
  14682. return true;
  14683. });
  14684. ASSERT_TRUE(items.size() == 2);
  14685. EXPECT_EQ(std::string(items[0].name), "name1");
  14686. EXPECT_EQ(items[0].content, "Testing123");
  14687. EXPECT_EQ(items[0].filename, "filename1");
  14688. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14689. EXPECT_EQ(items[1].name, "name2");
  14690. EXPECT_EQ(items[1].content, "Testing456");
  14691. EXPECT_EQ(items[1].filename, "");
  14692. EXPECT_EQ(items[1].content_type, "");
  14693. });
  14694. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14695. const ContentReader &content_reader) {
  14696. ASSERT_TRUE(req.is_multipart_form_data());
  14697. std::vector<FormData> items;
  14698. content_reader(
  14699. [&](const FormData &file) {
  14700. items.push_back(file);
  14701. return true;
  14702. },
  14703. [&](const char *data, size_t data_length) {
  14704. items.back().content.append(data, data_length);
  14705. return true;
  14706. });
  14707. ASSERT_TRUE(items.size() == 2);
  14708. EXPECT_EQ(items[0].name, "name3");
  14709. EXPECT_EQ(items[0].content, rand1);
  14710. EXPECT_EQ(items[0].filename, "filename3");
  14711. EXPECT_EQ(items[0].content_type, "");
  14712. EXPECT_EQ(items[1].name, "name4");
  14713. EXPECT_EQ(items[1].content, rand2);
  14714. EXPECT_EQ(items[1].filename, "filename4");
  14715. EXPECT_EQ(items[1].content_type, "");
  14716. });
  14717. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14718. const ContentReader &content_reader) {
  14719. ASSERT_TRUE(req.is_multipart_form_data());
  14720. std::vector<FormData> items;
  14721. content_reader(
  14722. [&](const FormData &file) {
  14723. items.push_back(file);
  14724. return true;
  14725. },
  14726. [&](const char *data, size_t data_length) {
  14727. items.back().content.append(data, data_length);
  14728. return true;
  14729. });
  14730. ASSERT_TRUE(items.size() == 4);
  14731. EXPECT_EQ(std::string(items[0].name), "name1");
  14732. EXPECT_EQ(items[0].content, "Testing123");
  14733. EXPECT_EQ(items[0].filename, "filename1");
  14734. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14735. EXPECT_EQ(items[1].name, "name2");
  14736. EXPECT_EQ(items[1].content, "Testing456");
  14737. EXPECT_EQ(items[1].filename, "");
  14738. EXPECT_EQ(items[1].content_type, "");
  14739. EXPECT_EQ(items[2].name, "name3");
  14740. EXPECT_EQ(items[2].content, rand1);
  14741. EXPECT_EQ(items[2].filename, "filename3");
  14742. EXPECT_EQ(items[2].content_type, "");
  14743. EXPECT_EQ(items[3].name, "name4");
  14744. EXPECT_EQ(items[3].content, rand2);
  14745. EXPECT_EQ(items[3].filename, "filename4");
  14746. EXPECT_EQ(items[3].content_type, "");
  14747. });
  14748. auto port = svr.bind_to_any_port("localhost");
  14749. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14750. auto se = detail::scope_exit([&] {
  14751. svr.stop();
  14752. t.join();
  14753. ASSERT_FALSE(svr.is_running());
  14754. });
  14755. svr.wait_until_ready();
  14756. {
  14757. SSLClient cli("localhost", port);
  14758. cli.enable_server_certificate_verification(false);
  14759. UploadFormDataItems items{
  14760. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14761. {"name2", "Testing456", "", ""}, // not a file
  14762. };
  14763. {
  14764. auto res = cli.Post("/post-none", {}, {}, {});
  14765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14766. ASSERT_EQ(StatusCode::OK_200, res->status);
  14767. }
  14768. FormDataProviderItems providers;
  14769. {
  14770. auto res =
  14771. cli.Post("/post-items", {}, items, providers); // empty providers
  14772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14773. ASSERT_EQ(StatusCode::OK_200, res->status);
  14774. }
  14775. providers.push_back({"name3",
  14776. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14777. // test the offset is given correctly at each step
  14778. if (!offset)
  14779. sink.os.write(rand1.data(), 30);
  14780. else if (offset == 30)
  14781. sink.os.write(rand1.data() + 30, 300);
  14782. else if (offset == 330)
  14783. sink.os.write(rand1.data() + 330, 670);
  14784. else if (offset == rand1.size())
  14785. sink.done();
  14786. return true;
  14787. },
  14788. "filename3",
  14789. {}});
  14790. providers.push_back({"name4",
  14791. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14792. // test the offset is given correctly at each step
  14793. if (!offset)
  14794. sink.os.write(rand2.data(), 2000);
  14795. else if (offset == 2000)
  14796. sink.os.write(rand2.data() + 2000, 1);
  14797. else if (offset == 2001)
  14798. sink.os.write(rand2.data() + 2001, 999);
  14799. else if (offset == rand2.size())
  14800. sink.done();
  14801. return true;
  14802. },
  14803. "filename4",
  14804. {}});
  14805. {
  14806. auto res = cli.Post("/post-providers", {}, {}, providers);
  14807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14808. ASSERT_EQ(StatusCode::OK_200, res->status);
  14809. }
  14810. {
  14811. auto res = cli.Post("/post-both", {}, items, providers);
  14812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14813. ASSERT_EQ(StatusCode::OK_200, res->status);
  14814. }
  14815. }
  14816. }
  14817. TEST(MultipartFormDataTest, BadHeader) {
  14818. Server svr;
  14819. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14820. res.set_content("ok", "text/plain");
  14821. });
  14822. thread t = thread([&] { svr.listen(HOST, PORT); });
  14823. auto se = detail::scope_exit([&] {
  14824. svr.stop();
  14825. t.join();
  14826. ASSERT_FALSE(svr.is_running());
  14827. });
  14828. svr.wait_until_ready();
  14829. const std::string body =
  14830. "This is the preamble. It is to be ignored, though it\r\n"
  14831. "is a handy place for composition agents to include an\r\n"
  14832. "explanatory note to non-MIME conformant readers.\r\n"
  14833. "\r\n"
  14834. "\r\n"
  14835. "--simple boundary\r\n"
  14836. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14837. ": BAD...\r\n"
  14838. "\r\n"
  14839. "value1\r\n"
  14840. "--simple boundary\r\n"
  14841. "Content-Disposition: form-data; name=\"field2\"; "
  14842. "filename=\"example.txt\"\r\n"
  14843. "\r\n"
  14844. "value2\r\n"
  14845. "--simple boundary--\r\n"
  14846. "This is the epilogue. It is also to be ignored.\r\n";
  14847. std::string content_type =
  14848. R"(multipart/form-data; boundary="simple boundary")";
  14849. Client cli(HOST, PORT);
  14850. auto res = cli.Post("/post", body, content_type.c_str());
  14851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14852. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14853. }
  14854. TEST(MultipartFormDataTest, WithPreamble) {
  14855. Server svr;
  14856. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14857. res.set_content("ok", "text/plain");
  14858. });
  14859. thread t = thread([&] { svr.listen(HOST, PORT); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop();
  14862. t.join();
  14863. ASSERT_FALSE(svr.is_running());
  14864. });
  14865. svr.wait_until_ready();
  14866. const std::string body =
  14867. "This is the preamble. It is to be ignored, though it\r\n"
  14868. "is a handy place for composition agents to include an\r\n"
  14869. "explanatory note to non-MIME conformant readers.\r\n"
  14870. "\r\n"
  14871. "\r\n"
  14872. "--simple boundary\r\n"
  14873. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14874. "\r\n"
  14875. "value1\r\n"
  14876. "--simple boundary\r\n"
  14877. "Content-Disposition: form-data; name=\"field2\"; "
  14878. "filename=\"example.txt\"\r\n"
  14879. "\r\n"
  14880. "value2\r\n"
  14881. "--simple boundary--\r\n"
  14882. "This is the epilogue. It is also to be ignored.\r\n";
  14883. std::string content_type =
  14884. R"(multipart/form-data; boundary="simple boundary")";
  14885. Client cli(HOST, PORT);
  14886. auto res = cli.Post("/post", body, content_type.c_str());
  14887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14888. EXPECT_EQ(StatusCode::OK_200, res->status);
  14889. }
  14890. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14891. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14892. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14893. const ContentReader &content_reader) {
  14894. if (req.is_multipart_form_data()) {
  14895. std::vector<FormData> items;
  14896. content_reader(
  14897. [&](const FormData &file) {
  14898. items.push_back(file);
  14899. return true;
  14900. },
  14901. [&](const char *data, size_t data_length) {
  14902. items.back().content.append(data, data_length);
  14903. return true;
  14904. });
  14905. EXPECT_TRUE(std::string(items[0].name) == "document");
  14906. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14907. EXPECT_TRUE(items[0].filename == "2MB_data");
  14908. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14909. EXPECT_TRUE(items[1].name == "hello");
  14910. EXPECT_TRUE(items[1].content == "world");
  14911. EXPECT_TRUE(items[1].filename == "");
  14912. EXPECT_TRUE(items[1].content_type == "");
  14913. } else {
  14914. std::string body;
  14915. content_reader([&](const char *data, size_t data_length) {
  14916. body.append(data, data_length);
  14917. return true;
  14918. });
  14919. }
  14920. });
  14921. auto port = svr.bind_to_any_port("localhost");
  14922. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14923. auto se = detail::scope_exit([&] {
  14924. svr.stop();
  14925. t.join();
  14926. ASSERT_FALSE(svr.is_running());
  14927. });
  14928. svr.wait_until_ready();
  14929. {
  14930. std::string data(1024 * 1024 * 2, '.');
  14931. std::stringstream buffer;
  14932. buffer << data;
  14933. SSLClient cli("localhost", port);
  14934. cli.enable_server_certificate_verification(false);
  14935. UploadFormDataItems items{
  14936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14937. {"hello", "world", "", ""},
  14938. };
  14939. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14941. ASSERT_EQ(StatusCode::OK_200, res->status);
  14942. }
  14943. }
  14944. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14945. std::string data(1024 * 1024 * 2, '&');
  14946. std::stringstream buffer;
  14947. buffer << data;
  14948. Client cli("https://localhost:8080");
  14949. UploadFormDataItems items{
  14950. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14951. {"hello", "world", "", ""},
  14952. };
  14953. for (const char &c : " \t\r\n") {
  14954. auto res =
  14955. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14956. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14957. ASSERT_FALSE(res);
  14958. }
  14959. }
  14960. TEST(MultipartFormDataTest, PutFormData) {
  14961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14962. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14963. const ContentReader &content_reader) {
  14964. if (req.is_multipart_form_data()) {
  14965. std::vector<FormData> items;
  14966. content_reader(
  14967. [&](const FormData &file) {
  14968. items.push_back(file);
  14969. return true;
  14970. },
  14971. [&](const char *data, size_t data_length) {
  14972. items.back().content.append(data, data_length);
  14973. return true;
  14974. });
  14975. EXPECT_TRUE(std::string(items[0].name) == "document");
  14976. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14977. EXPECT_TRUE(items[0].filename == "2MB_data");
  14978. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14979. EXPECT_TRUE(items[1].name == "hello");
  14980. EXPECT_TRUE(items[1].content == "world");
  14981. EXPECT_TRUE(items[1].filename == "");
  14982. EXPECT_TRUE(items[1].content_type == "");
  14983. } else {
  14984. std::string body;
  14985. content_reader([&](const char *data, size_t data_length) {
  14986. body.append(data, data_length);
  14987. return true;
  14988. });
  14989. }
  14990. });
  14991. auto port = svr.bind_to_any_port("localhost");
  14992. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14993. auto se = detail::scope_exit([&] {
  14994. svr.stop();
  14995. t.join();
  14996. ASSERT_FALSE(svr.is_running());
  14997. });
  14998. svr.wait_until_ready();
  14999. {
  15000. std::string data(1024 * 1024 * 2, '&');
  15001. std::stringstream buffer;
  15002. buffer << data;
  15003. SSLClient cli("localhost", port);
  15004. cli.enable_server_certificate_verification(false);
  15005. UploadFormDataItems items{
  15006. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15007. {"hello", "world", "", ""},
  15008. };
  15009. auto res = cli.Put("/put", items);
  15010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15011. ASSERT_EQ(StatusCode::OK_200, res->status);
  15012. }
  15013. }
  15014. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15016. svr.Put("/put_customboundary",
  15017. [&](const Request &req, const Response & /*res*/,
  15018. const ContentReader &content_reader) {
  15019. if (req.is_multipart_form_data()) {
  15020. std::vector<FormData> items;
  15021. content_reader(
  15022. [&](const FormData &file) {
  15023. items.push_back(file);
  15024. return true;
  15025. },
  15026. [&](const char *data, size_t data_length) {
  15027. items.back().content.append(data, data_length);
  15028. return true;
  15029. });
  15030. EXPECT_TRUE(std::string(items[0].name) == "document");
  15031. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15032. EXPECT_TRUE(items[0].filename == "2MB_data");
  15033. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15034. EXPECT_TRUE(items[1].name == "hello");
  15035. EXPECT_TRUE(items[1].content == "world");
  15036. EXPECT_TRUE(items[1].filename == "");
  15037. EXPECT_TRUE(items[1].content_type == "");
  15038. } else {
  15039. std::string body;
  15040. content_reader([&](const char *data, size_t data_length) {
  15041. body.append(data, data_length);
  15042. return true;
  15043. });
  15044. }
  15045. });
  15046. auto port = svr.bind_to_any_port("localhost");
  15047. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15048. auto se = detail::scope_exit([&] {
  15049. svr.stop();
  15050. t.join();
  15051. ASSERT_FALSE(svr.is_running());
  15052. });
  15053. svr.wait_until_ready();
  15054. {
  15055. std::string data(1024 * 1024 * 2, '&');
  15056. std::stringstream buffer;
  15057. buffer << data;
  15058. SSLClient cli("localhost", port);
  15059. cli.enable_server_certificate_verification(false);
  15060. UploadFormDataItems items{
  15061. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15062. {"hello", "world", "", ""},
  15063. };
  15064. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15066. ASSERT_EQ(StatusCode::OK_200, res->status);
  15067. }
  15068. }
  15069. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15070. std::string data(1024 * 1024 * 2, '&');
  15071. std::stringstream buffer;
  15072. buffer << data;
  15073. Client cli("https://localhost:8080");
  15074. cli.enable_server_certificate_verification(false);
  15075. UploadFormDataItems items{
  15076. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15077. {"hello", "world", "", ""},
  15078. };
  15079. for (const char &c : " \t\r\n") {
  15080. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15081. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15082. ASSERT_FALSE(res);
  15083. }
  15084. }
  15085. TEST(MultipartFormDataTest, AlternateFilename) {
  15086. auto handled = false;
  15087. Server svr;
  15088. svr.Post("/test", [&](const Request &req, Response &res) {
  15089. ASSERT_EQ(2u, req.form.files.size());
  15090. ASSERT_EQ(1u, req.form.fields.size());
  15091. // Test files
  15092. const auto &file1 = req.form.get_file("file1");
  15093. ASSERT_EQ("file1", file1.name);
  15094. ASSERT_EQ("A.txt", file1.filename);
  15095. ASSERT_EQ("text/plain", file1.content_type);
  15096. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15097. const auto &file2 = req.form.get_file("file2");
  15098. ASSERT_EQ("file2", file2.name);
  15099. ASSERT_EQ("a.html", file2.filename);
  15100. ASSERT_EQ("text/html", file2.content_type);
  15101. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15102. file2.content);
  15103. // Test text field
  15104. const auto &text = req.form.get_field("text");
  15105. ASSERT_EQ("text default", text);
  15106. res.set_content("ok", "text/plain");
  15107. handled = true;
  15108. });
  15109. thread t = thread([&] { svr.listen(HOST, PORT); });
  15110. auto se = detail::scope_exit([&] {
  15111. svr.stop();
  15112. t.join();
  15113. ASSERT_FALSE(svr.is_running());
  15114. ASSERT_TRUE(handled);
  15115. });
  15116. svr.wait_until_ready();
  15117. auto req = "POST /test HTTP/1.1\r\n"
  15118. "Host: localhost\r\n"
  15119. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15120. "Content-Length: 399\r\n"
  15121. "\r\n"
  15122. "----------\r\n"
  15123. "Content-Disposition: form-data; name=\"text\"\r\n"
  15124. "\r\n"
  15125. "text default\r\n"
  15126. "----------\r\n"
  15127. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15128. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15129. "Content-Type: text/plain\r\n"
  15130. "\r\n"
  15131. "Content of a.txt.\r\n"
  15132. "\r\n"
  15133. "----------\r\n"
  15134. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15135. "\"a.html\"\r\n"
  15136. "Content-Type: text/html\r\n"
  15137. "\r\n"
  15138. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15139. "\r\n"
  15140. "------------\r\n";
  15141. ASSERT_TRUE(send_request(1, req));
  15142. }
  15143. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15144. auto handled = false;
  15145. Server svr;
  15146. svr.Post("/test", [&](const Request &req, Response &res) {
  15147. // Case-insensitive "utf-8''" prefix with a long value
  15148. const auto &file = req.form.get_file("file1");
  15149. ASSERT_EQ("file1", file.name);
  15150. // 8000 chars exercises both the Content-Disposition parser and the
  15151. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15152. // Prior to the fix, std::regex_match on this header would cause O(N)
  15153. // stack recursion in libstdc++, leading to SIGSEGV.
  15154. std::string expected_filename(8000, 'A');
  15155. ASSERT_EQ(expected_filename, file.filename);
  15156. res.set_content("ok", "text/plain");
  15157. handled = true;
  15158. });
  15159. thread t = thread([&] { svr.listen(HOST, PORT); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. ASSERT_FALSE(svr.is_running());
  15164. ASSERT_TRUE(handled);
  15165. });
  15166. svr.wait_until_ready();
  15167. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15168. // Regression test for GHSA-qq6v-r583-3h69
  15169. std::string long_filename(8000, 'A');
  15170. std::string body = "----------\r\n"
  15171. "Content-Disposition: form-data; name=\"file1\"; "
  15172. "filename*=\"Utf-8''" +
  15173. long_filename +
  15174. "\"\r\n"
  15175. "\r\n"
  15176. "hello\r\n"
  15177. "------------\r\n";
  15178. auto req = "POST /test HTTP/1.1\r\n"
  15179. "Host: localhost\r\n"
  15180. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15181. "Content-Length: " +
  15182. std::to_string(body.size()) + "\r\n\r\n" + body;
  15183. ASSERT_TRUE(send_request(1, req));
  15184. }
  15185. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15186. auto handled = false;
  15187. Server svr;
  15188. svr.Post("/test", [&](const Request &req, Response &) {
  15189. ASSERT_EQ(2u, req.form.fields.size());
  15190. const auto &text1 = req.form.get_field("text1");
  15191. ASSERT_EQ("text1", text1);
  15192. const auto &text2 = req.form.get_field("text2");
  15193. ASSERT_EQ("text2", text2);
  15194. handled = true;
  15195. });
  15196. thread t = thread([&] { svr.listen(HOST, PORT); });
  15197. auto se = detail::scope_exit([&] {
  15198. svr.stop();
  15199. t.join();
  15200. ASSERT_FALSE(svr.is_running());
  15201. ASSERT_TRUE(handled);
  15202. });
  15203. svr.wait_until_ready();
  15204. auto req = "POST /test HTTP/1.1\r\n"
  15205. "Host: localhost\r\n"
  15206. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15207. "Content-Length: 146\r\n"
  15208. "\r\n----------\r\n"
  15209. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15210. "\r\n"
  15211. "text1"
  15212. "\r\n----------\r\n"
  15213. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15214. "\r\n"
  15215. "text2"
  15216. "\r\n------------";
  15217. std::string response;
  15218. ASSERT_TRUE(send_request(1, req, &response));
  15219. ASSERT_EQ("200", response.substr(9, 3));
  15220. }
  15221. TEST(MultipartFormDataTest, ContentLength) {
  15222. auto handled = false;
  15223. Server svr;
  15224. svr.Post("/test", [&](const Request &req, Response &) {
  15225. ASSERT_EQ(2u, req.form.fields.size());
  15226. const auto &text1 = req.form.get_field("text1");
  15227. ASSERT_EQ("text1", text1);
  15228. const auto &text2 = req.form.get_field("text2");
  15229. ASSERT_EQ("text2", text2);
  15230. handled = true;
  15231. });
  15232. thread t = thread([&] { svr.listen(HOST, PORT); });
  15233. auto se = detail::scope_exit([&] {
  15234. svr.stop();
  15235. t.join();
  15236. ASSERT_FALSE(svr.is_running());
  15237. ASSERT_TRUE(handled);
  15238. });
  15239. svr.wait_until_ready();
  15240. auto req = "POST /test HTTP/1.1\r\n"
  15241. "Host: localhost\r\n"
  15242. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15243. "Content-Length: 167\r\n"
  15244. "\r\n----------\r\n"
  15245. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15246. "Content-Length: 5\r\n"
  15247. "\r\n"
  15248. "text1"
  15249. "\r\n----------\r\n"
  15250. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15251. "\r\n"
  15252. "text2"
  15253. "\r\n------------\r\n";
  15254. std::string response;
  15255. ASSERT_TRUE(send_request(1, req, &response));
  15256. ASSERT_EQ("200", response.substr(9, 3));
  15257. }
  15258. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15259. auto handled = false;
  15260. Server svr;
  15261. svr.Post("/test", [&](const Request &req, Response &) {
  15262. ASSERT_EQ(2u, req.form.fields.size());
  15263. const auto &text1 = req.form.get_field("text1");
  15264. ASSERT_EQ("text1", text1);
  15265. // TODO: Add header access for text fields if needed
  15266. const auto &text2 = req.form.get_field("text2");
  15267. ASSERT_EQ("text2", text2);
  15268. // TODO: Header access for text fields needs to be implemented
  15269. // auto &headers = it->second.headers;
  15270. // ASSERT_EQ(3U, headers.size());
  15271. // auto custom_header = headers.find("x-whatever");
  15272. // ASSERT_TRUE(custom_header != headers.end());
  15273. // ASSERT_NE("customvalue", custom_header->second);
  15274. // ASSERT_EQ("CustomValue", custom_header->second);
  15275. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15276. handled = true;
  15277. });
  15278. thread t = thread([&] { svr.listen(HOST, PORT); });
  15279. auto se = detail::scope_exit([&] {
  15280. svr.stop();
  15281. t.join();
  15282. ASSERT_FALSE(svr.is_running());
  15283. ASSERT_TRUE(handled);
  15284. });
  15285. svr.wait_until_ready();
  15286. auto req = "POST /test HTTP/1.1\r\n"
  15287. "Host: localhost\r\n"
  15288. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15289. "Content-Length: 232\r\n"
  15290. "\r\n----------\r\n"
  15291. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15292. "Content-Length: 5\r\n"
  15293. "X-Test: 1\r\n"
  15294. "\r\n"
  15295. "text1"
  15296. "\r\n----------\r\n"
  15297. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15298. "Content-Type: text/plain\r\n"
  15299. "X-Whatever: CustomValue\r\n"
  15300. "\r\n"
  15301. "text2"
  15302. "\r\n------------\r\n"
  15303. "That should be disregarded. Not even read";
  15304. std::string response;
  15305. ASSERT_TRUE(send_request(1, req, &response));
  15306. ASSERT_EQ("200", response.substr(9, 3));
  15307. }
  15308. TEST(MultipartFormDataTest, LargeHeader) {
  15309. auto handled = false;
  15310. Server svr;
  15311. svr.Post("/test", [&](const Request &req, Response &) {
  15312. ASSERT_EQ(1u, req.form.fields.size());
  15313. const auto &text = req.form.get_field("name1");
  15314. ASSERT_EQ("text1", text);
  15315. handled = true;
  15316. });
  15317. thread t = thread([&] { svr.listen(HOST, PORT); });
  15318. auto se = detail::scope_exit([&] {
  15319. svr.stop();
  15320. t.join();
  15321. ASSERT_FALSE(svr.is_running());
  15322. ASSERT_TRUE(handled);
  15323. });
  15324. svr.wait_until_ready();
  15325. auto boundary = std::string("cpp-httplib-multipart-data");
  15326. std::string content = "--" + boundary +
  15327. "\r\n"
  15328. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15329. "\r\n"
  15330. "text1\r\n"
  15331. "--" +
  15332. boundary + "--\r\n";
  15333. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15334. "Host: localhost\r\n"
  15335. "Content-Type: multipart/form-data;boundary=" +
  15336. boundary +
  15337. "\r\n"
  15338. "Content-Length: " +
  15339. std::to_string(content.size()) +
  15340. "\r\n"
  15341. "Dummy-Header: ";
  15342. std::string header_suffix = "\r\n"
  15343. "\r\n";
  15344. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15345. size_t header_dummy_size =
  15346. read_buff_size -
  15347. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15348. auto header_dummy = std::string(header_dummy_size, '@');
  15349. auto req = header_prefix + header_dummy + header_suffix + content;
  15350. std::string response;
  15351. ASSERT_TRUE(send_request(1, req, &response));
  15352. ASSERT_EQ("200", response.substr(9, 3));
  15353. }
  15354. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15355. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15356. // (not chunked Transfer-Encoding) after the streaming refactor.
  15357. auto handled = false;
  15358. Server svr;
  15359. svr.Post("/upload", [&](const Request &req, Response &res) {
  15360. auto cl_it = req.headers.find("Content-Length");
  15361. EXPECT_TRUE(cl_it != req.headers.end());
  15362. auto te_it = req.headers.find("Transfer-Encoding");
  15363. EXPECT_TRUE(te_it == req.headers.end());
  15364. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15365. res.set_content("ok", "text/plain");
  15366. handled = true;
  15367. });
  15368. auto port = svr.bind_to_any_port(HOST);
  15369. auto t = thread([&] { svr.listen_after_bind(); });
  15370. auto se = detail::scope_exit([&] {
  15371. svr.stop();
  15372. t.join();
  15373. ASSERT_FALSE(svr.is_running());
  15374. ASSERT_TRUE(handled);
  15375. });
  15376. svr.wait_until_ready();
  15377. UploadFormDataItems items = {
  15378. {"field1", "hello", "", "text/plain"},
  15379. {"file1", "world", "test.txt", "application/octet-stream"},
  15380. };
  15381. Client cli(HOST, port);
  15382. auto res = cli.Post("/upload", {}, items);
  15383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15384. EXPECT_EQ(StatusCode::OK_200, res->status);
  15385. }
  15386. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15387. // Verify that make_multipart_content_provider coalesces many small segments
  15388. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15389. constexpr size_t kItemCount = 1000;
  15390. UploadFormDataItems items;
  15391. items.reserve(kItemCount);
  15392. for (size_t i = 0; i < kItemCount; i++) {
  15393. items.push_back(
  15394. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15395. }
  15396. const std::string boundary = "----test-boundary";
  15397. auto content_length = detail::get_multipart_content_length(items, boundary);
  15398. auto provider = detail::make_multipart_content_provider(items, boundary);
  15399. // Drive the provider the same way write_content_with_progress does
  15400. size_t write_count = 0;
  15401. size_t total_bytes = 0;
  15402. DataSink sink;
  15403. size_t offset = 0;
  15404. sink.write = [&](const char *d, size_t l) -> bool {
  15405. (void)d;
  15406. write_count++;
  15407. total_bytes += l;
  15408. offset += l;
  15409. return true;
  15410. };
  15411. sink.is_writable = []() -> bool { return true; };
  15412. while (offset < content_length) {
  15413. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15414. }
  15415. EXPECT_EQ(content_length, total_bytes);
  15416. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15417. // With buffering into 64KB blocks, write_count should be much smaller.
  15418. auto segment_count = 3 * kItemCount + 1;
  15419. EXPECT_LT(write_count, segment_count / 10);
  15420. }
  15421. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15422. // Integration test: send many UploadFormDataItems and verify the server
  15423. // receives all of them correctly (#2410).
  15424. constexpr size_t kItemCount = 500;
  15425. auto handled = false;
  15426. Server svr;
  15427. svr.Post("/upload", [&](const Request &req, Response &res) {
  15428. EXPECT_EQ(kItemCount, req.form.fields.size());
  15429. for (size_t i = 0; i < kItemCount; i++) {
  15430. auto key = "field" + std::to_string(i);
  15431. auto val = "value" + std::to_string(i);
  15432. auto it = req.form.fields.find(key);
  15433. if (it != req.form.fields.end()) {
  15434. EXPECT_EQ(val, it->second.content);
  15435. } else {
  15436. ADD_FAILURE() << "Missing field: " << key;
  15437. }
  15438. }
  15439. res.set_content("ok", "text/plain");
  15440. handled = true;
  15441. });
  15442. auto port = svr.bind_to_any_port(HOST);
  15443. auto t = thread([&] { svr.listen_after_bind(); });
  15444. auto se = detail::scope_exit([&] {
  15445. svr.stop();
  15446. t.join();
  15447. ASSERT_FALSE(svr.is_running());
  15448. ASSERT_TRUE(handled);
  15449. });
  15450. svr.wait_until_ready();
  15451. UploadFormDataItems items;
  15452. items.reserve(kItemCount);
  15453. for (size_t i = 0; i < kItemCount; i++) {
  15454. items.push_back(
  15455. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15456. }
  15457. Client cli(HOST, port);
  15458. auto res = cli.Post("/upload", items);
  15459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15460. EXPECT_EQ(StatusCode::OK_200, res->status);
  15461. }
  15462. TEST(MultipartFormDataTest, MakeFileProvider) {
  15463. // Verify make_file_provider sends a file's contents correctly.
  15464. const std::string file_content(4096, 'Z');
  15465. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15466. {
  15467. std::ofstream ofs(tmp_path, std::ios::binary);
  15468. ofs.write(file_content.data(),
  15469. static_cast<std::streamsize>(file_content.size()));
  15470. }
  15471. auto handled = false;
  15472. Server svr;
  15473. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15474. const ContentReader &content_reader) {
  15475. ASSERT_TRUE(req.is_multipart_form_data());
  15476. std::vector<FormData> items;
  15477. content_reader(
  15478. [&](const FormData &file) {
  15479. items.push_back(file);
  15480. return true;
  15481. },
  15482. [&](const char *data, size_t data_length) {
  15483. items.back().content.append(data, data_length);
  15484. return true;
  15485. });
  15486. ASSERT_EQ(1u, items.size());
  15487. EXPECT_EQ("myfile", items[0].name);
  15488. EXPECT_EQ("data.bin", items[0].filename);
  15489. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15490. EXPECT_EQ(file_content, items[0].content);
  15491. handled = true;
  15492. });
  15493. auto port = svr.bind_to_any_port(HOST);
  15494. auto t = thread([&] { svr.listen_after_bind(); });
  15495. auto se = detail::scope_exit([&] {
  15496. svr.stop();
  15497. t.join();
  15498. ASSERT_FALSE(svr.is_running());
  15499. ASSERT_TRUE(handled);
  15500. std::remove(tmp_path.c_str());
  15501. });
  15502. svr.wait_until_ready();
  15503. FormDataProviderItems providers;
  15504. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15505. "application/octet-stream"));
  15506. Client cli(HOST, port);
  15507. auto res = cli.Post("/upload", {}, {}, providers);
  15508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15509. EXPECT_EQ(StatusCode::OK_200, res->status);
  15510. }
  15511. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15512. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15513. // (100) headers is rejected with a 400 Bad Request response.
  15514. Server svr;
  15515. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15516. res.set_content("ok", "text/plain");
  15517. });
  15518. thread t = thread([&] { svr.listen(HOST, PORT); });
  15519. auto se = detail::scope_exit([&] {
  15520. svr.stop();
  15521. t.join();
  15522. ASSERT_FALSE(svr.is_running());
  15523. });
  15524. svr.wait_until_ready();
  15525. // Build a multipart part with 101 custom headers (exceeding
  15526. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15527. std::stringstream body;
  15528. body << "--simpleboundary\r\n"
  15529. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15530. for (int i = 0; i < 101; i++) {
  15531. body << "X-Custom-Header-" << i << ": value\r\n";
  15532. }
  15533. body << "\r\n"
  15534. << "value1\r\n"
  15535. << "--simpleboundary--\r\n";
  15536. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15537. Client cli(HOST, PORT);
  15538. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15540. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15541. }
  15542. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15543. // A body that never contains the declared boundary must not be accumulated
  15544. // while the parser waits for it. Buffering it would also make every read
  15545. // rescan everything seen so far, which is quadratic in the body size.
  15546. Server svr;
  15547. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15548. res.set_content("ok", "text/plain");
  15549. });
  15550. auto port = svr.bind_to_any_port(HOST);
  15551. thread t = thread([&] { svr.listen_after_bind(); });
  15552. auto se = detail::scope_exit([&] {
  15553. svr.stop();
  15554. t.join();
  15555. ASSERT_FALSE(svr.is_running());
  15556. });
  15557. svr.wait_until_ready();
  15558. Client cli(HOST, port);
  15559. cli.set_read_timeout(60, 0);
  15560. cli.set_write_timeout(60, 0);
  15561. // '-' is the worst case: it matches the first character of the boundary, so
  15562. // every position has to be checked against it.
  15563. auto post_dashes = [&](size_t size) {
  15564. const std::string body(size, '-');
  15565. auto start = std::chrono::steady_clock::now();
  15566. auto res =
  15567. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15568. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15569. std::chrono::steady_clock::now() - start)
  15570. .count();
  15571. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15572. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15573. return ms;
  15574. };
  15575. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15576. // Windows.
  15577. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15578. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15579. // Comparing the two sizes rather than checking an absolute duration keeps
  15580. // this meaningful across build types and CI load, both of which move the
  15581. // absolute numbers by more than an order of magnitude. Four times the bytes
  15582. // costs about four times the time when parsing is linear, and about sixteen
  15583. // times when the body is buffered and rescanned.
  15584. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15585. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15586. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15587. << "ms, which suggests the body is being buffered and rescanned";
  15588. }
  15589. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15590. // A boundary can only be followed by CRLF or by "--", so anything else is
  15591. // malformed no matter what comes next. The parser must say so right away
  15592. // instead of buffering the rest of the declared body.
  15593. Server svr;
  15594. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15595. res.set_content("ok", "text/plain");
  15596. });
  15597. auto port = svr.bind_to_any_port(HOST);
  15598. thread t = thread([&] { svr.listen_after_bind(); });
  15599. auto se = detail::scope_exit([&] {
  15600. svr.stop();
  15601. t.join();
  15602. ASSERT_FALSE(svr.is_running());
  15603. });
  15604. svr.wait_until_ready();
  15605. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15606. // buffers instead of failing would still be waiting for the remaining bytes.
  15607. const std::string body = "--zzzz\r\n"
  15608. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15609. "\r\n"
  15610. "text1"
  15611. "\r\n--zzzzXX";
  15612. const std::string req = "POST /post HTTP/1.1\r\n"
  15613. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15614. "Content-Length: 1048576\r\n"
  15615. "\r\n" +
  15616. body;
  15617. std::string response;
  15618. ASSERT_TRUE(send_request(3, req, &response, port));
  15619. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15620. EXPECT_EQ("400", response.substr(9, 3));
  15621. }
  15622. // Posts a multipart body split into two writes, so that the server sees the
  15623. // split at whatever offset the caller chose, and expects the single "text1"
  15624. // field to come through.
  15625. static void expect_split_multipart_ok(const std::string &body1,
  15626. const std::string &body2) {
  15627. auto handled = false;
  15628. Server svr;
  15629. svr.Post("/post", [&](const Request &req, Response &) {
  15630. EXPECT_EQ(1u, req.form.fields.size());
  15631. EXPECT_EQ("text1", req.form.get_field("text1"));
  15632. handled = true;
  15633. });
  15634. auto port = svr.bind_to_any_port(HOST);
  15635. thread t = thread([&] { svr.listen_after_bind(); });
  15636. auto se = detail::scope_exit([&] {
  15637. svr.stop();
  15638. t.join();
  15639. ASSERT_FALSE(svr.is_running());
  15640. ASSERT_TRUE(handled);
  15641. });
  15642. svr.wait_until_ready();
  15643. // "Connection: close" makes the server close once it has answered, so the
  15644. // response drain ends immediately instead of idling until the read timeout.
  15645. const std::string head =
  15646. "POST /post HTTP/1.1\r\n"
  15647. "Host: localhost\r\n"
  15648. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15649. "Connection: close\r\n"
  15650. "Content-Length: " +
  15651. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15652. std::string response;
  15653. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15654. ASSERT_GE(response.size(), 12u) << "no response";
  15655. EXPECT_EQ("200", response.substr(9, 3));
  15656. }
  15657. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15658. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15659. // ignored, including when it does not arrive in the same read as the
  15660. // close-delimiter itself.
  15661. expect_split_multipart_ok("--zzzz\r\n"
  15662. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15663. "\r\n"
  15664. "text1"
  15665. "\r\n--zzzz--",
  15666. "\r\nthis epilogue must be ignored\r\n");
  15667. }
  15668. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15669. // The initial boundary may be preceded by a preamble of any length and may
  15670. // straddle a read boundary. Discarding data while waiting for it must not
  15671. // throw away a partial boundary sitting at the end of the buffer.
  15672. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15673. "zz\r\n"
  15674. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15675. "\r\n"
  15676. "text1"
  15677. "\r\n--zzzz--\r\n");
  15678. }
  15679. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15680. // The received boundary was only checked for being non-empty, so it could be
  15681. // as long as a header is allowed to be. The parser scans the body for
  15682. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15683. // costs a nearly full comparison at nearly every position, making the
  15684. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15685. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15686. Server svr;
  15687. svr.Post("/post", [](const Request &req, Response &res) {
  15688. EXPECT_EQ(1u, req.form.fields.size());
  15689. EXPECT_EQ("text1", req.form.get_field("text1"));
  15690. res.set_content("ok", "text/plain");
  15691. });
  15692. auto port = svr.bind_to_any_port(HOST);
  15693. thread t = thread([&] { svr.listen_after_bind(); });
  15694. auto se = detail::scope_exit([&] {
  15695. svr.stop();
  15696. t.join();
  15697. ASSERT_FALSE(svr.is_running());
  15698. });
  15699. svr.wait_until_ready();
  15700. Client cli(HOST, port);
  15701. auto post_with_boundary_of_length = [&](size_t len) {
  15702. const std::string boundary(len, 'a');
  15703. const std::string body =
  15704. "--" + boundary +
  15705. "\r\n"
  15706. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15707. "\r\n"
  15708. "text1"
  15709. "\r\n--" +
  15710. boundary + "--\r\n";
  15711. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15712. };
  15713. auto res = post_with_boundary_of_length(70);
  15714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15715. EXPECT_EQ(StatusCode::OK_200, res->status);
  15716. res = post_with_boundary_of_length(71);
  15717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15718. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15719. }
  15720. TEST(MakeFileBodyTest, Basic) {
  15721. const std::string file_content(4096, 'Z');
  15722. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15723. {
  15724. std::ofstream ofs(tmp_path, std::ios::binary);
  15725. ofs.write(file_content.data(),
  15726. static_cast<std::streamsize>(file_content.size()));
  15727. }
  15728. auto handled = false;
  15729. Server svr;
  15730. svr.Post("/upload", [&](const Request &req, Response &res) {
  15731. EXPECT_EQ(file_content, req.body);
  15732. handled = true;
  15733. res.status = StatusCode::OK_200;
  15734. });
  15735. auto port = svr.bind_to_any_port(HOST);
  15736. auto t = thread([&] { svr.listen_after_bind(); });
  15737. auto se = detail::scope_exit([&] {
  15738. svr.stop();
  15739. t.join();
  15740. ASSERT_FALSE(svr.is_running());
  15741. ASSERT_TRUE(handled);
  15742. std::remove(tmp_path.c_str());
  15743. });
  15744. svr.wait_until_ready();
  15745. auto fb = make_file_body(tmp_path);
  15746. ASSERT_GT(fb.first, 0u);
  15747. Client cli(HOST, port);
  15748. auto res =
  15749. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15751. EXPECT_EQ(StatusCode::OK_200, res->status);
  15752. }
  15753. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15754. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15755. {
  15756. std::ofstream ofs(path, std::ios::binary);
  15757. const std::string content(100, 'A');
  15758. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15759. }
  15760. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15761. auto body = make_file_body(path);
  15762. ASSERT_EQ(100u, body.first);
  15763. ASSERT_TRUE(static_cast<bool>(body.second));
  15764. // Rewritten shorter after its length was measured - and, on a server, after
  15765. // that length has already gone out as Content-Length.
  15766. {
  15767. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15768. const std::string content(10, 'A');
  15769. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15770. }
  15771. std::string written;
  15772. DataSink sink;
  15773. sink.write = [&](const char *d, size_t l) {
  15774. written.append(d, l);
  15775. return true;
  15776. };
  15777. // The provider has to report failure. write_content_with_progress() advances
  15778. // its offset only by what was written, so a provider that returns true
  15779. // without completing the length it promised is called again straight away,
  15780. // and again.
  15781. EXPECT_FALSE(body.second(0, body.first, sink));
  15782. EXPECT_EQ(std::string(10, 'A'), written);
  15783. }
  15784. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15785. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15786. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15787. {
  15788. std::ofstream ofs(path, std::ios::binary);
  15789. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15790. }
  15791. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15792. auto body = make_file_body(path);
  15793. ASSERT_EQ(content.size(), body.first);
  15794. ASSERT_TRUE(static_cast<bool>(body.second));
  15795. std::string written;
  15796. DataSink sink;
  15797. sink.write = [&](const char *d, size_t l) {
  15798. written.append(d, l);
  15799. return true;
  15800. };
  15801. EXPECT_TRUE(body.second(0, body.first, sink));
  15802. EXPECT_EQ(content, written);
  15803. }
  15804. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15805. static constexpr unsigned int number_of_tasks{1000000};
  15806. std::atomic_uint count{0};
  15807. std::unique_ptr<TaskQueue> task_queue{
  15808. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15809. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15810. auto queued = task_queue->enqueue(
  15811. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15812. EXPECT_TRUE(queued);
  15813. }
  15814. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15815. task_queue->shutdown();
  15816. #else
  15817. EXPECT_NO_THROW(task_queue->shutdown());
  15818. #endif
  15819. EXPECT_EQ(number_of_tasks, count.load());
  15820. }
  15821. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15822. static constexpr unsigned int number_of_tasks{1000000};
  15823. static constexpr unsigned int qlimit{2};
  15824. unsigned int queued_count{0};
  15825. std::atomic_uint count{0};
  15826. std::unique_ptr<TaskQueue> task_queue{
  15827. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15828. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15829. if (task_queue->enqueue(
  15830. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15831. queued_count++;
  15832. }
  15833. }
  15834. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15835. task_queue->shutdown();
  15836. #else
  15837. EXPECT_NO_THROW(task_queue->shutdown());
  15838. #endif
  15839. EXPECT_EQ(queued_count, count.load());
  15840. EXPECT_TRUE(queued_count <= number_of_tasks);
  15841. EXPECT_TRUE(queued_count >= qlimit);
  15842. }
  15843. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15844. // Use a short idle timeout so a dynamic thread spawns, times out and
  15845. // exits during the test, and the pool keeps working afterwards.
  15846. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15847. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15848. /*idle_timeout_sec=*/1}};
  15849. std::atomic_uint count{0};
  15850. std::condition_variable cv;
  15851. std::mutex mtx;
  15852. bool release = false;
  15853. // Block the base thread so the second task spawns a dynamic thread.
  15854. EXPECT_TRUE(task_queue->enqueue([&] {
  15855. std::unique_lock<std::mutex> lock(mtx);
  15856. while (!release) {
  15857. cv.wait(lock);
  15858. }
  15859. count++;
  15860. }));
  15861. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15862. // Let the dynamic thread finish its task and exceed the idle timeout.
  15863. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15864. {
  15865. std::unique_lock<std::mutex> lock(mtx);
  15866. release = true;
  15867. }
  15868. cv.notify_all();
  15869. // The pool must still accept and run tasks after the dynamic thread exited.
  15870. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15871. task_queue->shutdown();
  15872. EXPECT_EQ(3u, count.load());
  15873. }
  15874. TEST(TaskQueueTest, MaxQueuedRequests) {
  15875. static constexpr unsigned int qlimit{3};
  15876. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15877. std::condition_variable sem_cv;
  15878. std::mutex sem_mtx;
  15879. int credits = 0;
  15880. bool queued;
  15881. /* Fill up the queue with tasks that will block until we give them credits to
  15882. * complete. */
  15883. for (unsigned int n = 0; n <= qlimit;) {
  15884. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15885. std::unique_lock<std::mutex> lock(sem_mtx);
  15886. while (credits <= 0) {
  15887. sem_cv.wait(lock);
  15888. }
  15889. /* Consume the credit and signal the test code if they are all gone. */
  15890. if (--credits == 0) { sem_cv.notify_one(); }
  15891. });
  15892. if (n < qlimit) {
  15893. /* The first qlimit enqueues must succeed. */
  15894. EXPECT_TRUE(queued);
  15895. } else {
  15896. /* The last one will succeed only when the worker thread
  15897. * starts and dequeues the first blocking task. Although
  15898. * not necessary for the correctness of this test, we sleep for
  15899. * a short while to avoid busy waiting. */
  15900. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15901. }
  15902. if (queued) { n++; }
  15903. }
  15904. /* Further enqueues must fail since the queue is full. */
  15905. for (auto i = 0; i < 4; i++) {
  15906. queued = task_queue->enqueue([] {});
  15907. EXPECT_FALSE(queued);
  15908. }
  15909. /* Give the credits to allow the previous tasks to complete. */
  15910. {
  15911. std::unique_lock<std::mutex> lock(sem_mtx);
  15912. credits += qlimit + 1;
  15913. }
  15914. sem_cv.notify_all();
  15915. /* Wait for all the credits to be consumed. */
  15916. {
  15917. std::unique_lock<std::mutex> lock(sem_mtx);
  15918. while (credits > 0) {
  15919. sem_cv.wait(lock);
  15920. }
  15921. }
  15922. /* Check that we are able again to enqueue at least qlimit tasks. */
  15923. for (unsigned int i = 0; i < qlimit; i++) {
  15924. queued = task_queue->enqueue([] {});
  15925. EXPECT_TRUE(queued);
  15926. }
  15927. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15928. task_queue->shutdown();
  15929. #else
  15930. EXPECT_NO_THROW(task_queue->shutdown());
  15931. #endif
  15932. }
  15933. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15934. Server svr;
  15935. std::string method;
  15936. std::string body;
  15937. auto has_content_length = false;
  15938. auto has_transfer_encoding = false;
  15939. std::atomic<int> bad_requests{0};
  15940. // Leftover body bytes get parsed as a malformed request and answered with
  15941. // 400
  15942. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15943. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15944. });
  15945. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15946. res.set_redirect("/down", StatusCode::SeeOther_303);
  15947. });
  15948. svr.Get("/down", [&](const Request &req, Response &res) {
  15949. method = req.method;
  15950. body = req.body;
  15951. has_content_length = req.has_header("Content-Length");
  15952. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15953. res.set_content("ok", "text/plain");
  15954. });
  15955. auto port = svr.bind_to_any_port(HOST);
  15956. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15957. auto se = detail::scope_exit([&] {
  15958. svr.stop();
  15959. thread.join();
  15960. ASSERT_FALSE(svr.is_running());
  15961. });
  15962. svr.wait_until_ready();
  15963. const std::string payload = "SECRET-BODY";
  15964. auto check = [&](Client &cli, const Result &res) {
  15965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15966. EXPECT_EQ(StatusCode::OK_200, res->status);
  15967. EXPECT_EQ("ok", res->body);
  15968. EXPECT_EQ("GET", method);
  15969. EXPECT_TRUE(body.empty());
  15970. EXPECT_FALSE(has_content_length);
  15971. EXPECT_FALSE(has_transfer_encoding);
  15972. // Nothing of the original body may be left on the connection
  15973. auto res2 = cli.Get("/down");
  15974. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15975. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15976. EXPECT_EQ("ok", res2->body);
  15977. EXPECT_EQ(0, bad_requests);
  15978. };
  15979. // With content length
  15980. {
  15981. Client cli(HOST, port);
  15982. cli.set_keep_alive(true);
  15983. cli.set_follow_location(true);
  15984. auto res = cli.Post(
  15985. "/up", payload.size(),
  15986. [&](size_t offset, size_t length, DataSink &sink) {
  15987. return sink.write(payload.data() + offset, length);
  15988. },
  15989. "text/plain");
  15990. check(cli, res);
  15991. }
  15992. // Without content length (chunked)
  15993. {
  15994. Client cli(HOST, port);
  15995. cli.set_keep_alive(true);
  15996. cli.set_follow_location(true);
  15997. auto res = cli.Post(
  15998. "/up",
  15999. [&](size_t /*offset*/, DataSink &sink) {
  16000. sink.write(payload.data(), payload.size());
  16001. sink.done();
  16002. return true;
  16003. },
  16004. "text/plain");
  16005. check(cli, res);
  16006. }
  16007. }
  16008. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16009. Server svr;
  16010. std::string target;
  16011. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16012. // Echo the still-encoded name back in the Location
  16013. const std::string prefix = "/start/";
  16014. res.status = StatusCode::Found_302;
  16015. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16016. });
  16017. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16018. target = req.target;
  16019. res.set_content("ok", "text/plain");
  16020. });
  16021. auto port = svr.bind_to_any_port(HOST);
  16022. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16023. auto se = detail::scope_exit([&] {
  16024. svr.stop();
  16025. thread.join();
  16026. ASSERT_FALSE(svr.is_running());
  16027. });
  16028. svr.wait_until_ready();
  16029. // Decoding the Location path would turn the first four into a path
  16030. // separator, a query delimiter, a fragment delimiter and a different
  16031. // percent-encoded octet. The rest must keep reaching the server as they are.
  16032. const std::vector<std::string> names = {
  16033. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16034. };
  16035. for (auto path_encode : {true, false}) {
  16036. Client cli(HOST, port);
  16037. cli.set_follow_location(true);
  16038. cli.set_path_encode(path_encode);
  16039. for (const auto &name : names) {
  16040. target.clear();
  16041. auto res = cli.Get("/start/" + name);
  16042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16043. EXPECT_EQ(StatusCode::OK_200, res->status);
  16044. EXPECT_EQ("/dest/" + name, target);
  16045. }
  16046. }
  16047. }
  16048. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16049. Server svr;
  16050. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16051. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16052. });
  16053. svr.Get("/hello", [](const Request &req, Response &res) {
  16054. res.set_content(req.get_param_value("key"), "text/plain");
  16055. });
  16056. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16057. auto se = detail::scope_exit([&] {
  16058. svr.stop();
  16059. thread.join();
  16060. ASSERT_FALSE(svr.is_running());
  16061. });
  16062. svr.wait_until_ready();
  16063. {
  16064. Client cli(HOST, PORT);
  16065. cli.set_follow_location(true);
  16066. auto res = cli.Get("/");
  16067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16068. EXPECT_EQ(StatusCode::OK_200, res->status);
  16069. EXPECT_EQ("val&key2=val2", res->body);
  16070. }
  16071. }
  16072. #endif
  16073. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16074. Server svr;
  16075. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16076. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16077. });
  16078. svr.Get("/hello", [](const Request &req, Response &res) {
  16079. res.set_content(req.get_param_value("key"), "text/plain");
  16080. });
  16081. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16082. auto se = detail::scope_exit([&] {
  16083. svr.stop();
  16084. thread.join();
  16085. ASSERT_FALSE(svr.is_running());
  16086. });
  16087. svr.wait_until_ready();
  16088. {
  16089. Client cli(HOST, PORT);
  16090. cli.set_follow_location(true);
  16091. auto res = cli.Get("/");
  16092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16093. EXPECT_EQ(StatusCode::OK_200, res->status);
  16094. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16095. }
  16096. }
  16097. TEST(RedirectTest, RedirectWithPlusInPath) {
  16098. Server svr;
  16099. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16100. res.set_redirect("/a+b");
  16101. });
  16102. // Route pattern uses regex; escape + as \\+
  16103. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16104. res.set_content(req.path, "text/plain");
  16105. });
  16106. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16107. auto se = detail::scope_exit([&] {
  16108. svr.stop();
  16109. thread.join();
  16110. ASSERT_FALSE(svr.is_running());
  16111. });
  16112. svr.wait_until_ready();
  16113. {
  16114. Client cli(HOST, PORT);
  16115. cli.set_follow_location(true);
  16116. auto res = cli.Get("/");
  16117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16118. EXPECT_EQ(StatusCode::OK_200, res->status);
  16119. EXPECT_EQ("/a+b", res->body);
  16120. }
  16121. }
  16122. TEST(RedirectTest, ResolveRelativeLocation) {
  16123. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16124. const std::vector<std::pair<std::string, std::string>> cases = {
  16125. {"g", "/b/c/g"},
  16126. {"./g", "/b/c/g"},
  16127. {"g/", "/b/c/g/"},
  16128. {"?y", "/b/c/d;p?y"},
  16129. {"g?y", "/b/c/g?y"},
  16130. {"#s", "/b/c/d;p?q#s"},
  16131. {"g#s", "/b/c/g#s"},
  16132. {"g?y#s", "/b/c/g?y#s"},
  16133. {";x", "/b/c/;x"},
  16134. {"g;x", "/b/c/g;x"},
  16135. {".", "/b/c/"},
  16136. {"./", "/b/c/"},
  16137. {"..", "/b/"},
  16138. {"../", "/b/"},
  16139. {"../g", "/b/g"},
  16140. {"../..", "/"},
  16141. {"../../", "/"},
  16142. {"../../g", "/g"},
  16143. {"../../../g", "/g"},
  16144. {"g.", "/b/c/g."},
  16145. {".g", "/b/c/.g"},
  16146. {"g..", "/b/c/g.."},
  16147. {"..g", "/b/c/..g"},
  16148. {"./../g", "/b/g"},
  16149. {"./g/.", "/b/c/g/"},
  16150. {"g/./h", "/b/c/g/h"},
  16151. {"g/../h", "/b/c/h"},
  16152. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16153. {"g;x=1/../y", "/b/c/y"},
  16154. {"g?y/./x", "/b/c/g?y/./x"},
  16155. {"g#s/../x", "/b/c/g#s/../x"},
  16156. // Not relative-path references, so left for parse_url.
  16157. {"/g", "/g"},
  16158. {"//g", "//g"},
  16159. {"http://g/x", "http://g/x"},
  16160. {"g:h", "g:h"},
  16161. };
  16162. for (const auto &c : cases) {
  16163. EXPECT_EQ(c.second,
  16164. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16165. << c.first;
  16166. }
  16167. }
  16168. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16169. Server svr;
  16170. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16171. res.set_redirect(req.get_param_value("to"));
  16172. });
  16173. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16174. res.set_content(req.target, "text/plain");
  16175. });
  16176. svr.Get("/other", [](const Request &req, Response &res) {
  16177. res.set_content(req.target, "text/plain");
  16178. });
  16179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16180. auto se = detail::scope_exit([&] {
  16181. svr.stop();
  16182. thread.join();
  16183. ASSERT_FALSE(svr.is_running());
  16184. });
  16185. svr.wait_until_ready();
  16186. const std::vector<std::pair<std::string, std::string>> cases = {
  16187. {"next", "/dir/next"},
  16188. {"./next?x=1", "/dir/next?x=1"},
  16189. {"../other", "/other"},
  16190. };
  16191. for (const auto &c : cases) {
  16192. Client cli(HOST, PORT);
  16193. cli.set_follow_location(true);
  16194. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16195. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16196. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16197. EXPECT_EQ(c.second, res->body) << c.first;
  16198. }
  16199. }
  16200. #ifdef CPPHTTPLIB_SSL_ENABLED
  16201. TEST(RedirectTest, Issue2185_Online) {
  16202. SSLClient client("github.com");
  16203. client.set_follow_location(true);
  16204. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16205. "Coollab-Windows.zip");
  16206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16207. EXPECT_EQ(StatusCode::OK_200, res->status);
  16208. EXPECT_EQ(9920427U, res->body.size());
  16209. }
  16210. #endif
  16211. TEST(VulnerabilityTest, CRLFInjection) {
  16212. Server svr;
  16213. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16214. res.set_content("Hello 1", "text/plain");
  16215. });
  16216. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16217. res.set_content("Hello 2", "text/plain");
  16218. });
  16219. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16220. res.set_content("Hello 3", "text/plain");
  16221. });
  16222. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16223. res.set_content("Hello 4", "text/plain");
  16224. });
  16225. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16226. for (const auto &x : req.headers) {
  16227. auto key = x.first;
  16228. EXPECT_STRNE("evil", key.c_str());
  16229. }
  16230. });
  16231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16232. auto se = detail::scope_exit([&] {
  16233. svr.stop();
  16234. thread.join();
  16235. ASSERT_FALSE(svr.is_running());
  16236. });
  16237. svr.wait_until_ready();
  16238. {
  16239. Client cli(HOST, PORT);
  16240. cli.Post("/test1", "A=B",
  16241. "application/x-www-form-urlencoded\r\nevil: hello1");
  16242. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16243. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16244. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16245. }
  16246. }
  16247. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16248. auto server_thread = std::thread([] {
  16249. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16250. default_socket_options(srv);
  16251. sockaddr_in addr{};
  16252. addr.sin_family = AF_INET;
  16253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16254. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16255. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16256. ::listen(srv, 1);
  16257. sockaddr_in cli_addr{};
  16258. socklen_t cli_len = sizeof(cli_addr);
  16259. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16260. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16261. std::string buf_all;
  16262. char buf[2048];
  16263. ssize_t n;
  16264. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16265. buf_all.append(buf, static_cast<size_t>(n));
  16266. size_t pos;
  16267. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16268. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16269. auto e = request_block.find("\r\n");
  16270. if (e != std::string::npos) {
  16271. auto request_line = request_block.substr(0, e);
  16272. std::string msg =
  16273. "CRLF injection detected in request line: '" + request_line + "'";
  16274. EXPECT_FALSE(true) << msg;
  16275. }
  16276. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16277. ::send(cli,
  16278. #ifdef _WIN32
  16279. static_cast<const char *>(resp.c_str()),
  16280. static_cast<int>(resp.size()),
  16281. #else
  16282. resp.c_str(), resp.size(),
  16283. #endif
  16284. 0);
  16285. buf_all.erase(0, pos + 4);
  16286. }
  16287. }
  16288. detail::close_socket(cli);
  16289. detail::close_socket(srv);
  16290. });
  16291. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16292. auto cli = Client("127.0.0.1", PORT + 1);
  16293. auto headers = Headers{
  16294. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16295. {"Connection", "keep-alive"}};
  16296. auto res = cli.Get("/hi", headers);
  16297. EXPECT_FALSE(res);
  16298. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16299. server_thread.join();
  16300. }
  16301. // A request rejected before any byte reaches the socket must fail right away
  16302. // instead of waiting for a response the server will never send.
  16303. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16304. // The kernel completes the TCP handshake from the listen backlog, so the
  16305. // client connects, but nothing ever reads, responds or closes.
  16306. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16307. default_socket_options(srv);
  16308. sockaddr_in addr{};
  16309. addr.sin_family = AF_INET;
  16310. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16311. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16312. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16313. ASSERT_EQ(0, ::listen(srv, 8));
  16314. auto cli = Client("127.0.0.1", PORT + 1);
  16315. cli.set_read_timeout(10, 0);
  16316. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16317. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16318. std::chrono::steady_clock::now() - start)
  16319. .count();
  16320. };
  16321. {
  16322. Request req;
  16323. req.method = "GE T";
  16324. req.path = "/";
  16325. auto start = std::chrono::steady_clock::now();
  16326. auto res = cli.send(req);
  16327. EXPECT_FALSE(res);
  16328. EXPECT_EQ(Error::Write, res.error());
  16329. EXPECT_LT(elapsed_ms(start), 1000);
  16330. }
  16331. {
  16332. auto start = std::chrono::steady_clock::now();
  16333. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16334. EXPECT_FALSE(res);
  16335. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16336. EXPECT_LT(elapsed_ms(start), 1000);
  16337. }
  16338. EXPECT_FALSE(cli.is_socket_open());
  16339. detail::close_socket(srv);
  16340. }
  16341. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16342. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16343. default_socket_options(srv);
  16344. sockaddr_in addr{};
  16345. addr.sin_family = AF_INET;
  16346. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16347. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16348. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16349. ASSERT_EQ(0, ::listen(srv, 1));
  16350. std::string received;
  16351. auto server_thread = std::thread([&] {
  16352. auto sock = ::accept(srv, nullptr, nullptr);
  16353. if (sock == INVALID_SOCKET) { return; }
  16354. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16355. char buf[2048];
  16356. ssize_t n;
  16357. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16358. received.append(buf, static_cast<size_t>(n));
  16359. }
  16360. detail::close_socket(sock);
  16361. });
  16362. {
  16363. auto cli = Client("127.0.0.1", PORT + 1);
  16364. // "Z" sorts after the default headers, so writing straight to the socket
  16365. // would have sent the request line and those headers before the rejection.
  16366. auto handle =
  16367. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16368. EXPECT_FALSE(handle.is_valid());
  16369. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16370. }
  16371. server_thread.join();
  16372. detail::close_socket(srv);
  16373. EXPECT_TRUE(received.empty()) << received;
  16374. }
  16375. TEST(PathParamsTest, StaticMatch) {
  16376. const auto pattern = "/users/all";
  16377. detail::PathParamsMatcher matcher(pattern);
  16378. Request request;
  16379. request.path = "/users/all";
  16380. ASSERT_TRUE(matcher.match(request));
  16381. std::unordered_map<std::string, std::string> expected_params = {};
  16382. EXPECT_EQ(request.path_params, expected_params);
  16383. }
  16384. TEST(PathParamsTest, StaticMismatch) {
  16385. const auto pattern = "/users/all";
  16386. detail::PathParamsMatcher matcher(pattern);
  16387. Request request;
  16388. request.path = "/users/1";
  16389. ASSERT_FALSE(matcher.match(request));
  16390. }
  16391. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16392. const auto pattern = "/users/:id/subscriptions";
  16393. detail::PathParamsMatcher matcher(pattern);
  16394. Request request;
  16395. request.path = "/users/42/subscriptions";
  16396. ASSERT_TRUE(matcher.match(request));
  16397. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16398. EXPECT_EQ(request.path_params, expected_params);
  16399. }
  16400. TEST(PathParamsTest, SingleParamInTheEnd) {
  16401. const auto pattern = "/users/:id";
  16402. detail::PathParamsMatcher matcher(pattern);
  16403. Request request;
  16404. request.path = "/users/24";
  16405. ASSERT_TRUE(matcher.match(request));
  16406. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16407. EXPECT_EQ(request.path_params, expected_params);
  16408. }
  16409. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16410. const auto pattern = "/users/:id/";
  16411. detail::PathParamsMatcher matcher(pattern);
  16412. Request request;
  16413. request.path = "/users/42/";
  16414. ASSERT_TRUE(matcher.match(request));
  16415. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16416. EXPECT_EQ(request.path_params, expected_params);
  16417. }
  16418. TEST(PathParamsTest, EmptyParam) {
  16419. const auto pattern = "/users/:id/";
  16420. detail::PathParamsMatcher matcher(pattern);
  16421. Request request;
  16422. request.path = "/users//";
  16423. ASSERT_TRUE(matcher.match(request));
  16424. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16425. EXPECT_EQ(request.path_params, expected_params);
  16426. }
  16427. TEST(PathParamsTest, FragmentMismatch) {
  16428. const auto pattern = "/users/:id/";
  16429. detail::PathParamsMatcher matcher(pattern);
  16430. Request request;
  16431. request.path = "/admins/24/";
  16432. ASSERT_FALSE(matcher.match(request));
  16433. }
  16434. TEST(PathParamsTest, ExtraFragments) {
  16435. const auto pattern = "/users/:id";
  16436. detail::PathParamsMatcher matcher(pattern);
  16437. Request request;
  16438. request.path = "/users/42/subscriptions";
  16439. ASSERT_FALSE(matcher.match(request));
  16440. }
  16441. TEST(PathParamsTest, MissingTrailingParam) {
  16442. const auto pattern = "/users/:id";
  16443. detail::PathParamsMatcher matcher(pattern);
  16444. Request request;
  16445. request.path = "/users";
  16446. ASSERT_FALSE(matcher.match(request));
  16447. }
  16448. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16449. const auto pattern = "/users/:id/subscriptions";
  16450. detail::PathParamsMatcher matcher(pattern);
  16451. Request request;
  16452. request.path = "/users/subscriptions";
  16453. ASSERT_FALSE(matcher.match(request));
  16454. }
  16455. TEST(PathParamsTest, MultipleParams) {
  16456. const auto pattern = "/users/:userid/subscriptions/:subid";
  16457. detail::PathParamsMatcher matcher(pattern);
  16458. Request request;
  16459. request.path = "/users/42/subscriptions/2";
  16460. ASSERT_TRUE(matcher.match(request));
  16461. std::unordered_map<std::string, std::string> expected_params = {
  16462. {"userid", "42"}, {"subid", "2"}};
  16463. EXPECT_EQ(request.path_params, expected_params);
  16464. }
  16465. TEST(PathParamsTest, SequenceOfParams) {
  16466. const auto pattern = "/values/:x/:y/:z";
  16467. detail::PathParamsMatcher matcher(pattern);
  16468. Request request;
  16469. request.path = "/values/1/2/3";
  16470. ASSERT_TRUE(matcher.match(request));
  16471. std::unordered_map<std::string, std::string> expected_params = {
  16472. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16473. EXPECT_EQ(request.path_params, expected_params);
  16474. }
  16475. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16476. const auto pattern = "/prefix:suffix";
  16477. detail::PathParamsMatcher matcher(pattern);
  16478. Request request;
  16479. request.path = "/prefix:suffix";
  16480. ASSERT_TRUE(matcher.match(request));
  16481. const std::unordered_map<std::string, std::string> expected_params = {};
  16482. EXPECT_EQ(request.path_params, expected_params);
  16483. }
  16484. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16485. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16486. // calling thread's stack on a long enough path for a quantified pattern;
  16487. // RegexMatcher must refuse to run regex matching on paths beyond
  16488. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16489. detail::RegexMatcher matcher("/files/(.*)");
  16490. Request within_limit;
  16491. within_limit.path = "/files/" + std::string(10, 'A');
  16492. EXPECT_TRUE(matcher.match(within_limit));
  16493. Request over_limit;
  16494. over_limit.path =
  16495. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16496. EXPECT_FALSE(matcher.match(over_limit));
  16497. }
  16498. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16499. Server svr;
  16500. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16501. res.set_content("ok", "text/plain");
  16502. });
  16503. auto port = svr.bind_to_any_port(HOST);
  16504. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16505. auto se = detail::scope_exit([&] {
  16506. svr.stop();
  16507. thread.join();
  16508. ASSERT_FALSE(svr.is_running());
  16509. });
  16510. svr.wait_until_ready();
  16511. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16512. // request URI limit; this used to be able to crash the process.
  16513. std::string path =
  16514. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16515. std::string req = "GET " + path +
  16516. " HTTP/1.1\r\n"
  16517. "Host: " +
  16518. std::string(HOST) + ":" + std::to_string(port) +
  16519. "\r\n"
  16520. "Connection: close\r\n"
  16521. "\r\n";
  16522. std::string response;
  16523. ASSERT_TRUE(send_request(5, req, &response, port));
  16524. EXPECT_NE(std::string::npos, response.find("404"));
  16525. }
  16526. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16527. Server svr;
  16528. auto handler = [](const Request & /*req*/, Response &res) {
  16529. res.set_content("hit", "text/plain");
  16530. };
  16531. // No regex metacharacter, so this one is compared literally
  16532. svr.Get("/literal/route", handler);
  16533. // '.' is a regex metacharacter, so this one must keep regex semantics
  16534. svr.Get("/a.c", handler);
  16535. auto port = svr.bind_to_any_port(HOST);
  16536. std::thread t([&]() { svr.listen_after_bind(); });
  16537. auto se = detail::scope_exit([&] {
  16538. svr.stop();
  16539. t.join();
  16540. ASSERT_FALSE(svr.is_running());
  16541. });
  16542. svr.wait_until_ready();
  16543. Client cli(HOST, port);
  16544. struct {
  16545. const char *path;
  16546. int status;
  16547. } cases[] = {
  16548. {"/literal/route", StatusCode::OK_200},
  16549. {"/literal/routes", StatusCode::NotFound_404},
  16550. {"/literal/rout", StatusCode::NotFound_404},
  16551. {"/abc", StatusCode::OK_200},
  16552. {"/a.c", StatusCode::OK_200},
  16553. };
  16554. for (const auto &x : cases) {
  16555. auto res = cli.Get(x.path);
  16556. ASSERT_TRUE(res) << x.path;
  16557. EXPECT_EQ(x.status, res->status) << x.path;
  16558. }
  16559. }
  16560. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16561. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16562. // from exhausting the stack, so it must only constrain routes that actually
  16563. // run a regular expression. A literal route is matched by comparison and
  16564. // stays usable at any length.
  16565. Server svr;
  16566. const std::string pattern =
  16567. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16568. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16569. res.set_content("hit", "text/plain");
  16570. });
  16571. auto port = svr.bind_to_any_port(HOST);
  16572. std::thread t([&]() { svr.listen_after_bind(); });
  16573. auto se = detail::scope_exit([&] {
  16574. svr.stop();
  16575. t.join();
  16576. ASSERT_FALSE(svr.is_running());
  16577. });
  16578. svr.wait_until_ready();
  16579. Client cli(HOST, port);
  16580. auto res = cli.Get(pattern);
  16581. ASSERT_TRUE(res);
  16582. EXPECT_EQ(StatusCode::OK_200, res->status);
  16583. }
  16584. TEST(ParseUrlTest, VariousPatterns) {
  16585. {
  16586. detail::UrlComponents uc;
  16587. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16588. EXPECT_EQ("http", uc.scheme);
  16589. EXPECT_EQ("example.com", uc.host);
  16590. EXPECT_EQ("8080", uc.port);
  16591. EXPECT_EQ("/path", uc.path);
  16592. EXPECT_EQ("?q=1", uc.query);
  16593. }
  16594. {
  16595. detail::UrlComponents uc;
  16596. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16597. EXPECT_EQ("https", uc.scheme);
  16598. EXPECT_EQ("example.com", uc.host);
  16599. EXPECT_TRUE(uc.port.empty());
  16600. EXPECT_EQ("/path", uc.path);
  16601. }
  16602. {
  16603. detail::UrlComponents uc;
  16604. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16605. EXPECT_EQ("::1", uc.host);
  16606. EXPECT_EQ("8080", uc.port);
  16607. EXPECT_EQ("/path", uc.path);
  16608. }
  16609. {
  16610. detail::UrlComponents uc;
  16611. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16612. }
  16613. {
  16614. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16615. // the path while the connection still targets the bracketed host.
  16616. detail::UrlComponents uc;
  16617. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16618. }
  16619. {
  16620. detail::UrlComponents uc;
  16621. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16622. }
  16623. {
  16624. detail::UrlComponents uc;
  16625. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16626. EXPECT_EQ("::1", uc.host);
  16627. EXPECT_TRUE(uc.port.empty());
  16628. EXPECT_EQ("/path", uc.path);
  16629. }
  16630. {
  16631. detail::UrlComponents uc;
  16632. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16633. EXPECT_TRUE(uc.scheme.empty());
  16634. EXPECT_EQ("example.com", uc.host);
  16635. EXPECT_EQ("/path", uc.path);
  16636. EXPECT_EQ("?q=1", uc.query);
  16637. }
  16638. {
  16639. detail::UrlComponents uc;
  16640. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16641. EXPECT_TRUE(uc.host.empty());
  16642. EXPECT_EQ("/path", uc.path);
  16643. EXPECT_EQ("?q=1", uc.query);
  16644. }
  16645. {
  16646. detail::UrlComponents uc;
  16647. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16648. EXPECT_EQ("example.com", uc.host);
  16649. EXPECT_EQ("8080", uc.port);
  16650. }
  16651. {
  16652. // Unix socket path — must not be parsed as host
  16653. detail::UrlComponents uc;
  16654. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16655. EXPECT_TRUE(uc.host.empty());
  16656. }
  16657. {
  16658. detail::UrlComponents uc;
  16659. ASSERT_TRUE(detail::parse_url("", uc));
  16660. EXPECT_TRUE(uc.host.empty());
  16661. EXPECT_TRUE(uc.path.empty());
  16662. }
  16663. {
  16664. detail::UrlComponents uc;
  16665. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16666. }
  16667. {
  16668. detail::UrlComponents uc;
  16669. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16670. }
  16671. {
  16672. // Accepted by parse_url; callers restrict to http/https
  16673. detail::UrlComponents uc;
  16674. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16675. EXPECT_EQ("ftp", uc.scheme);
  16676. }
  16677. {
  16678. detail::UrlComponents uc;
  16679. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16680. }
  16681. {
  16682. detail::UrlComponents uc;
  16683. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16684. }
  16685. }
  16686. TEST(ParseUrlTest, FragmentHandling) {
  16687. {
  16688. detail::UrlComponents uc;
  16689. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16690. EXPECT_EQ("/path", uc.path);
  16691. EXPECT_TRUE(uc.query.empty());
  16692. }
  16693. {
  16694. detail::UrlComponents uc;
  16695. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16696. EXPECT_TRUE(uc.path.empty());
  16697. EXPECT_TRUE(uc.query.empty());
  16698. }
  16699. }
  16700. TEST(ParseUrlTest, UserinfoHandling) {
  16701. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16702. // parsers would see evil.com as the host.
  16703. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16704. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16705. for (auto url : urls) {
  16706. detail::UrlComponents uc;
  16707. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16708. }
  16709. }
  16710. TEST(ParseUrlTest, IPv6EdgeCases) {
  16711. {
  16712. detail::UrlComponents uc;
  16713. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16714. EXPECT_TRUE(uc.scheme.empty());
  16715. EXPECT_EQ("::1", uc.host);
  16716. EXPECT_EQ("8080", uc.port);
  16717. }
  16718. {
  16719. // Zone ID '%25' is not in [a-fA-F0-9:]
  16720. detail::UrlComponents uc;
  16721. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16722. }
  16723. }
  16724. TEST(ParseUrlTest, SchemeEdgeCases) {
  16725. {
  16726. detail::UrlComponents uc;
  16727. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16728. }
  16729. {
  16730. detail::UrlComponents uc;
  16731. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16732. }
  16733. {
  16734. detail::UrlComponents uc;
  16735. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16736. }
  16737. }
  16738. TEST(ParseUrlTest, PortEdgeCases) {
  16739. {
  16740. detail::UrlComponents uc;
  16741. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16742. EXPECT_TRUE(uc.port.empty());
  16743. EXPECT_EQ("/path", uc.path);
  16744. }
  16745. {
  16746. // parse_url accepts any port string; validation is done by parse_port
  16747. detail::UrlComponents uc;
  16748. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16749. EXPECT_EQ("abc", uc.port);
  16750. }
  16751. }
  16752. TEST(ParseUrlTest, WebSocketPatterns) {
  16753. {
  16754. detail::UrlComponents uc;
  16755. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16756. EXPECT_EQ("ws", uc.scheme);
  16757. EXPECT_EQ("echo.example.com", uc.host);
  16758. EXPECT_EQ("8080", uc.port);
  16759. EXPECT_EQ("/ws", uc.path);
  16760. }
  16761. {
  16762. detail::UrlComponents uc;
  16763. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16764. EXPECT_EQ("wss", uc.scheme);
  16765. EXPECT_EQ("echo.example.com", uc.host);
  16766. EXPECT_TRUE(uc.port.empty());
  16767. EXPECT_EQ("/ws", uc.path);
  16768. }
  16769. }
  16770. TEST(ParseUrlTest, QueryOnly) {
  16771. detail::UrlComponents uc;
  16772. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16773. EXPECT_TRUE(uc.host.empty());
  16774. EXPECT_TRUE(uc.path.empty());
  16775. EXPECT_EQ("?q=1&r=2", uc.query);
  16776. }
  16777. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16778. detail::UrlComponents uc;
  16779. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16780. EXPECT_TRUE(uc.scheme.empty());
  16781. EXPECT_EQ("example.com", uc.host);
  16782. EXPECT_EQ("443", uc.port);
  16783. EXPECT_EQ("/path", uc.path);
  16784. }
  16785. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16786. // If ipv6 regex working, regex match codepath is taken.
  16787. // else port will default to 80 in Client impl
  16788. int clientImplMagicPort = 80;
  16789. int port = 4321;
  16790. // above ports must be different to avoid false negative
  16791. EXPECT_NE(clientImplMagicPort, port);
  16792. std::string ipV6TestURL = "http://[ff06::c3]";
  16793. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16794. CLIENT_PRIVATE_KEY_FILE);
  16795. EXPECT_EQ(cli.port(), port);
  16796. }
  16797. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16798. auto file_path = "./www/dir/index.html";
  16799. auto dir_path = "./www/dir";
  16800. detail::FileStat stat_file(file_path);
  16801. EXPECT_TRUE(stat_file.is_file());
  16802. EXPECT_FALSE(stat_file.is_dir());
  16803. detail::FileStat stat_dir(dir_path);
  16804. EXPECT_FALSE(stat_dir.is_file());
  16805. EXPECT_TRUE(stat_dir.is_dir());
  16806. }
  16807. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16808. // IPv4 with default HTTP port (80)
  16809. EXPECT_EQ("example.com",
  16810. detail::make_host_and_port_string("example.com", 80, false));
  16811. // IPv4 with default HTTPS port (443)
  16812. EXPECT_EQ("example.com",
  16813. detail::make_host_and_port_string("example.com", 443, true));
  16814. // IPv4 with non-default HTTP port
  16815. EXPECT_EQ("example.com:8080",
  16816. detail::make_host_and_port_string("example.com", 8080, false));
  16817. // IPv4 with non-default HTTPS port
  16818. EXPECT_EQ("example.com:8443",
  16819. detail::make_host_and_port_string("example.com", 8443, true));
  16820. // IPv6 with default HTTP port (80)
  16821. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16822. // IPv6 with default HTTPS port (443)
  16823. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16824. // IPv6 with non-default HTTP port
  16825. EXPECT_EQ("[::1]:8080",
  16826. detail::make_host_and_port_string("::1", 8080, false));
  16827. // IPv6 with non-default HTTPS port
  16828. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16829. // IPv6 full address with default port
  16830. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16831. detail::make_host_and_port_string(
  16832. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16833. // IPv6 full address with non-default port
  16834. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16835. detail::make_host_and_port_string(
  16836. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16837. // IPv6 localhost with non-default port
  16838. EXPECT_EQ("[::1]:3000",
  16839. detail::make_host_and_port_string("::1", 3000, false));
  16840. // IPv6 with zone ID (link-local address) with default port
  16841. EXPECT_EQ("[fe80::1%eth0]",
  16842. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16843. // IPv6 with zone ID (link-local address) with non-default port
  16844. EXPECT_EQ("[fe80::1%eth0]:8080",
  16845. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16846. // Edge case: Port 443 with is_ssl=false (should add port)
  16847. EXPECT_EQ("example.com:443",
  16848. detail::make_host_and_port_string("example.com", 443, false));
  16849. // Edge case: Port 80 with is_ssl=true (should add port)
  16850. EXPECT_EQ("example.com:80",
  16851. detail::make_host_and_port_string("example.com", 80, true));
  16852. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16853. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16854. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16855. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16856. // Security fix: Already bracketed IPv6 should not get double brackets
  16857. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16858. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16859. EXPECT_EQ("[::1]:8080",
  16860. detail::make_host_and_port_string("[::1]", 8080, false));
  16861. EXPECT_EQ("[2001:db8::1]:8080",
  16862. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16863. EXPECT_EQ("[fe80::1%eth0]",
  16864. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16865. EXPECT_EQ("[fe80::1%eth0]:8080",
  16866. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16867. // Edge case: Empty host (should return as-is)
  16868. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16869. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16870. // This is a known limitation but shouldn't crash
  16871. EXPECT_EQ("[host:name]",
  16872. detail::make_host_and_port_string("host:name", 80, false));
  16873. // Port number edge cases (no validation, but should not crash)
  16874. EXPECT_EQ("example.com:0",
  16875. detail::make_host_and_port_string("example.com", 0, false));
  16876. EXPECT_EQ("example.com:-1",
  16877. detail::make_host_and_port_string("example.com", -1, false));
  16878. EXPECT_EQ("example.com:65535",
  16879. detail::make_host_and_port_string("example.com", 65535, false));
  16880. EXPECT_EQ("example.com:65536",
  16881. detail::make_host_and_port_string("example.com", 65536, false));
  16882. }
  16883. #ifdef CPPHTTPLIB_SSL_ENABLED
  16884. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16885. httplib::SSLClient cli("roblox.com", 443);
  16886. cli.set_follow_location(true);
  16887. auto res = cli.Get("/");
  16888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16889. EXPECT_EQ(StatusCode::OK_200, res->status);
  16890. }
  16891. #endif
  16892. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16893. Server svr;
  16894. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16895. EXPECT_EQ(res.status, 400);
  16896. });
  16897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16898. auto se = detail::scope_exit([&] {
  16899. svr.stop();
  16900. thread.join();
  16901. ASSERT_FALSE(svr.is_running());
  16902. });
  16903. svr.wait_until_ready();
  16904. Client cli(HOST, PORT);
  16905. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16906. }
  16907. TEST(InvalidHeaderCharsTest, is_field_name) {
  16908. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16909. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16910. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16911. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16912. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16913. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16914. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16915. EXPECT_FALSE(detail::fields::is_field_name(""));
  16916. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16917. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16918. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16919. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16920. }
  16921. TEST(InvalidHeaderCharsTest, is_field_value) {
  16922. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16923. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16924. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16925. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16926. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16927. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16928. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16929. EXPECT_TRUE(detail::fields::is_field_value(""));
  16930. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16931. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16932. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16933. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16934. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16935. }
  16936. TEST(InvalidHeaderCharsTest, OnServer) {
  16937. Server svr;
  16938. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16939. std::string header = "Not Set";
  16940. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16941. res.set_header(header, "value");
  16942. res.set_content("Page Content Page Content", "text/plain");
  16943. });
  16944. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16945. std::string header = "Not Set";
  16946. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16947. res.set_header("X-Test", header);
  16948. res.set_content("Page Content Page Content", "text/plain");
  16949. });
  16950. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16951. auto se = detail::scope_exit([&] {
  16952. svr.stop();
  16953. thread.join();
  16954. ASSERT_FALSE(svr.is_running());
  16955. });
  16956. svr.wait_until_ready();
  16957. Client cli(HOST, PORT);
  16958. {
  16959. auto res = cli.Get(
  16960. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16962. EXPECT_EQ("Page Content Page Content", res->body);
  16963. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16964. }
  16965. {
  16966. auto res = cli.Get(
  16967. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16969. EXPECT_EQ("Page Content Page Content", res->body);
  16970. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16971. }
  16972. }
  16973. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16974. auto handled = false;
  16975. Server svr;
  16976. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16977. thread t = thread([&] { svr.listen(HOST, PORT); });
  16978. auto se = detail::scope_exit([&] {
  16979. svr.stop();
  16980. t.join();
  16981. ASSERT_FALSE(svr.is_running());
  16982. ASSERT_FALSE(handled);
  16983. });
  16984. svr.wait_until_ready();
  16985. auto req = "POST /test HTTP/1.1\r\n"
  16986. "Content-Length: x\r\n"
  16987. "\r\n";
  16988. std::string response;
  16989. ASSERT_TRUE(send_request(1, req, &response));
  16990. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16991. response.substr(0, response.find("\r\n")));
  16992. }
  16993. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16994. // case-insensitive, and a server that receives a 100-continue expectation in
  16995. // an HTTP/1.0 request MUST ignore it.
  16996. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16997. std::string response;
  16998. ASSERT_TRUE(send_request(1, req, &response, port));
  16999. *got_100 = response.find("100 Continue") != std::string::npos;
  17000. }
  17001. class ExpectTokenTest : public ::testing::Test {
  17002. protected:
  17003. void SetUp() override {
  17004. svr_.Post("/p", [](const Request &, Response &res) {
  17005. res.set_content("ok", "text/plain");
  17006. });
  17007. port_ = svr_.bind_to_any_port(HOST);
  17008. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17009. svr_.wait_until_ready();
  17010. }
  17011. void TearDown() override {
  17012. svr_.stop();
  17013. if (thread_.joinable()) { thread_.join(); }
  17014. }
  17015. std::string request(const char *version, const char *expect_value) const {
  17016. return std::string("POST /p ") + version +
  17017. "\r\n"
  17018. "Host: localhost\r\n"
  17019. "Content-Length: 2\r\n"
  17020. "Connection: close\r\n"
  17021. "Expect: " +
  17022. expect_value +
  17023. "\r\n"
  17024. "\r\n"
  17025. "hi";
  17026. }
  17027. Server svr_;
  17028. int port_ = 0;
  17029. thread thread_;
  17030. };
  17031. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17032. bool got_100 = false;
  17033. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17034. EXPECT_TRUE(got_100);
  17035. }
  17036. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17037. bool got_100 = true;
  17038. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17039. EXPECT_FALSE(got_100);
  17040. }
  17041. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17042. bool got_100 = false;
  17043. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17044. EXPECT_TRUE(got_100);
  17045. }
  17046. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17047. bool got_100 = false;
  17048. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17049. EXPECT_TRUE(got_100);
  17050. }
  17051. // `100 Continue` is sent only when the server starts reading the body, so a
  17052. // request rejected before that never invites the client to send it. The
  17053. // requests below carry the expectation but withhold the body, as a client
  17054. // waiting for `100 Continue` would.
  17055. // A POST that expects `100 Continue` and withholds its two-byte body.
  17056. static std::string expect_headers_only(const std::string &path) {
  17057. return "POST " + path +
  17058. " HTTP/1.1\r\n"
  17059. "Host: localhost\r\n"
  17060. "Content-Length: 2\r\n"
  17061. "Expect: 100-continue\r\n"
  17062. "\r\n";
  17063. }
  17064. class ExpectLazyContinueTest : public ::testing::Test {
  17065. protected:
  17066. void SetUp() override {
  17067. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17068. if (req.path == "/pre-routing") {
  17069. res.status = StatusCode::Unauthorized_401;
  17070. return Server::HandlerResponse::Handled;
  17071. }
  17072. return Server::HandlerResponse::Unhandled;
  17073. });
  17074. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17075. if (req.matched_route == "/pre-request") {
  17076. res.status = StatusCode::Forbidden_403;
  17077. return Server::HandlerResponse::Handled;
  17078. }
  17079. return Server::HandlerResponse::Unhandled;
  17080. });
  17081. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17082. res.set_content("ok", "text/plain");
  17083. });
  17084. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17085. res.set_content("ok", "text/plain");
  17086. });
  17087. svr_.Post("/reader-used", [](const Request &, Response &res,
  17088. const ContentReader &content_reader) {
  17089. std::string body;
  17090. content_reader([&](const char *data, size_t len) {
  17091. body.append(data, len);
  17092. return true;
  17093. });
  17094. res.set_content(body, "text/plain");
  17095. });
  17096. svr_.Post("/reader-unused",
  17097. [](const Request &, Response &res, const ContentReader &) {
  17098. res.set_content("ignored", "text/plain");
  17099. });
  17100. port_ = svr_.bind_to_any_port(HOST);
  17101. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17102. svr_.wait_until_ready();
  17103. }
  17104. void TearDown() override {
  17105. svr_.stop();
  17106. if (thread_.joinable()) { thread_.join(); }
  17107. }
  17108. // Sends `req` and reads until the server closes the connection. Returns
  17109. // false if the read had to wait for the client-side timeout instead.
  17110. bool send_until_closed(const std::string &req, std::string *resp) const {
  17111. auto start = std::chrono::steady_clock::now();
  17112. if (!send_request(3, req, resp, port_)) { return false; }
  17113. auto elapsed = std::chrono::steady_clock::now() - start;
  17114. return elapsed < std::chrono::seconds(2);
  17115. }
  17116. // The final response comes without `100 Continue`, and the server closes
  17117. // the connection since the body may or may not follow.
  17118. void expect_final_without_interim(const std::string &path,
  17119. const char *status_line) const {
  17120. std::string resp;
  17121. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17122. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17123. EXPECT_EQ(0u, resp.find(status_line));
  17124. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17125. }
  17126. Server svr_;
  17127. int port_ = 0;
  17128. thread thread_;
  17129. };
  17130. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17131. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17132. }
  17133. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17134. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17135. }
  17136. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17137. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17138. }
  17139. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17140. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17141. }
  17142. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17143. // The body follows once `100 Continue` has had time to arrive.
  17144. auto req = expect_headers_only("/reader-used");
  17145. req.insert(req.size() - 2, "Connection: close\r\n");
  17146. std::string resp;
  17147. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17148. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17149. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17150. EXPECT_NE(std::string::npos, resp.find("hi"));
  17151. }
  17152. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17153. // Large enough for the client to add `Expect: 100-continue` itself.
  17154. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17155. std::atomic<bool> body_sent{false};
  17156. Client cli(HOST, port_);
  17157. auto res = cli.Post(
  17158. "/pre-request", length,
  17159. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17160. body_sent = true;
  17161. std::string chunk(len, 'x');
  17162. sink.write(chunk.data(), chunk.size());
  17163. return true;
  17164. },
  17165. "application/octet-stream");
  17166. ASSERT_TRUE(res);
  17167. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17168. EXPECT_FALSE(body_sent);
  17169. }
  17170. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17171. Server svr;
  17172. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17173. return StatusCode::ExpectationFailed_417;
  17174. });
  17175. svr.Post("/p", [](const Request &, Response &res) {
  17176. res.set_content("ok", "text/plain");
  17177. });
  17178. auto port = svr.bind_to_any_port(HOST);
  17179. thread t = thread([&] { svr.listen_after_bind(); });
  17180. auto se = detail::scope_exit([&] {
  17181. svr.stop();
  17182. t.join();
  17183. });
  17184. svr.wait_until_ready();
  17185. std::string resp;
  17186. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17187. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17188. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17189. // Exactly one response: the route handler must not run after the 417.
  17190. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17191. }
  17192. #ifndef _WIN32
  17193. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17194. static constexpr char reject[] = "Unauthorized";
  17195. static constexpr char accept[] = "Upload accepted";
  17196. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17197. Server svr;
  17198. svr.set_expect_100_continue_handler(
  17199. [](const Request & /*req*/, Response &res) {
  17200. res.status = StatusCode::Unauthorized_401;
  17201. res.set_content(reject, "text/plain");
  17202. return res.status;
  17203. });
  17204. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17205. res.set_content(accept, "text/plain");
  17206. });
  17207. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17208. auto se = detail::scope_exit([&] {
  17209. svr.stop();
  17210. thread.join();
  17211. ASSERT_FALSE(svr.is_running());
  17212. });
  17213. svr.wait_until_ready();
  17214. {
  17215. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17216. curl_easy_init(), &curl_easy_cleanup};
  17217. ASSERT_NE(curl, nullptr);
  17218. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17219. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17220. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17221. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17222. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17223. &curl_slist_free_all};
  17224. ASSERT_NE(list, nullptr);
  17225. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17226. struct read_data {
  17227. size_t read_size;
  17228. size_t total_size;
  17229. } data = {0, total_size};
  17230. using read_callback_t =
  17231. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17232. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17233. void *userdata) -> size_t {
  17234. read_data *d = (read_data *)userdata;
  17235. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17236. std::fill_n(ptr, size * nmemb, 'A');
  17237. d->read_size += size * nmemb;
  17238. return size * nmemb;
  17239. };
  17240. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17241. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17242. std::vector<char> buffer;
  17243. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17244. using write_callback_t =
  17245. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17246. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17247. void *userdata) -> size_t {
  17248. std::vector<char> *buf = (std::vector<char> *)userdata;
  17249. buf->reserve(buf->size() + size * nmemb + 1);
  17250. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17251. return size * nmemb;
  17252. };
  17253. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17254. {
  17255. const auto res = curl_easy_perform(curl.get());
  17256. ASSERT_EQ(res, CURLE_OK);
  17257. }
  17258. {
  17259. auto response_code = long{};
  17260. const auto res =
  17261. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17262. ASSERT_EQ(res, CURLE_OK);
  17263. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17264. }
  17265. {
  17266. auto dl = curl_off_t{};
  17267. const auto res =
  17268. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17269. ASSERT_EQ(res, CURLE_OK);
  17270. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17271. }
  17272. {
  17273. buffer.push_back('\0');
  17274. ASSERT_STRCASEEQ(buffer.data(), reject);
  17275. }
  17276. }
  17277. }
  17278. #endif
  17279. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17280. // Regression test for #2458.
  17281. //
  17282. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17283. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17284. // ticket can make the client socket spuriously readable during the
  17285. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17286. // the client withholds the body and then blocks reading a response that never
  17287. // comes, failing with `Failed to read connection`.
  17288. //
  17289. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17290. // within the timeout. This raw OpenSSL server deliberately never sends
  17291. // `100 Continue`; the client must still deliver the body and receive 200.
  17292. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17293. signal(SIGPIPE, SIG_IGN);
  17294. const auto port = PORT + 4;
  17295. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17296. ASSERT_NE(srv, INVALID_SOCKET);
  17297. int opt = 1;
  17298. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17299. sockaddr_in addr{};
  17300. addr.sin_family = AF_INET;
  17301. addr.sin_port = htons(static_cast<uint16_t>(port));
  17302. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17303. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17304. ASSERT_EQ(0, ::listen(srv, 1));
  17305. std::atomic<size_t> server_body_bytes{0};
  17306. auto server_thread = std::thread([&] {
  17307. sockaddr_in cli_addr{};
  17308. socklen_t cli_len = sizeof(cli_addr);
  17309. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17310. if (cli == INVALID_SOCKET) { return; }
  17311. // Bound the lifetime of the server side so a buggy client (which never
  17312. // sends the body) cannot make this thread block forever on join.
  17313. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17314. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17315. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17316. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17317. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17318. SSL *ssl = SSL_new(ctx);
  17319. SSL_set_fd(ssl, static_cast<int>(cli));
  17320. if (SSL_accept(ssl) > 0) {
  17321. // Read the request headers. Reading here also flushes the TLS 1.3
  17322. // session tickets to the client. Deliberately do NOT send
  17323. // `100 Continue`.
  17324. std::string buf;
  17325. char tmp[1024];
  17326. while (buf.find("\r\n\r\n") == std::string::npos) {
  17327. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17328. if (n <= 0) { break; }
  17329. buf.append(tmp, static_cast<size_t>(n));
  17330. }
  17331. // A correct client sends the body now; count what arrives.
  17332. auto pos = buf.find("\r\n\r\n");
  17333. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17334. while (body < 4096) {
  17335. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17336. if (n <= 0) { break; }
  17337. body += static_cast<size_t>(n);
  17338. }
  17339. server_body_bytes = body;
  17340. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17341. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17342. SSL_shutdown(ssl);
  17343. }
  17344. SSL_free(ssl);
  17345. detail::close_socket(cli);
  17346. SSL_CTX_free(ctx);
  17347. });
  17348. auto se = detail::scope_exit([&] {
  17349. server_thread.join();
  17350. detail::close_socket(srv);
  17351. });
  17352. SSLClient cli("127.0.0.1", port);
  17353. cli.enable_server_certificate_verification(false);
  17354. cli.set_connection_timeout(5, 0);
  17355. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17356. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17357. std::string body(4096, 'A');
  17358. auto res = cli.Put("/api/test", body, "application/json");
  17359. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17360. EXPECT_EQ(StatusCode::OK_200, res->status);
  17361. EXPECT_EQ(body.size(), server_body_bytes.load());
  17362. }
  17363. #endif
  17364. template <typename S, typename C>
  17365. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17366. svr.Get("/stream", [&](const Request &, Response &res) {
  17367. auto data = new std::string("01234567890123456789");
  17368. res.set_content_provider(
  17369. data->size(), "text/plain",
  17370. [&, data](size_t offset, size_t length, DataSink &sink) {
  17371. const size_t DATA_CHUNK_SIZE = 4;
  17372. const auto &d = *data;
  17373. std::this_thread::sleep_for(std::chrono::seconds(1));
  17374. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17375. return true;
  17376. },
  17377. [data](bool success) {
  17378. EXPECT_FALSE(success);
  17379. delete data;
  17380. });
  17381. });
  17382. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17383. auto i = new size_t(0);
  17384. res.set_content_provider(
  17385. "text/plain",
  17386. [i](size_t, DataSink &sink) {
  17387. if (*i < 5) {
  17388. std::this_thread::sleep_for(std::chrono::seconds(1));
  17389. sink.write("abcd", 4);
  17390. (*i)++;
  17391. } else {
  17392. sink.done();
  17393. }
  17394. return true;
  17395. },
  17396. [i](bool success) {
  17397. EXPECT_FALSE(success);
  17398. delete i;
  17399. });
  17400. });
  17401. svr.Get("/chunked", [&](const Request &, Response &res) {
  17402. auto i = new size_t(0);
  17403. res.set_chunked_content_provider(
  17404. "text/plain",
  17405. [i](size_t, DataSink &sink) {
  17406. if (*i < 5) {
  17407. std::this_thread::sleep_for(std::chrono::seconds(1));
  17408. sink.os << "abcd";
  17409. (*i)++;
  17410. } else {
  17411. sink.done();
  17412. }
  17413. return true;
  17414. },
  17415. [i](bool success) {
  17416. EXPECT_FALSE(success);
  17417. delete i;
  17418. });
  17419. });
  17420. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17421. auto se = detail::scope_exit([&] {
  17422. svr.stop();
  17423. listen_thread.join();
  17424. ASSERT_FALSE(svr.is_running());
  17425. });
  17426. svr.wait_until_ready();
  17427. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17428. {
  17429. auto start = std::chrono::steady_clock::now();
  17430. auto res = cli.Get("/stream");
  17431. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17432. std::chrono::steady_clock::now() - start)
  17433. .count();
  17434. ASSERT_FALSE(res);
  17435. EXPECT_EQ(Error::Read, res.error());
  17436. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17437. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17438. }
  17439. {
  17440. auto start = std::chrono::steady_clock::now();
  17441. auto res = cli.Get("/stream_without_length");
  17442. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17443. std::chrono::steady_clock::now() - start)
  17444. .count();
  17445. ASSERT_FALSE(res);
  17446. EXPECT_EQ(Error::Read, res.error());
  17447. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17448. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17449. }
  17450. {
  17451. auto start = std::chrono::steady_clock::now();
  17452. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17453. EXPECT_EQ("abcd", string(data, data_length));
  17454. return true;
  17455. });
  17456. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17457. std::chrono::steady_clock::now() - start)
  17458. .count();
  17459. ASSERT_FALSE(res);
  17460. EXPECT_EQ(Error::Read, res.error());
  17461. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17462. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17463. }
  17464. }
  17465. TEST(MaxTimeoutTest, ContentStream) {
  17466. time_t timeout = 2000;
  17467. time_t threshold = 200;
  17468. Server svr;
  17469. Client cli("localhost", PORT);
  17470. max_timeout_test(svr, cli, timeout, threshold);
  17471. }
  17472. #ifdef CPPHTTPLIB_SSL_ENABLED
  17473. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17474. time_t timeout = 2000;
  17475. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17477. SSLClient cli("localhost", PORT);
  17478. cli.enable_server_certificate_verification(false);
  17479. max_timeout_test(svr, cli, timeout, threshold);
  17480. }
  17481. #endif
  17482. class EventDispatcher {
  17483. public:
  17484. EventDispatcher() {}
  17485. bool wait_event(DataSink *sink) {
  17486. unique_lock<mutex> lk(m_);
  17487. int id = id_;
  17488. // Wait with timeout to prevent hanging if client disconnects
  17489. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17490. [&] { return cid_ == id; })) {
  17491. return false; // Timeout occurred
  17492. }
  17493. sink->write(message_.data(), message_.size());
  17494. return true;
  17495. }
  17496. void send_event(const string &message) {
  17497. lock_guard<mutex> lk(m_);
  17498. cid_ = id_++;
  17499. message_ = message;
  17500. cv_.notify_all();
  17501. }
  17502. private:
  17503. mutex m_;
  17504. condition_variable cv_;
  17505. atomic_int id_{0};
  17506. atomic_int cid_{-1};
  17507. string message_;
  17508. };
  17509. TEST(ClientInThreadTest, Issue2068) {
  17510. EventDispatcher ed;
  17511. Server svr;
  17512. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17513. res.set_chunked_content_provider("text/event-stream",
  17514. [&](size_t /*offset*/, DataSink &sink) {
  17515. return ed.wait_event(&sink);
  17516. });
  17517. });
  17518. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17519. svr.wait_until_ready();
  17520. thread event_thread([&] {
  17521. int id = 0;
  17522. while (svr.is_running()) {
  17523. this_thread::sleep_for(chrono::milliseconds(500));
  17524. std::stringstream ss;
  17525. ss << "data: " << id << "\n\n";
  17526. ed.send_event(ss.str());
  17527. id++;
  17528. }
  17529. });
  17530. auto se = detail::scope_exit([&] {
  17531. svr.stop();
  17532. listen_thread.join();
  17533. event_thread.join();
  17534. ASSERT_FALSE(svr.is_running());
  17535. });
  17536. {
  17537. auto client = detail::make_unique<Client>(HOST, PORT);
  17538. client->set_read_timeout(std::chrono::minutes(10));
  17539. std::atomic<bool> stop{false};
  17540. std::thread t([&] {
  17541. client->Get("/event1",
  17542. [&](const char *, size_t) -> bool { return !stop; });
  17543. });
  17544. std::this_thread::sleep_for(std::chrono::seconds(2));
  17545. stop = true;
  17546. client->stop();
  17547. t.join();
  17548. // Reset client after thread has finished
  17549. client.reset();
  17550. }
  17551. }
  17552. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17553. auto handled = false;
  17554. Server svr;
  17555. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17556. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17557. auto se = detail::scope_exit([&] {
  17558. svr.stop();
  17559. t.join();
  17560. ASSERT_FALSE(svr.is_running());
  17561. ASSERT_FALSE(handled);
  17562. });
  17563. svr.wait_until_ready();
  17564. // Two Content-Length headers with different values — must be rejected
  17565. auto req = "POST /test HTTP/1.1\r\n"
  17566. "Content-Length: 5\r\n"
  17567. "Content-Length: 10\r\n"
  17568. "\r\n"
  17569. "hello";
  17570. std::string response;
  17571. ASSERT_TRUE(send_request(1, req, &response));
  17572. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17573. response.substr(0, response.find("\r\n")));
  17574. }
  17575. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17576. auto handled = false;
  17577. Server svr;
  17578. svr.Post("/test", [&](const Request &, Response &res) {
  17579. handled = true;
  17580. res.set_content("ok", "text/plain");
  17581. });
  17582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17583. auto se = detail::scope_exit([&] {
  17584. svr.stop();
  17585. t.join();
  17586. ASSERT_FALSE(svr.is_running());
  17587. ASSERT_TRUE(handled);
  17588. });
  17589. svr.wait_until_ready();
  17590. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17591. auto req = "POST /test HTTP/1.1\r\n"
  17592. "Host: localhost\r\n"
  17593. "Content-Length: 5\r\n"
  17594. "Content-Length: 5\r\n"
  17595. "\r\n"
  17596. "hello";
  17597. std::string response;
  17598. ASSERT_TRUE(send_request(1, req, &response));
  17599. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17600. }
  17601. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17602. Server svr;
  17603. svr.Get("/test", [](const Request &, Response &res) {
  17604. res.set_content("ok", "text/plain");
  17605. });
  17606. auto port = svr.bind_to_any_port(HOST);
  17607. thread t = thread([&] { svr.listen_after_bind(); });
  17608. auto se = detail::scope_exit([&] {
  17609. svr.stop();
  17610. t.join();
  17611. ASSERT_FALSE(svr.is_running());
  17612. });
  17613. svr.wait_until_ready();
  17614. auto status_line = [&](const std::string &host_lines) {
  17615. std::string res;
  17616. send_request(
  17617. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17618. &res, port);
  17619. return res.substr(0, res.find("\r\n"));
  17620. };
  17621. const char *accepted[] = {
  17622. "Host: localhost\r\n",
  17623. "Host: a.example:8080\r\n",
  17624. "Host: my_service\r\n",
  17625. "Host: [::1]:8080\r\n",
  17626. "Host: [fe80::1%25eth0]\r\n",
  17627. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17628. };
  17629. for (auto host_lines : accepted) {
  17630. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17631. }
  17632. const char *rejected[] = {
  17633. "Host: a.example\r\nHost: b.example\r\n",
  17634. "Host: a.example\r\nHost: a.example\r\n",
  17635. "Host: a@b.example\r\n",
  17636. "Host: a.example/b\r\n",
  17637. "Host: a.example\\b\r\n",
  17638. "Host: a.example?b\r\n",
  17639. "Host: a.example#b\r\n",
  17640. "Host: a.example b.example\r\n",
  17641. };
  17642. for (auto host_lines : rejected) {
  17643. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17644. << host_lines;
  17645. }
  17646. }
  17647. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17648. Server svr;
  17649. svr.Get("/", [](const Request &req, Response &res) {
  17650. EXPECT_EQ(2U, req.trailers.size());
  17651. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17652. // Denied
  17653. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17654. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17655. // Accepted
  17656. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17657. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17658. EXPECT_TRUE(req.has_trailer("X-World"));
  17659. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17660. res.set_content("ok", "text/plain");
  17661. });
  17662. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17663. auto se = detail::scope_exit([&] {
  17664. svr.stop();
  17665. t.join();
  17666. ASSERT_FALSE(svr.is_running());
  17667. });
  17668. svr.wait_until_ready();
  17669. const std::string req = "GET / HTTP/1.1\r\n"
  17670. "Transfer-Encoding: chunked\r\n"
  17671. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17672. "\r\n"
  17673. "0\r\n"
  17674. "Content-Length: 10\r\n"
  17675. "Host: internal.local\r\n"
  17676. "Content-Type: malicious/content\r\n"
  17677. "Cookie: any\r\n"
  17678. "Set-Cookie: any\r\n"
  17679. "X-Forwarded-For: attacker.com\r\n"
  17680. "X-Real-Ip: 1.1.1.1\r\n"
  17681. "X-Hello: hello\r\n"
  17682. "X-World: world\r\n"
  17683. "\r\n";
  17684. std::string res;
  17685. ASSERT_TRUE(send_request(1, req, &res));
  17686. }
  17687. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17688. // several field lines, and the combined value is what has to be parsed. A
  17689. // Trailer field split across lines therefore declares every name it lists;
  17690. // reading only the first line silently drops the trailers the later lines
  17691. // declare. The prohibited-trailer filter still applies to every line.
  17692. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17693. Server svr;
  17694. size_t observed_trailer_count = 0;
  17695. std::string observed_hello;
  17696. std::string observed_world;
  17697. bool observed_content_length = true;
  17698. svr.Get("/", [&](const Request &req, Response &res) {
  17699. observed_trailer_count = req.trailers.size();
  17700. observed_hello = req.get_trailer_value("X-Hello");
  17701. observed_world = req.get_trailer_value("X-World");
  17702. observed_content_length = req.has_trailer("Content-Length");
  17703. res.set_content("ok", "text/plain");
  17704. });
  17705. auto port = svr.bind_to_any_port(HOST);
  17706. thread t = thread([&]() { svr.listen_after_bind(); });
  17707. auto se = detail::scope_exit([&] {
  17708. svr.stop();
  17709. t.join();
  17710. ASSERT_FALSE(svr.is_running());
  17711. });
  17712. svr.wait_until_ready();
  17713. const std::string req = "GET / HTTP/1.1\r\n"
  17714. "Host: localhost\r\n"
  17715. "Transfer-Encoding: chunked\r\n"
  17716. "Trailer: X-Hello\r\n"
  17717. "Trailer: X-World, Content-Length\r\n"
  17718. "\r\n"
  17719. "0\r\n"
  17720. "X-Hello: hello\r\n"
  17721. "X-World: world\r\n"
  17722. "Content-Length: 10\r\n"
  17723. "\r\n";
  17724. std::string res;
  17725. ASSERT_TRUE(send_request(1, req, &res, port));
  17726. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17727. // Accepted: both field lines contribute to the declared set
  17728. EXPECT_EQ(2U, observed_trailer_count);
  17729. EXPECT_EQ(observed_hello, "hello");
  17730. EXPECT_EQ(observed_world, "world");
  17731. // Denied: a prohibited name stays prohibited on a later field line
  17732. EXPECT_FALSE(observed_content_length);
  17733. }
  17734. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17735. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17736. // unbounded run of fields that are never declared, because the counter would
  17737. // only advance for declared fields.
  17738. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17739. Server svr;
  17740. bool handler_called = false;
  17741. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17742. handler_called = true;
  17743. res.set_content("ok", "text/plain");
  17744. });
  17745. auto port = svr.bind_to_any_port(HOST);
  17746. thread t = thread([&]() { svr.listen_after_bind(); });
  17747. auto se = detail::scope_exit([&] {
  17748. svr.stop();
  17749. t.join();
  17750. ASSERT_FALSE(svr.is_running());
  17751. });
  17752. svr.wait_until_ready();
  17753. // Declare nothing, then send far more undeclared trailer fields than the
  17754. // header-count limit. Parsing must stop and reject the request rather than
  17755. // read every line.
  17756. std::string req = "GET / HTTP/1.1\r\n"
  17757. "Transfer-Encoding: chunked\r\n"
  17758. "\r\n"
  17759. "0\r\n";
  17760. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17761. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17762. }
  17763. req += "\r\n";
  17764. std::string res;
  17765. ASSERT_TRUE(send_request(1, req, &res, port));
  17766. // The request is rejected before the handler runs.
  17767. EXPECT_FALSE(handler_called);
  17768. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17769. }
  17770. // The set of declared trailer names is capped so a peer cannot grow it without
  17771. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17772. // declared past the cap is not honored, even if the field is actually sent.
  17773. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17774. Server svr;
  17775. // One name inside the cap and one past it, so the test tracks the cap rather
  17776. // than a fixed count.
  17777. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17778. const std::string within_cap_name = "X-T-0";
  17779. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17780. bool observed_within_cap = false;
  17781. bool observed_past_cap = false;
  17782. svr.Get("/", [&](const Request &req, Response &res) {
  17783. observed_within_cap = req.has_trailer(within_cap_name);
  17784. observed_past_cap = req.has_trailer(past_cap_name);
  17785. res.set_content("ok", "text/plain");
  17786. });
  17787. auto port = svr.bind_to_any_port(HOST);
  17788. thread t = thread([&]() { svr.listen_after_bind(); });
  17789. auto se = detail::scope_exit([&] {
  17790. svr.stop();
  17791. t.join();
  17792. ASSERT_FALSE(svr.is_running());
  17793. });
  17794. svr.wait_until_ready();
  17795. // Declare more trailer names than the cap in a single Trailer field, then
  17796. // actually send the first (within the cap) and the last (past it).
  17797. std::string trailer_decl = "Trailer: ";
  17798. for (int i = 0; i < declared_count; i++) {
  17799. if (i != 0) { trailer_decl += ", "; }
  17800. trailer_decl += "X-T-" + std::to_string(i);
  17801. }
  17802. trailer_decl += "\r\n";
  17803. const std::string req = "GET / HTTP/1.1\r\n"
  17804. "Host: localhost\r\n"
  17805. "Transfer-Encoding: chunked\r\n" +
  17806. trailer_decl +
  17807. "\r\n"
  17808. "0\r\n" +
  17809. within_cap_name + ": a\r\n" + past_cap_name +
  17810. ": b\r\n"
  17811. "\r\n";
  17812. std::string res;
  17813. ASSERT_TRUE(send_request(1, req, &res, port));
  17814. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17815. // A name within the cap is honored; one declared past the cap is dropped.
  17816. EXPECT_TRUE(observed_within_cap);
  17817. EXPECT_FALSE(observed_past_cap);
  17818. }
  17819. // A direct client that is not listed in trusted_proxies must not be able to
  17820. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17821. // the peer address on the actual TCP connection determines whether the
  17822. // header is honored.
  17823. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17824. Server svr;
  17825. // Deliberately does NOT include the loopback address the test client
  17826. // actually connects from, so the direct connection is not a trusted proxy.
  17827. svr.set_trusted_proxies({"203.0.113.66"});
  17828. std::string observed_remote_addr;
  17829. svr.Get("/ip", [&](const Request &req, Response &res) {
  17830. observed_remote_addr = req.remote_addr;
  17831. res.set_content("ok", "text/plain");
  17832. });
  17833. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17834. auto se = detail::scope_exit([&] {
  17835. svr.stop();
  17836. t.join();
  17837. ASSERT_FALSE(svr.is_running());
  17838. });
  17839. svr.wait_until_ready();
  17840. Client cli(HOST, PORT);
  17841. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17843. EXPECT_EQ(StatusCode::OK_200, res->status);
  17844. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17845. // ignored entirely and the real connection-level address retained.
  17846. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17847. observed_remote_addr == "127.0.0.1");
  17848. }
  17849. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17850. Server svr;
  17851. std::string observed_remote_addr;
  17852. std::string observed_xff;
  17853. svr.Get("/ip", [&](const Request &req, Response &res) {
  17854. observed_remote_addr = req.remote_addr;
  17855. observed_xff = req.get_header_value("X-Forwarded-For");
  17856. res.set_content("ok", "text/plain");
  17857. });
  17858. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17859. auto se = detail::scope_exit([&] {
  17860. svr.stop();
  17861. t.join();
  17862. ASSERT_FALSE(svr.is_running());
  17863. });
  17864. svr.wait_until_ready();
  17865. Client cli(HOST, PORT);
  17866. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17868. EXPECT_EQ(StatusCode::OK_200, res->status);
  17869. EXPECT_EQ(observed_xff, "203.0.113.66");
  17870. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17871. observed_remote_addr == "127.0.0.1");
  17872. }
  17873. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17874. Server svr;
  17875. svr.set_trusted_proxies({"203.0.113.66"});
  17876. std::string observed_remote_addr;
  17877. std::string observed_xff;
  17878. svr.Get("/ip", [&](const Request &req, Response &res) {
  17879. observed_remote_addr = req.remote_addr;
  17880. observed_xff = req.get_header_value("X-Forwarded-For");
  17881. res.set_content("ok", "text/plain");
  17882. });
  17883. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17884. auto se = detail::scope_exit([&] {
  17885. svr.stop();
  17886. t.join();
  17887. ASSERT_FALSE(svr.is_running());
  17888. });
  17889. svr.wait_until_ready();
  17890. Client cli(HOST, PORT);
  17891. auto res = cli.Get("/ip");
  17892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17893. EXPECT_EQ(StatusCode::OK_200, res->status);
  17894. EXPECT_EQ(observed_xff, "");
  17895. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17896. observed_remote_addr == "127.0.0.1");
  17897. }
  17898. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17899. Server svr;
  17900. // Include the loopback address the test client actually connects from, so
  17901. // the direct connection itself is recognized as the trusted proxy hop.
  17902. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17903. std::string observed_remote_addr;
  17904. std::string observed_xff;
  17905. svr.Get("/ip", [&](const Request &req, Response &res) {
  17906. observed_remote_addr = req.remote_addr;
  17907. observed_xff = req.get_header_value("X-Forwarded-For");
  17908. res.set_content("ok", "text/plain");
  17909. });
  17910. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17911. auto se = detail::scope_exit([&] {
  17912. svr.stop();
  17913. t.join();
  17914. ASSERT_FALSE(svr.is_running());
  17915. });
  17916. svr.wait_until_ready();
  17917. Client cli(HOST, PORT);
  17918. auto res = cli.Get(
  17919. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17921. EXPECT_EQ(StatusCode::OK_200, res->status);
  17922. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17923. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17924. }
  17925. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17926. Server svr;
  17927. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17928. std::string observed_remote_addr;
  17929. std::string observed_xff;
  17930. svr.Get("/ip", [&](const Request &req, Response &res) {
  17931. observed_remote_addr = req.remote_addr;
  17932. observed_xff = req.get_header_value("X-Forwarded-For");
  17933. res.set_content("ok", "text/plain");
  17934. });
  17935. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17936. auto se = detail::scope_exit([&] {
  17937. svr.stop();
  17938. t.join();
  17939. ASSERT_FALSE(svr.is_running());
  17940. });
  17941. svr.wait_until_ready();
  17942. Client cli(HOST, PORT);
  17943. auto res = cli.Get(
  17944. "/ip",
  17945. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17947. EXPECT_EQ(StatusCode::OK_200, res->status);
  17948. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17949. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17950. }
  17951. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17952. Server svr;
  17953. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17954. std::string observed_remote_addr;
  17955. std::string observed_xff;
  17956. svr.Get("/ip", [&](const Request &req, Response &res) {
  17957. observed_remote_addr = req.remote_addr;
  17958. observed_xff = req.get_header_value("X-Forwarded-For");
  17959. res.set_content("ok", "text/plain");
  17960. });
  17961. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17962. auto se = detail::scope_exit([&] {
  17963. svr.stop();
  17964. t.join();
  17965. ASSERT_FALSE(svr.is_running());
  17966. });
  17967. svr.wait_until_ready();
  17968. Client cli(HOST, PORT);
  17969. auto res = cli.Get(
  17970. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17972. EXPECT_EQ(StatusCode::OK_200, res->status);
  17973. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17974. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17975. // and must not be selected.
  17976. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17977. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17978. }
  17979. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17980. Server svr;
  17981. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17982. std::string observed_remote_addr;
  17983. svr.Get("/ip", [&](const Request &req, Response &res) {
  17984. observed_remote_addr = req.remote_addr;
  17985. res.set_content("ok", "text/plain");
  17986. });
  17987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17988. auto se = detail::scope_exit([&] {
  17989. svr.stop();
  17990. t.join();
  17991. ASSERT_FALSE(svr.is_running());
  17992. });
  17993. svr.wait_until_ready();
  17994. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17995. // a forged address and the trusted proxy's own address; the forged value must
  17996. // not win over the address the trusted proxy actually recorded.
  17997. Client cli(HOST, PORT);
  17998. auto res = cli.Get(
  17999. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18001. EXPECT_EQ(StatusCode::OK_200, res->status);
  18002. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18003. }
  18004. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18005. Server svr;
  18006. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18007. std::string observed_remote_addr;
  18008. std::string observed_xff;
  18009. svr.Get("/ip", [&](const Request &req, Response &res) {
  18010. observed_remote_addr = req.remote_addr;
  18011. observed_xff = req.get_header_value("X-Forwarded-For");
  18012. res.set_content("ok", "text/plain");
  18013. });
  18014. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18015. auto se = detail::scope_exit([&] {
  18016. svr.stop();
  18017. t.join();
  18018. ASSERT_FALSE(svr.is_running());
  18019. });
  18020. svr.wait_until_ready();
  18021. Client cli(HOST, PORT);
  18022. auto res = cli.Get(
  18023. "/ip",
  18024. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18026. EXPECT_EQ(StatusCode::OK_200, res->status);
  18027. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18028. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18029. }
  18030. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18031. Server svr;
  18032. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18033. std::string observed_remote_addr;
  18034. std::string observed_xff;
  18035. svr.Get("/ip", [&](const Request &req, Response &res) {
  18036. observed_remote_addr = req.remote_addr;
  18037. observed_xff = req.get_header_value("X-Forwarded-For");
  18038. res.set_content("ok", "text/plain");
  18039. });
  18040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18041. auto se = detail::scope_exit([&] {
  18042. svr.stop();
  18043. t.join();
  18044. ASSERT_FALSE(svr.is_running());
  18045. });
  18046. svr.wait_until_ready();
  18047. std::string raw_req =
  18048. "GET /ip HTTP/1.1\r\n"
  18049. "Host: localhost\r\n"
  18050. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18051. "Connection: close\r\n"
  18052. "\r\n";
  18053. std::string out;
  18054. ASSERT_TRUE(send_request(5, raw_req, &out));
  18055. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18056. // Header parser trims surrounding whitespace of the header value
  18057. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18058. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18059. }
  18060. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18061. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18062. // their own X-Forwarded-For as a separate field line rather than extending the
  18063. // one the client sent, so every occurrence has to be taken into account.
  18064. // Reading only the first one hands back the address the client chose.
  18065. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18066. Server svr;
  18067. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18068. std::string observed_remote_addr;
  18069. size_t observed_xff_count = 0;
  18070. svr.Get("/ip", [&](const Request &req, Response &res) {
  18071. observed_remote_addr = req.remote_addr;
  18072. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18073. res.set_content("ok", "text/plain");
  18074. });
  18075. auto port = svr.bind_to_any_port(HOST);
  18076. thread t = thread([&]() { svr.listen_after_bind(); });
  18077. auto se = detail::scope_exit([&] {
  18078. svr.stop();
  18079. t.join();
  18080. ASSERT_FALSE(svr.is_running());
  18081. });
  18082. svr.wait_until_ready();
  18083. // The client supplies the first field line; the trusted proxy appends the
  18084. // address it observed as a second one.
  18085. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18086. "Host: localhost\r\n"
  18087. "X-Forwarded-For: 1.2.3.4\r\n"
  18088. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18089. "Connection: close\r\n"
  18090. "\r\n";
  18091. std::string out;
  18092. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18093. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18094. EXPECT_EQ(observed_xff_count, 2U);
  18095. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18096. // The same chain spread over one field line per hop derives the same client
  18097. // address, i.e. the split and the comma-joined representations agree.
  18098. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18099. "Host: localhost\r\n"
  18100. "X-Forwarded-For: 1.2.3.4\r\n"
  18101. "X-Forwarded-For: 198.51.100.23\r\n"
  18102. "X-Forwarded-For: 192.0.2.45\r\n"
  18103. "Connection: close\r\n"
  18104. "\r\n";
  18105. out.clear();
  18106. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18107. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18108. EXPECT_EQ(observed_xff_count, 3U);
  18109. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18110. }
  18111. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18112. // crash the server (it used to call front() on an empty vector inside
  18113. // get_client_ip). The connection-level remote address must be retained instead.
  18114. static void run_malformed_xff_test(const std::string &xff_value) {
  18115. Server svr;
  18116. svr.set_trusted_proxies({"192.0.2.45"});
  18117. std::string observed_remote_addr;
  18118. svr.Get("/ip", [&](const Request &req, Response &res) {
  18119. observed_remote_addr = req.remote_addr;
  18120. res.set_content("ok", "text/plain");
  18121. });
  18122. int port = 0;
  18123. thread t = thread([&]() {
  18124. port = svr.bind_to_any_port(HOST);
  18125. svr.listen_after_bind();
  18126. });
  18127. auto se = detail::scope_exit([&] {
  18128. svr.stop();
  18129. t.join();
  18130. ASSERT_FALSE(svr.is_running());
  18131. });
  18132. svr.wait_until_ready();
  18133. Client cli(HOST, port);
  18134. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18136. EXPECT_EQ(StatusCode::OK_200, res->status);
  18137. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18138. observed_remote_addr == "127.0.0.1");
  18139. }
  18140. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18141. run_malformed_xff_test("");
  18142. }
  18143. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18144. run_malformed_xff_test(",");
  18145. }
  18146. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18147. run_malformed_xff_test(", , ,");
  18148. }
  18149. // The same rule applies to Accept: a request whose acceptable types are spread
  18150. // over several field lines must be negotiated against all of them.
  18151. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18152. // case-insensitive connection options. Comparing the whole field value against
  18153. // one option misses a client that sends several of them, and misses every
  18154. // casing but the one written in the comparison.
  18155. //
  18156. // Sends req, reads the response, then reuses the same socket for a second
  18157. // request to find out whether the server kept the connection.
  18158. static void probe_connection_reuse(int port, const std::string &req,
  18159. bool *announced_close, bool *reusable) {
  18160. auto error = Error::Success;
  18161. auto sock = detail::create_client_socket(
  18162. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18163. /*connection_timeout_sec=*/5, 0,
  18164. /*read_timeout_sec=*/1, 0,
  18165. /*write_timeout_sec=*/5, 0, std::string(), error);
  18166. ASSERT_NE(sock, INVALID_SOCKET);
  18167. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18168. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18169. "Host: localhost\r\n"
  18170. "Connection: close\r\n"
  18171. "\r\n";
  18172. std::string first_response;
  18173. std::string second_response;
  18174. detail::process_client_socket(
  18175. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18176. [&](Stream &strm) {
  18177. if (strm.write(req.data(), req.size()) !=
  18178. static_cast<ssize_t>(req.size())) {
  18179. return false;
  18180. }
  18181. char buf[512];
  18182. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18183. // Headers plus the two-byte body of the handler below
  18184. while (reader.getline()) {
  18185. first_response += reader.ptr();
  18186. if (first_response.find("ok") != std::string::npos) { break; }
  18187. }
  18188. if (strm.write(second.data(), second.size()) !=
  18189. static_cast<ssize_t>(second.size())) {
  18190. return true;
  18191. }
  18192. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18193. while (reader2.getline()) {
  18194. second_response += reader2.ptr();
  18195. if (second_response.find("ok") != std::string::npos) { break; }
  18196. }
  18197. return true;
  18198. });
  18199. *announced_close =
  18200. first_response.find("Connection: close") != std::string::npos;
  18201. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18202. }
  18203. class ConnectionTokenTest : public ::testing::Test {
  18204. protected:
  18205. void SetUp() override {
  18206. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18207. res.set_content("ok", "text/plain");
  18208. });
  18209. port_ = svr_.bind_to_any_port(HOST);
  18210. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18211. svr_.wait_until_ready();
  18212. }
  18213. void TearDown() override {
  18214. svr_.stop();
  18215. if (thread_.joinable()) { thread_.join(); }
  18216. }
  18217. Server svr_;
  18218. int port_ = 0;
  18219. thread thread_;
  18220. };
  18221. // "close" alongside another option still closes the connection, and the
  18222. // response says so rather than leaving the peer to discover it.
  18223. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18224. bool announced_close = false;
  18225. bool reusable = true;
  18226. probe_connection_reuse(port_,
  18227. "GET /keepalive HTTP/1.1\r\n"
  18228. "Host: localhost\r\n"
  18229. "Connection: keep-alive, close\r\n"
  18230. "\r\n",
  18231. &announced_close, &reusable);
  18232. EXPECT_TRUE(announced_close);
  18233. EXPECT_FALSE(reusable);
  18234. }
  18235. // "close" split over two field lines is the same list, so it is honored too.
  18236. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18237. bool announced_close = false;
  18238. bool reusable = true;
  18239. probe_connection_reuse(port_,
  18240. "GET /keepalive HTTP/1.1\r\n"
  18241. "Host: localhost\r\n"
  18242. "Connection: keep-alive\r\n"
  18243. "Connection: close\r\n"
  18244. "\r\n",
  18245. &announced_close, &reusable);
  18246. EXPECT_TRUE(announced_close);
  18247. EXPECT_FALSE(reusable);
  18248. }
  18249. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18250. // keep-alive in the spelling everyone actually sends keeps its connection.
  18251. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18252. bool announced_close = false;
  18253. bool reusable = false;
  18254. probe_connection_reuse(port_,
  18255. "GET /keepalive HTTP/1.0\r\n"
  18256. "Host: localhost\r\n"
  18257. "Connection: keep-alive\r\n"
  18258. "\r\n",
  18259. &announced_close, &reusable);
  18260. EXPECT_FALSE(announced_close);
  18261. EXPECT_TRUE(reusable);
  18262. }
  18263. // A token the value merely contains is not the token itself.
  18264. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18265. bool announced_close = false;
  18266. bool reusable = false;
  18267. probe_connection_reuse(port_,
  18268. "GET /keepalive HTTP/1.1\r\n"
  18269. "Host: localhost\r\n"
  18270. "Connection: notclose\r\n"
  18271. "\r\n",
  18272. &announced_close, &reusable);
  18273. EXPECT_FALSE(announced_close);
  18274. EXPECT_TRUE(reusable);
  18275. }
  18276. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18277. Server svr;
  18278. std::vector<std::string> observed_types;
  18279. svr.Get("/", [&](const Request &req, Response &res) {
  18280. observed_types = req.accept_content_types;
  18281. res.set_content("ok", "text/plain");
  18282. });
  18283. auto port = svr.bind_to_any_port(HOST);
  18284. thread t = thread([&]() { svr.listen_after_bind(); });
  18285. auto se = detail::scope_exit([&] {
  18286. svr.stop();
  18287. t.join();
  18288. ASSERT_FALSE(svr.is_running());
  18289. });
  18290. svr.wait_until_ready();
  18291. Client cli(HOST, port);
  18292. Headers headers;
  18293. headers.emplace("Accept", "text/plain;q=0.5");
  18294. headers.emplace("Accept", "application/json");
  18295. auto res = cli.Get("/", headers);
  18296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18297. EXPECT_EQ(StatusCode::OK_200, res->status);
  18298. // Sorted by q-value, so the second field line's type comes first
  18299. ASSERT_EQ(2U, observed_types.size());
  18300. EXPECT_EQ("application/json", observed_types[0]);
  18301. EXPECT_EQ("text/plain", observed_types[1]);
  18302. }
  18303. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18304. // empty field line must not contribute a bare comma to the combined value.
  18305. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18306. Server svr;
  18307. std::vector<std::string> observed_types;
  18308. svr.Get("/", [&](const Request &req, Response &res) {
  18309. observed_types = req.accept_content_types;
  18310. res.set_content("ok", "text/plain");
  18311. });
  18312. auto port = svr.bind_to_any_port(HOST);
  18313. thread t = thread([&]() { svr.listen_after_bind(); });
  18314. auto se = detail::scope_exit([&] {
  18315. svr.stop();
  18316. t.join();
  18317. ASSERT_FALSE(svr.is_running());
  18318. });
  18319. svr.wait_until_ready();
  18320. // Empty first field line, then a real one
  18321. std::string raw_req = "GET / HTTP/1.1\r\n"
  18322. "Host: localhost\r\n"
  18323. "Accept:\r\n"
  18324. "Accept: application/json\r\n"
  18325. "Connection: close\r\n"
  18326. "\r\n";
  18327. std::string out;
  18328. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18329. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18330. ASSERT_EQ(1U, observed_types.size());
  18331. EXPECT_EQ("application/json", observed_types[0]);
  18332. }
  18333. // The skip in get_combined_header_value() is what keeps an empty field line
  18334. // from contributing a bare comma. Only a trailing empty field line exercises
  18335. // it: a leading one is already covered by the "combined is still empty" check,
  18336. // and parse_accept_header() now ignores the empty element either way, so the
  18337. // request-level test above can no longer tell the two apart.
  18338. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18339. Headers headers;
  18340. headers.emplace("Accept", "text/html");
  18341. headers.emplace("Accept", "");
  18342. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18343. headers.clear();
  18344. headers.emplace("Accept", "");
  18345. headers.emplace("Accept", "application/json");
  18346. EXPECT_EQ("application/json",
  18347. detail::get_combined_header_value(headers, "Accept"));
  18348. }
  18349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18350. // An encoding offered on a later Accept-Encoding field line is still offered.
  18351. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18352. Server svr;
  18353. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18354. res.set_content(std::string(1024, 'x'), "text/plain");
  18355. });
  18356. auto port = svr.bind_to_any_port(HOST);
  18357. thread t = thread([&]() { svr.listen_after_bind(); });
  18358. auto se = detail::scope_exit([&] {
  18359. svr.stop();
  18360. t.join();
  18361. ASSERT_FALSE(svr.is_running());
  18362. });
  18363. svr.wait_until_ready();
  18364. Client cli(HOST, port);
  18365. cli.set_decompress(false);
  18366. Headers headers;
  18367. headers.emplace("Accept-Encoding", "identity");
  18368. headers.emplace("Accept-Encoding", "gzip");
  18369. auto res = cli.Get("/", headers);
  18370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18371. EXPECT_EQ(StatusCode::OK_200, res->status);
  18372. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18373. }
  18374. #endif
  18375. #ifndef _WIN32
  18376. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18377. Server svr;
  18378. svr.Post("/post", [&](const Request &req, Response &res) {
  18379. res.set_content(req.body, "text/plain");
  18380. });
  18381. svr.Put("/put", [&](const Request &req, Response &res) {
  18382. res.set_content(req.body, "text/plain");
  18383. });
  18384. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18385. res.set_content(req.body, "text/plain");
  18386. });
  18387. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18388. res.set_content(req.body, "text/plain");
  18389. });
  18390. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18391. auto se = detail::scope_exit([&] {
  18392. svr.stop();
  18393. t.join();
  18394. ASSERT_FALSE(svr.is_running());
  18395. });
  18396. svr.wait_until_ready();
  18397. std::string resp;
  18398. // POST without Content-Length
  18399. ASSERT_TRUE(send_request(5,
  18400. "POST /post HTTP/1.1\r\n"
  18401. "Host: localhost\r\n"
  18402. "Connection: close\r\n"
  18403. "\r\n",
  18404. &resp));
  18405. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18406. // PUT without Content-Length
  18407. resp.clear();
  18408. ASSERT_TRUE(send_request(5,
  18409. "PUT /put HTTP/1.1\r\n"
  18410. "Host: localhost\r\n"
  18411. "Connection: close\r\n"
  18412. "\r\n",
  18413. &resp));
  18414. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18415. // PATCH without Content-Length
  18416. resp.clear();
  18417. ASSERT_TRUE(send_request(5,
  18418. "PATCH /patch HTTP/1.1\r\n"
  18419. "Host: localhost\r\n"
  18420. "Connection: close\r\n"
  18421. "\r\n",
  18422. &resp));
  18423. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18424. // DELETE without Content-Length
  18425. resp.clear();
  18426. ASSERT_TRUE(send_request(5,
  18427. "DELETE /delete HTTP/1.1\r\n"
  18428. "Host: localhost\r\n"
  18429. "Connection: close\r\n"
  18430. "\r\n",
  18431. &resp));
  18432. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18433. }
  18434. #endif
  18435. //==============================================================================
  18436. // open_stream() Tests
  18437. //==============================================================================
  18438. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18439. std::string result;
  18440. char buf[8192];
  18441. ssize_t n;
  18442. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18443. result.append(buf, static_cast<size_t>(n));
  18444. }
  18445. return result;
  18446. }
  18447. // Mock stream for unit tests
  18448. class MockStream : public Stream {
  18449. public:
  18450. std::string data;
  18451. size_t pos = 0;
  18452. ssize_t error_after = -1; // -1 = no error
  18453. explicit MockStream(const std::string &d, ssize_t err = -1)
  18454. : data(d), error_after(err) {}
  18455. bool is_readable() const override { return true; }
  18456. bool wait_readable() const override { return true; }
  18457. bool wait_writable() const override { return true; }
  18458. ssize_t read(char *ptr, size_t size) override {
  18459. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18460. if (pos >= data.size()) return 0;
  18461. size_t limit =
  18462. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18463. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18464. std::memcpy(ptr, data.data() + pos, to_read);
  18465. pos += to_read;
  18466. return static_cast<ssize_t>(to_read);
  18467. }
  18468. ssize_t write(const char *, size_t) override { return -1; }
  18469. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18470. ip = "127.0.0.1";
  18471. port = 0;
  18472. }
  18473. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18474. ip = "127.0.0.1";
  18475. port = 0;
  18476. }
  18477. socket_t socket() const override { return INVALID_SOCKET; }
  18478. time_t duration() const override { return 0; }
  18479. };
  18480. TEST(StreamHandleTest, Basic) {
  18481. ClientImpl::StreamHandle handle;
  18482. EXPECT_FALSE(handle.is_valid());
  18483. handle.response = detail::make_unique<Response>();
  18484. handle.error = Error::Connection;
  18485. EXPECT_FALSE(handle.is_valid());
  18486. handle.error = Error::Success;
  18487. EXPECT_TRUE(handle.is_valid());
  18488. }
  18489. TEST(BodyReaderTest, Basic) {
  18490. MockStream stream("Hello, World!");
  18491. detail::BodyReader reader;
  18492. reader.stream = &stream;
  18493. reader.content_length = 13;
  18494. char buf[32];
  18495. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18496. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18497. EXPECT_TRUE(reader.eof);
  18498. }
  18499. TEST(BodyReaderTest, NoStream) {
  18500. detail::BodyReader reader;
  18501. char buf[32];
  18502. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18503. EXPECT_EQ(Error::Connection, reader.last_error);
  18504. }
  18505. TEST(BodyReaderTest, Error) {
  18506. MockStream stream("Hello, World!", 5);
  18507. detail::BodyReader reader;
  18508. reader.stream = &stream;
  18509. reader.content_length = 13;
  18510. char buf[32];
  18511. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18512. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18513. EXPECT_EQ(Error::Read, reader.last_error);
  18514. }
  18515. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18516. // Mock-based StreamHandle tests relying on private internals are removed.
  18517. class OpenStreamTest : public ::testing::Test {
  18518. protected:
  18519. void SetUp() override {
  18520. svr_.Get("/hello", [](const Request &, Response &res) {
  18521. res.set_content("Hello World!", "text/plain");
  18522. });
  18523. svr_.Get("/large", [](const Request &, Response &res) {
  18524. res.set_content(std::string(10000, 'X'), "text/plain");
  18525. });
  18526. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18527. res.set_content("Hello World!", "image/jpeg");
  18528. res.set_header("Content-Encoding", "UTF-8");
  18529. });
  18530. svr_.Get("/chunked", [](const Request &, Response &res) {
  18531. res.set_chunked_content_provider("text/plain",
  18532. [](size_t offset, DataSink &sink) {
  18533. if (offset < 15) {
  18534. sink.write("chunk", 5);
  18535. return true;
  18536. }
  18537. sink.done();
  18538. return true;
  18539. });
  18540. });
  18541. svr_.Get("/compressible", [](const Request &, Response &res) {
  18542. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18543. DataSink &sink) {
  18544. if (offset < 100 * 1024) {
  18545. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18546. sink.write(chunk.data(), chunk.size());
  18547. return true;
  18548. }
  18549. sink.done();
  18550. return true;
  18551. });
  18552. });
  18553. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18554. [](const Request & /*req*/, Response &res) {
  18555. auto i = new int(0);
  18556. res.set_header("Trailer", "Content-Length, X-Allowed");
  18557. res.set_chunked_content_provider(
  18558. "text/plain",
  18559. [i](size_t /*offset*/, DataSink &sink) {
  18560. switch (*i) {
  18561. case 0: sink.os << "123"; break;
  18562. case 1: sink.os << "456"; break;
  18563. case 2: sink.os << "789"; break;
  18564. case 3: {
  18565. sink.done_with_trailer(
  18566. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18567. } break;
  18568. }
  18569. (*i)++;
  18570. return true;
  18571. },
  18572. [i](bool success) {
  18573. EXPECT_TRUE(success);
  18574. delete i;
  18575. });
  18576. });
  18577. // Echo headers endpoint for header-related tests
  18578. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18579. std::string body;
  18580. for (const auto &h : req.headers) {
  18581. body.append(h.first);
  18582. body.push_back(':');
  18583. body.append(h.second);
  18584. body.push_back('\n');
  18585. }
  18586. res.set_content(body, "text/plain");
  18587. });
  18588. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18589. std::string body;
  18590. for (const auto &h : req.headers) {
  18591. body.append(h.first);
  18592. body.push_back(':');
  18593. body.append(h.second);
  18594. body.push_back('\n');
  18595. }
  18596. res.set_content(body, "text/plain");
  18597. });
  18598. port_ = svr_.bind_to_any_port("127.0.0.1");
  18599. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18600. svr_.wait_until_ready();
  18601. }
  18602. void TearDown() override {
  18603. svr_.stop();
  18604. if (thread_.joinable()) thread_.join();
  18605. }
  18606. Server svr_;
  18607. std::thread thread_;
  18608. int port_ = 0;
  18609. };
  18610. TEST_F(OpenStreamTest, Basic) {
  18611. Client cli("127.0.0.1", port_);
  18612. auto handle = cli.open_stream("GET", "/hello");
  18613. EXPECT_TRUE(handle.is_valid());
  18614. EXPECT_EQ("Hello World!", read_all(handle));
  18615. }
  18616. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18617. Client cli("127.0.0.1", port_);
  18618. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18619. ASSERT_TRUE(handle.is_valid());
  18620. EXPECT_EQ("Hello World!", read_all(handle));
  18621. }
  18622. TEST_F(OpenStreamTest, SmallBuffer) {
  18623. Client cli("127.0.0.1", port_);
  18624. auto handle = cli.open_stream("GET", "/hello");
  18625. std::string result;
  18626. char buf[4];
  18627. ssize_t n;
  18628. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18629. result.append(buf, static_cast<size_t>(n));
  18630. EXPECT_EQ("Hello World!", result);
  18631. }
  18632. TEST_F(OpenStreamTest, DefaultHeaders) {
  18633. Client cli("127.0.0.1", port_);
  18634. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18635. {
  18636. auto handle = cli.open_stream("GET", "/echo-headers");
  18637. ASSERT_TRUE(handle.is_valid());
  18638. auto body = read_all(handle);
  18639. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18640. std::string::npos);
  18641. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18642. std::string::npos);
  18643. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18644. }
  18645. // open_stream POST with body and no explicit content_type should NOT add
  18646. // text/plain Content-Type (behavior differs from non-streaming path), but
  18647. // should include Content-Length
  18648. {
  18649. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18650. ASSERT_TRUE(handle.is_valid());
  18651. auto body = read_all(handle);
  18652. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18653. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18654. }
  18655. // open_stream POST with explicit Content-Type should preserve it
  18656. {
  18657. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18658. {{"Content-Type", "application/custom"}},
  18659. "{}", "application/custom");
  18660. ASSERT_TRUE(handle.is_valid());
  18661. auto body = read_all(handle);
  18662. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18663. }
  18664. // User-specified User-Agent must not be overwritten for stream API
  18665. {
  18666. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18667. {{"User-Agent", "MyAgent/1.2"}});
  18668. ASSERT_TRUE(handle.is_valid());
  18669. auto body = read_all(handle);
  18670. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18671. }
  18672. }
  18673. TEST_F(OpenStreamTest, Large) {
  18674. Client cli("127.0.0.1", port_);
  18675. auto handle = cli.open_stream("GET", "/large");
  18676. EXPECT_EQ(10000u, read_all(handle).size());
  18677. }
  18678. TEST_F(OpenStreamTest, ConnectionError) {
  18679. Client cli("127.0.0.1", 9999);
  18680. auto handle = cli.open_stream("GET", "/hello");
  18681. EXPECT_FALSE(handle.is_valid());
  18682. }
  18683. TEST_F(OpenStreamTest, Chunked) {
  18684. Client cli("127.0.0.1", port_);
  18685. auto handle = cli.open_stream("GET", "/chunked");
  18686. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18687. "Transfer-Encoding") == "chunked");
  18688. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18689. }
  18690. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18691. Client cli("127.0.0.1", port_);
  18692. auto handle =
  18693. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18694. ASSERT_TRUE(handle.is_valid());
  18695. // Consume body to allow trailers to be received/parsed
  18696. auto body = read_all(handle);
  18697. // Explicitly parse trailers (ensure trailers are available for assertion)
  18698. handle.parse_trailers_if_needed();
  18699. EXPECT_EQ(std::string("123456789"), body);
  18700. // The response should include a Trailer header declaring both names
  18701. ASSERT_TRUE(handle.response);
  18702. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18703. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18704. handle.response->get_header_value("Trailer"));
  18705. // Prohibited trailer must not be present
  18706. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18707. // Allowed trailer should be present
  18708. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18709. EXPECT_EQ(std::string("yes"),
  18710. handle.response->get_trailer_value("X-Allowed"));
  18711. // Verify trailers are NOT present as regular headers
  18712. EXPECT_EQ(std::string(""),
  18713. handle.response->get_header_value("Content-Length"));
  18714. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18715. }
  18716. // Accepts one connection on an OS-assigned port, which it hands over through
  18717. // port_promise, reads the request head and sends back response. after_send,
  18718. // if given, runs on the connection before it is closed.
  18719. static std::thread
  18720. serve_single_response(std::promise<int> &port_promise,
  18721. const std::string &response,
  18722. std::function<void(socket_t)> after_send = nullptr) {
  18723. return std::thread([&port_promise, response, after_send] {
  18724. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18725. default_socket_options(srv);
  18726. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18727. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18728. sockaddr_in addr{};
  18729. addr.sin_family = AF_INET;
  18730. addr.sin_port = htons(0); // Let OS assign a free port
  18731. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18732. int opt = 1;
  18733. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18734. #ifdef _WIN32
  18735. reinterpret_cast<const char *>(&opt),
  18736. #else
  18737. &opt,
  18738. #endif
  18739. sizeof(opt));
  18740. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18741. ::listen(srv, 1) != 0) {
  18742. port_promise.set_value(-1);
  18743. detail::close_socket(srv);
  18744. return;
  18745. }
  18746. socklen_t addr_len = sizeof(addr);
  18747. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18748. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18749. sockaddr_in cli_addr{};
  18750. socklen_t cli_len = sizeof(cli_addr);
  18751. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18752. if (cli != INVALID_SOCKET) {
  18753. // Read the complete HTTP request (until the blank line that terminates
  18754. // headers) before sending the response. If the server closes the socket
  18755. // while the client's request data is still unread in the kernel receive
  18756. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18757. // connection on both sides: it discards the client's receive buffer
  18758. // (which already holds our response) and causes any in-progress write on
  18759. // the client to fail with ECONNRESET. Reading all request data first
  18760. // ensures close() emits a graceful FIN.
  18761. {
  18762. char rbuf[256];
  18763. std::string req;
  18764. while (req.find("\r\n\r\n") == std::string::npos) {
  18765. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18766. if (n <= 0) { break; }
  18767. req.append(rbuf, static_cast<size_t>(n));
  18768. }
  18769. }
  18770. ::send(cli,
  18771. #ifdef _WIN32
  18772. static_cast<const char *>(response.c_str()),
  18773. static_cast<int>(response.size()),
  18774. #else
  18775. response.c_str(), response.size(),
  18776. #endif
  18777. 0);
  18778. if (after_send) { after_send(cli); }
  18779. detail::close_socket(cli);
  18780. }
  18781. detail::close_socket(srv);
  18782. });
  18783. }
  18784. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18785. #ifndef _WIN32
  18786. signal(SIGPIPE, SIG_IGN);
  18787. #endif
  18788. std::promise<int> port_promise;
  18789. auto port_future = port_promise.get_future();
  18790. auto server_thread =
  18791. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18792. "Content-Type: text/plain\r\n"
  18793. "Content-Length: not-a-number\r\n"
  18794. "Connection: close\r\n"
  18795. "\r\n"
  18796. "hello");
  18797. auto port = port_future.get();
  18798. ASSERT_GT(port, 0);
  18799. Client cli("127.0.0.1", port);
  18800. auto handle = cli.open_stream("GET", "/");
  18801. EXPECT_FALSE(handle.is_valid());
  18802. server_thread.join();
  18803. }
  18804. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18805. #ifndef _WIN32
  18806. signal(SIGPIPE, SIG_IGN);
  18807. #endif
  18808. std::promise<int> port_promise;
  18809. auto port_future = port_promise.get_future();
  18810. auto server_thread = serve_single_response(
  18811. port_promise, "HTTP/1.1 200 OK\r\n"
  18812. "Content-Type: text/plain\r\n"
  18813. "Content-Length: 99999999999999999999999999\r\n"
  18814. "Connection: close\r\n"
  18815. "\r\n"
  18816. "hello");
  18817. auto port = port_future.get();
  18818. ASSERT_GT(port, 0);
  18819. // Historically std::stoull would throw std::out_of_range here and crash
  18820. // the process, then parsing silently clamped to a bogus framing length and
  18821. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18822. // so the stream fails to open, matching the not-a-number case above. The
  18823. // process still must NOT terminate.
  18824. Client cli("127.0.0.1", port);
  18825. auto handle = cli.open_stream("GET", "/");
  18826. EXPECT_FALSE(handle.is_valid());
  18827. server_thread.join();
  18828. }
  18829. // Serves `response` to the single request `fn` makes with a fresh client.
  18830. template <typename Fn>
  18831. static void with_single_response(const std::string &response, Fn fn) {
  18832. #ifndef _WIN32
  18833. signal(SIGPIPE, SIG_IGN);
  18834. #endif
  18835. std::promise<int> port_promise;
  18836. auto port_future = port_promise.get_future();
  18837. auto server_thread = serve_single_response(port_promise, response);
  18838. auto se = detail::scope_exit([&] { server_thread.join(); });
  18839. auto port = port_future.get();
  18840. ASSERT_GT(port, 0);
  18841. Client cli("127.0.0.1", port);
  18842. fn(cli);
  18843. }
  18844. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18845. const char *responses[] = {
  18846. "HTTP/1.1 103 Early Hints\r\n"
  18847. "Link: </style.css>; rel=preload\r\n"
  18848. "\r\n"
  18849. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18850. "HTTP/1.1 100 Continue\r\n"
  18851. "X-Note: interim\r\n"
  18852. "\r\n"
  18853. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18854. };
  18855. for (auto response : responses) {
  18856. with_single_response(response, [](Client &cli) {
  18857. auto res = cli.Get("/");
  18858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18859. EXPECT_EQ(StatusCode::OK_200, res->status);
  18860. EXPECT_EQ("ok", res->body);
  18861. });
  18862. }
  18863. }
  18864. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18865. #ifndef _WIN32
  18866. signal(SIGPIPE, SIG_IGN);
  18867. #endif
  18868. // The server answers the head without asking for the body. Bytes it then
  18869. // reads on the connection would be taken for the body the request declared.
  18870. auto closed_by_client = false;
  18871. std::promise<int> port_promise;
  18872. auto server_thread = serve_single_response(
  18873. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18874. [&](socket_t sock) {
  18875. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18876. char buf[256];
  18877. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  18878. });
  18879. Client cli("127.0.0.1", port_promise.get_future().get());
  18880. cli.set_keep_alive(true);
  18881. cli.set_read_timeout(1, 0);
  18882. // Long enough for the client to send Expect: 100-continue.
  18883. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18886. cli.Get("/second");
  18887. server_thread.join();
  18888. EXPECT_TRUE(closed_by_client);
  18889. }
  18890. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  18891. // Long enough for the client to send Expect: 100-continue
  18892. with_single_response(
  18893. "HTTP/1.1 103 Early Hints\r\n"
  18894. "Link: </style.css>; rel=preload\r\n"
  18895. "\r\n"
  18896. "HTTP/1.1 401 Unauthorized\r\n"
  18897. "Content-Length: 0\r\n\r\n",
  18898. [](Client &cli) {
  18899. cli.set_read_timeout(2, 0);
  18900. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18902. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18903. });
  18904. }
  18905. #ifdef CPPHTTPLIB_SSL_ENABLED
  18906. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  18907. #ifndef _WIN32
  18908. signal(SIGPIPE, SIG_IGN);
  18909. #endif
  18910. auto reused = false;
  18911. std::promise<int> port_promise;
  18912. auto server_thread = serve_single_response(
  18913. port_promise,
  18914. "HTTP/1.1 401 Unauthorized\r\n"
  18915. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  18916. "Content-Length: 0\r\n\r\n",
  18917. [&](socket_t sock) {
  18918. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18919. char buf[256];
  18920. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  18921. });
  18922. Client cli("127.0.0.1", port_promise.get_future().get());
  18923. cli.set_keep_alive(true);
  18924. cli.set_digest_auth("user", "pass");
  18925. cli.set_read_timeout(1, 0);
  18926. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18927. server_thread.join();
  18928. EXPECT_FALSE(reused);
  18929. }
  18930. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  18931. // Any other answer to CONNECT would read as the origin's response.
  18932. struct {
  18933. const char *response;
  18934. bool passed_on;
  18935. } cases[] = {
  18936. {"HTTP/1.1 201 Created\r\n"
  18937. "Set-Cookie: session=from-proxy\r\n"
  18938. "Content-Length: 0\r\n\r\n",
  18939. false},
  18940. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  18941. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  18942. "Content-Length: 0\r\n\r\n",
  18943. true},
  18944. };
  18945. for (const auto &c : cases) {
  18946. std::promise<int> port_promise;
  18947. auto server_thread = serve_single_response(port_promise, c.response);
  18948. SSLClient cli("example.com", 443);
  18949. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  18950. auto res = cli.Get("/");
  18951. server_thread.join();
  18952. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  18953. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  18954. if (res) {
  18955. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18956. }
  18957. }
  18958. }
  18959. #endif
  18960. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18961. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18962. // the chunked coding and drop Content-Length, so a front-end that trusts
  18963. // Content-Length would disagree about where the body ends (response
  18964. // smuggling). The client must reject such a response.
  18965. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18966. for (const char *te : {"chunked", "gzip, chunked"}) {
  18967. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18968. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18969. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18970. "5\r\nhello\r\n0\r\n\r\n";
  18971. with_single_response(response, [&](Client &cli) {
  18972. auto res = cli.Get("/");
  18973. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18974. EXPECT_EQ(Error::Read, res.error()) << te;
  18975. });
  18976. with_single_response(response, [&](Client &cli) {
  18977. auto handle = cli.open_stream("GET", "/");
  18978. EXPECT_FALSE(handle.is_valid()) << te;
  18979. EXPECT_EQ(Error::Read, handle.error) << te;
  18980. });
  18981. }
  18982. }
  18983. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18984. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18985. // closing the connection (unlike a request, which must be rejected).
  18986. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18987. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18988. "Transfer-Encoding: chunked\r\n"
  18989. "Connection: close\r\n"
  18990. "\r\n"
  18991. "5\r\nhello\r\n0\r\n\r\n",
  18992. "HTTP/1.1 200 OK\r\n"
  18993. "Transfer-Encoding: gzip\r\n"
  18994. "Connection: close\r\n"
  18995. "\r\n"
  18996. "hello"}) {
  18997. with_single_response(response, [&](Client &cli) {
  18998. auto res = cli.Get("/");
  18999. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19000. EXPECT_EQ("hello", res->body);
  19001. });
  19002. with_single_response(response, [&](Client &cli) {
  19003. auto handle = cli.open_stream("GET", "/");
  19004. ASSERT_TRUE(handle.is_valid()) << response;
  19005. EXPECT_EQ("hello", read_all(handle));
  19006. });
  19007. }
  19008. }
  19009. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19010. // framing headers describe nothing to read and must not be rejected.
  19011. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19012. const std::string framing = "Content-Length: 5\r\n"
  19013. "Transfer-Encoding: chunked\r\n"
  19014. "Connection: close\r\n"
  19015. "\r\n";
  19016. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19017. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19018. });
  19019. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19020. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19021. });
  19022. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19023. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19024. with_single_response(response, [&](Client &cli) {
  19025. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19026. });
  19027. with_single_response(response, [&](Client &cli) {
  19028. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19029. });
  19030. }
  19031. }
  19032. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19033. // response, is faulty framing, so the connection is not reused after it.
  19034. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19035. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19036. "Content-Length: 0\r\n"
  19037. "Transfer-Encoding: chunked\r\n"
  19038. "\r\n"
  19039. "5\r\nhello\r\n0\r\n\r\n",
  19040. "HTTP/1.0 200 Connection established\r\n"
  19041. "Connection: keep-alive\r\n"
  19042. "Transfer-Encoding: chunked\r\n"
  19043. "\r\n"
  19044. "5\r\nhello\r\n0\r\n\r\n"}) {
  19045. with_single_response(response, [&](Client &cli) {
  19046. cli.set_keep_alive(true);
  19047. auto res = cli.Get("/");
  19048. ASSERT_TRUE(res) << response;
  19049. EXPECT_EQ("hello", res->body);
  19050. EXPECT_FALSE(cli.is_socket_open()) << response;
  19051. });
  19052. }
  19053. }
  19054. // A payload max length of 0 means no limit, however the body is framed.
  19055. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19056. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19057. "Transfer-Encoding: chunked\r\n"
  19058. "\r\n"
  19059. "5\r\nhello\r\n0\r\n\r\n",
  19060. "HTTP/1.1 200 OK\r\n"
  19061. "Connection: close\r\n"
  19062. "\r\n"
  19063. "hello"}) {
  19064. with_single_response(response, [&](Client &cli) {
  19065. cli.set_payload_max_length(0);
  19066. auto res = cli.Get("/");
  19067. ASSERT_TRUE(res) << response;
  19068. EXPECT_EQ("hello", res->body) << response;
  19069. });
  19070. }
  19071. }
  19072. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19073. Server svr;
  19074. svr.set_payload_max_length(0);
  19075. svr.Post("/echo", [](const Request &req, Response &res) {
  19076. res.set_content(req.body, "text/plain");
  19077. });
  19078. auto port = svr.bind_to_any_port(HOST);
  19079. thread t = thread([&] { svr.listen_after_bind(); });
  19080. auto se = detail::scope_exit([&] {
  19081. svr.stop();
  19082. t.join();
  19083. ASSERT_FALSE(svr.is_running());
  19084. });
  19085. svr.wait_until_ready();
  19086. Client cli(HOST, port);
  19087. auto res = cli.Post(
  19088. "/echo",
  19089. [](size_t /*offset*/, DataSink &sink) {
  19090. sink.write("hello", 5);
  19091. sink.done();
  19092. return true;
  19093. },
  19094. "text/plain");
  19095. ASSERT_TRUE(res);
  19096. EXPECT_EQ(StatusCode::OK_200, res->status);
  19097. EXPECT_EQ("hello", res->body);
  19098. }
  19099. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19100. TEST_F(OpenStreamTest, Gzip) {
  19101. Client cli("127.0.0.1", port_);
  19102. auto handle = cli.open_stream("GET", "/compressible", {},
  19103. {{"Accept-Encoding", "gzip"}});
  19104. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19105. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19106. }
  19107. #endif
  19108. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19109. TEST_F(OpenStreamTest, Brotli) {
  19110. Client cli("127.0.0.1", port_);
  19111. auto handle =
  19112. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19113. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19114. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19115. }
  19116. #endif
  19117. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19118. TEST_F(OpenStreamTest, Zstd) {
  19119. Client cli("127.0.0.1", port_);
  19120. auto handle = cli.open_stream("GET", "/compressible", {},
  19121. {{"Accept-Encoding", "zstd"}});
  19122. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19123. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19124. }
  19125. #endif
  19126. #ifdef CPPHTTPLIB_SSL_ENABLED
  19127. class SSLOpenStreamTest : public ::testing::Test {
  19128. protected:
  19129. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19130. void SetUp() override {
  19131. svr_.Get("/hello", [](const Request &, Response &res) {
  19132. res.set_content("Hello SSL World!", "text/plain");
  19133. });
  19134. svr_.Get("/chunked", [](const Request &, Response &res) {
  19135. res.set_chunked_content_provider("text/plain",
  19136. [](size_t offset, DataSink &sink) {
  19137. if (offset < 15) {
  19138. sink.write("chunk", 5);
  19139. return true;
  19140. }
  19141. sink.done();
  19142. return true;
  19143. });
  19144. });
  19145. svr_.Post("/echo", [](const Request &req, Response &res) {
  19146. res.set_content(req.body, req.get_header_value("Content-Type"));
  19147. });
  19148. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19149. std::string body = req.body;
  19150. res.set_chunked_content_provider(
  19151. "text/plain", [body](size_t offset, DataSink &sink) {
  19152. if (offset < body.size()) {
  19153. sink.write(body.data() + offset, body.size() - offset);
  19154. }
  19155. sink.done();
  19156. return true;
  19157. });
  19158. });
  19159. port_ = svr_.bind_to_any_port("127.0.0.1");
  19160. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19161. svr_.wait_until_ready();
  19162. }
  19163. void TearDown() override {
  19164. svr_.stop();
  19165. if (thread_.joinable()) thread_.join();
  19166. }
  19167. SSLServer svr_;
  19168. std::thread thread_;
  19169. int port_ = 0;
  19170. };
  19171. TEST_F(SSLOpenStreamTest, Basic) {
  19172. SSLClient cli("127.0.0.1", port_);
  19173. cli.enable_server_certificate_verification(false);
  19174. auto handle = cli.open_stream("GET", "/hello");
  19175. ASSERT_TRUE(handle.is_valid());
  19176. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19177. }
  19178. TEST_F(SSLOpenStreamTest, Chunked) {
  19179. SSLClient cli("127.0.0.1", port_);
  19180. cli.enable_server_certificate_verification(false);
  19181. auto handle = cli.open_stream("GET", "/chunked");
  19182. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19183. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19184. "Transfer-Encoding") == "chunked");
  19185. auto body = read_all(handle);
  19186. EXPECT_EQ("chunkchunkchunk", body);
  19187. }
  19188. TEST_F(SSLOpenStreamTest, Post) {
  19189. SSLClient cli("127.0.0.1", port_);
  19190. cli.enable_server_certificate_verification(false);
  19191. auto handle =
  19192. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19193. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19194. EXPECT_EQ(200, handle.response->status);
  19195. auto body = read_all(handle);
  19196. EXPECT_EQ("Hello SSL POST", body);
  19197. }
  19198. TEST_F(SSLOpenStreamTest, PostChunked) {
  19199. SSLClient cli("127.0.0.1", port_);
  19200. cli.enable_server_certificate_verification(false);
  19201. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19202. "Chunked SSL Data", "text/plain");
  19203. ASSERT_TRUE(handle.is_valid());
  19204. EXPECT_EQ(200, handle.response->status);
  19205. auto body = read_all(handle);
  19206. EXPECT_EQ("Chunked SSL Data", body);
  19207. }
  19208. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19209. // Content-Length is terminated by the server closing the connection. When the
  19210. // SSL peer sends a close_notify after the body, the client must treat it as a
  19211. // clean EOF and return a successful response rather than an error.
  19212. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19214. ASSERT_TRUE(svr.is_valid());
  19215. svr.set_keep_alive_max_count(1);
  19216. const std::string expected_body = "Hello from connection-close response!";
  19217. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19218. res.set_content_provider("text/plain",
  19219. [&](size_t offset, DataSink &sink) -> bool {
  19220. if (offset < expected_body.size()) {
  19221. sink.write(expected_body.data() + offset,
  19222. expected_body.size() - offset);
  19223. }
  19224. sink.done();
  19225. return true;
  19226. });
  19227. });
  19228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19229. auto se = detail::scope_exit([&] {
  19230. svr.stop();
  19231. listen_thread.join();
  19232. ASSERT_FALSE(svr.is_running());
  19233. });
  19234. svr.wait_until_ready();
  19235. SSLClient cli(HOST, PORT);
  19236. cli.enable_server_certificate_verification(false);
  19237. auto res = cli.Get("/no-content-length");
  19238. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19239. EXPECT_EQ(StatusCode::OK_200, res->status);
  19240. EXPECT_EQ(expected_body, res->body);
  19241. }
  19242. #endif // CPPHTTPLIB_SSL_ENABLED
  19243. //==============================================================================
  19244. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19245. // results for various scenarios.
  19246. //==============================================================================
  19247. TEST(ParityTest, GetVsOpenStream) {
  19248. Server svr;
  19249. const std::string path = "/parity";
  19250. const std::string content = "Parity test content: hello world";
  19251. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19252. res.set_content(content, "text/plain");
  19253. });
  19254. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19255. auto se = detail::scope_exit([&] {
  19256. svr.stop();
  19257. t.join();
  19258. ASSERT_FALSE(svr.is_running());
  19259. });
  19260. svr.wait_until_ready();
  19261. Client cli(HOST, PORT);
  19262. // Non-stream path
  19263. auto r1 = cli.Get(path);
  19264. ASSERT_TRUE(r1);
  19265. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19266. // Stream path
  19267. auto h = cli.open_stream("GET", path);
  19268. ASSERT_TRUE(h.is_valid());
  19269. EXPECT_EQ(r1->body, read_all(h));
  19270. }
  19271. // Helper to compress data with provided compressor type T
  19272. template <typename Compressor>
  19273. static std::string compress_payload_for_parity(const std::string &in) {
  19274. std::string out;
  19275. Compressor compressor;
  19276. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19277. [&](const char *data, size_t n) {
  19278. out.append(data, n);
  19279. return true;
  19280. });
  19281. EXPECT_TRUE(ok);
  19282. return out;
  19283. }
  19284. // Helper function for compression parity tests
  19285. template <typename Compressor>
  19286. static void test_compression_parity(const std::string &original,
  19287. const std::string &path,
  19288. const std::string &encoding) {
  19289. const std::string compressed =
  19290. compress_payload_for_parity<Compressor>(original);
  19291. Server svr;
  19292. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19293. res.set_content(compressed, "application/octet-stream");
  19294. res.set_header("Content-Encoding", encoding);
  19295. });
  19296. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19297. auto se = detail::scope_exit([&] {
  19298. svr.stop();
  19299. t.join();
  19300. ASSERT_FALSE(svr.is_running());
  19301. });
  19302. svr.wait_until_ready();
  19303. Client cli(HOST, PORT);
  19304. // Non-streaming
  19305. {
  19306. auto res = cli.Get(path);
  19307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19308. EXPECT_EQ(StatusCode::OK_200, res->status);
  19309. EXPECT_EQ(original, res->body);
  19310. }
  19311. // Streaming
  19312. {
  19313. auto h = cli.open_stream("GET", path);
  19314. ASSERT_TRUE(h.is_valid());
  19315. EXPECT_EQ(original, read_all(h));
  19316. }
  19317. }
  19318. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19319. TEST(ParityTest, Gzip) {
  19320. test_compression_parity<detail::gzip_compressor>(
  19321. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19322. }
  19323. #endif
  19324. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19325. TEST(ParityTest, Brotli) {
  19326. test_compression_parity<detail::brotli_compressor>(
  19327. "Hello, brotli parity test payload", "/parity-br", "br");
  19328. }
  19329. #endif
  19330. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19331. TEST(ParityTest, Zstd) {
  19332. test_compression_parity<detail::zstd_compressor>(
  19333. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19334. }
  19335. #endif
  19336. //==============================================================================
  19337. // New Stream API Tests
  19338. //==============================================================================
  19339. inline std::string read_body(httplib::stream::Result &result) {
  19340. std::string body;
  19341. while (result.next()) {
  19342. body.append(result.data(), result.size());
  19343. }
  19344. return body;
  19345. }
  19346. TEST(ClientConnectionTest, Basic) {
  19347. httplib::ClientConnection conn;
  19348. EXPECT_FALSE(conn.is_open());
  19349. conn.sock = 1;
  19350. EXPECT_TRUE(conn.is_open());
  19351. httplib::ClientConnection conn2(std::move(conn));
  19352. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19353. conn2.sock = INVALID_SOCKET;
  19354. }
  19355. // Unified test server for all stream::* tests
  19356. class StreamApiTest : public ::testing::Test {
  19357. protected:
  19358. void SetUp() override {
  19359. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19360. res.set_content("Hello World!", "text/plain");
  19361. });
  19362. svr_.Get("/echo-params",
  19363. [](const httplib::Request &req, httplib::Response &res) {
  19364. std::string r;
  19365. for (const auto &p : req.params) {
  19366. if (!r.empty()) r += "&";
  19367. r += p.first + "=" + p.second;
  19368. }
  19369. res.set_content(r, "text/plain");
  19370. });
  19371. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19372. res.set_content(req.body, req.get_header_value("Content-Type"));
  19373. });
  19374. svr_.Post("/echo-headers",
  19375. [](const httplib::Request &req, httplib::Response &res) {
  19376. std::string r;
  19377. for (const auto &h : req.headers)
  19378. r += h.first + ": " + h.second + "\n";
  19379. res.set_content(r, "text/plain");
  19380. });
  19381. svr_.Post("/echo-params",
  19382. [](const httplib::Request &req, httplib::Response &res) {
  19383. std::string r = "params:";
  19384. for (const auto &p : req.params)
  19385. r += p.first + "=" + p.second + ";";
  19386. res.set_content(r + " body:" + req.body, "text/plain");
  19387. });
  19388. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19389. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19390. });
  19391. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19392. res.set_content("PUT:" + req.body, "text/plain");
  19393. });
  19394. svr_.Patch("/echo",
  19395. [](const httplib::Request &req, httplib::Response &res) {
  19396. res.set_content("PATCH:" + req.body, "text/plain");
  19397. });
  19398. svr_.Delete(
  19399. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19400. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19401. "text/plain");
  19402. });
  19403. svr_.Get("/head-test",
  19404. [](const httplib::Request &, httplib::Response &res) {
  19405. res.set_content("body for HEAD", "text/plain");
  19406. });
  19407. svr_.Options("/options",
  19408. [](const httplib::Request &, httplib::Response &res) {
  19409. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19410. });
  19411. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19412. svr_.wait_until_ready();
  19413. }
  19414. void TearDown() override {
  19415. svr_.stop();
  19416. if (thread_.joinable()) thread_.join();
  19417. }
  19418. httplib::Server svr_;
  19419. std::thread thread_;
  19420. };
  19421. // stream::Get tests
  19422. TEST_F(StreamApiTest, GetBasic) {
  19423. httplib::Client cli(HOST, PORT);
  19424. auto result = httplib::stream::Get(cli, "/hello");
  19425. ASSERT_TRUE(result.is_valid());
  19426. EXPECT_EQ(200, result.status());
  19427. EXPECT_EQ("Hello World!", read_body(result));
  19428. }
  19429. TEST_F(StreamApiTest, GetWithParams) {
  19430. httplib::Client cli(HOST, PORT);
  19431. httplib::Params params{{"foo", "bar"}};
  19432. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19433. ASSERT_TRUE(result.is_valid());
  19434. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19435. }
  19436. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19437. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19438. httplib::Client cli(HOST, PORT);
  19439. cli.set_payload_max_length(0);
  19440. auto result = httplib::stream::Get(cli, "/hello");
  19441. ASSERT_TRUE(result.is_valid());
  19442. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19443. EXPECT_EQ("Hello World!", read_body(result));
  19444. }
  19445. #endif
  19446. TEST_F(StreamApiTest, GetConnectionError) {
  19447. httplib::Client cli(HOST, 9999);
  19448. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19449. }
  19450. TEST_F(StreamApiTest, Get404) {
  19451. httplib::Client cli(HOST, PORT);
  19452. auto result = httplib::stream::Get(cli, "/nonexistent");
  19453. EXPECT_TRUE(result.is_valid());
  19454. EXPECT_EQ(404, result.status());
  19455. }
  19456. // stream::Post tests
  19457. TEST_F(StreamApiTest, PostBasic) {
  19458. httplib::Client cli(HOST, PORT);
  19459. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19460. "application/json");
  19461. ASSERT_TRUE(result.is_valid());
  19462. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19463. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19464. }
  19465. TEST_F(StreamApiTest, PostWithHeaders) {
  19466. httplib::Client cli(HOST, PORT);
  19467. httplib::Headers headers{{"X-Custom", "value"}};
  19468. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19469. "text/plain");
  19470. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19471. }
  19472. TEST_F(StreamApiTest, PostWithParams) {
  19473. httplib::Client cli(HOST, PORT);
  19474. httplib::Params params{{"k", "v"}};
  19475. auto result =
  19476. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19477. auto body = read_body(result);
  19478. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19479. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19480. }
  19481. TEST_F(StreamApiTest, PostLarge) {
  19482. httplib::Client cli(HOST, PORT);
  19483. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19484. size_t total = 0;
  19485. while (result.next()) {
  19486. total += result.size();
  19487. }
  19488. EXPECT_EQ(100u * 1024u, total);
  19489. }
  19490. // stream::Put/Patch tests
  19491. TEST_F(StreamApiTest, PutAndPatch) {
  19492. httplib::Client cli(HOST, PORT);
  19493. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19494. EXPECT_EQ("PUT:test", read_body(put));
  19495. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19496. EXPECT_EQ("PATCH:test", read_body(patch));
  19497. }
  19498. // stream::Delete tests
  19499. TEST_F(StreamApiTest, Delete) {
  19500. httplib::Client cli(HOST, PORT);
  19501. auto del1 = httplib::stream::Delete(cli, "/resource");
  19502. EXPECT_EQ("Deleted", read_body(del1));
  19503. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19504. EXPECT_EQ("Deleted:data", read_body(del2));
  19505. }
  19506. // stream::Head/Options tests
  19507. TEST_F(StreamApiTest, HeadAndOptions) {
  19508. httplib::Client cli(HOST, PORT);
  19509. auto head = httplib::stream::Head(cli, "/head-test");
  19510. EXPECT_TRUE(head.is_valid());
  19511. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19512. auto opts = httplib::stream::Options(cli, "/options");
  19513. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19514. }
  19515. // SSL stream::* tests
  19516. #ifdef CPPHTTPLIB_SSL_ENABLED
  19517. class SSLStreamApiTest : public ::testing::Test {
  19518. protected:
  19519. void SetUp() override {
  19520. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19521. res.set_content("Hello SSL!", "text/plain");
  19522. });
  19523. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19524. res.set_content(req.body, "text/plain");
  19525. });
  19526. port_ = svr_.bind_to_any_port("127.0.0.1");
  19527. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19528. svr_.wait_until_ready();
  19529. }
  19530. void TearDown() override {
  19531. svr_.stop();
  19532. if (thread_.joinable()) thread_.join();
  19533. }
  19534. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19535. std::thread thread_;
  19536. int port_ = 0;
  19537. };
  19538. TEST_F(SSLStreamApiTest, GetAndPost) {
  19539. httplib::SSLClient cli("127.0.0.1", port_);
  19540. cli.enable_server_certificate_verification(false);
  19541. auto get = httplib::stream::Get(cli, "/hello");
  19542. EXPECT_EQ("Hello SSL!", read_body(get));
  19543. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19544. EXPECT_EQ("test", read_body(post));
  19545. }
  19546. #endif
  19547. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19548. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19549. // BodyReader
  19550. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19551. // Test that read timeout during streaming is detected
  19552. // Use a large content-length response where server delays mid-stream
  19553. Server svr;
  19554. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19555. // Send a large response with delay in the middle
  19556. res.set_content_provider(
  19557. 1000, // content_length
  19558. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19559. if (offset < 100) {
  19560. // Send first 100 bytes immediately
  19561. std::string data(100, 'A');
  19562. sink.write(data.c_str(), data.size());
  19563. return true;
  19564. }
  19565. // Then delay longer than client timeout
  19566. std::this_thread::sleep_for(std::chrono::seconds(3));
  19567. std::string data(900, 'B');
  19568. sink.write(data.c_str(), data.size());
  19569. return true;
  19570. });
  19571. });
  19572. auto port = 8091;
  19573. std::thread t([&]() { svr.listen("localhost", port); });
  19574. svr.wait_until_ready();
  19575. Client cli("localhost", port);
  19576. cli.set_read_timeout(1, 0); // 1 second timeout
  19577. auto handle = cli.open_stream("GET", "/slow-stream");
  19578. ASSERT_TRUE(handle.is_valid());
  19579. char buf[256];
  19580. ssize_t total = 0;
  19581. ssize_t n;
  19582. bool got_error = false;
  19583. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19584. total += n;
  19585. }
  19586. if (n < 0) {
  19587. got_error = true;
  19588. // Should be timeout or read error
  19589. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19590. handle.get_read_error() == Error::Read)
  19591. << "Actual error: " << to_string(handle.get_read_error());
  19592. }
  19593. // Either we got an error, or we got less data than expected
  19594. EXPECT_TRUE(got_error || total < 1000)
  19595. << "Expected timeout but got all " << total << " bytes";
  19596. svr.stop();
  19597. t.join();
  19598. }
  19599. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19600. // Test connection closed detection via BodyReader
  19601. Server svr;
  19602. std::atomic<bool> close_now{false};
  19603. svr.Get("/will-close", [&](const Request &, Response &res) {
  19604. res.set_content_provider(
  19605. 10000, // Large content_length that we won't fully send
  19606. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19607. if (offset < 100) {
  19608. std::string data(100, 'X');
  19609. sink.write(data.c_str(), data.size());
  19610. return true;
  19611. }
  19612. // Wait for signal then abort
  19613. while (!close_now) {
  19614. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19615. }
  19616. return false; // Abort - server will close connection
  19617. });
  19618. });
  19619. auto port = 8092;
  19620. std::thread t([&]() { svr.listen("localhost", port); });
  19621. svr.wait_until_ready();
  19622. Client cli("localhost", port);
  19623. auto handle = cli.open_stream("GET", "/will-close");
  19624. ASSERT_TRUE(handle.is_valid());
  19625. char buf[256];
  19626. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19627. EXPECT_GT(n, 0) << "First read should succeed";
  19628. // Signal server to close
  19629. close_now = true;
  19630. // Keep reading until error or EOF
  19631. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19632. // Keep reading
  19633. }
  19634. // Should get an error since content_length wasn't satisfied
  19635. if (n < 0) {
  19636. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19637. handle.get_read_error() == Error::Read)
  19638. << "Actual error: " << to_string(handle.get_read_error());
  19639. }
  19640. svr.stop();
  19641. t.join();
  19642. }
  19643. #ifdef CPPHTTPLIB_SSL_ENABLED
  19644. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19645. // Test that read timeout during SSL streaming is detected
  19646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19647. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19648. res.set_content_provider(
  19649. 1000, "text/plain",
  19650. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19651. if (offset < 100) {
  19652. std::string data(100, 'A');
  19653. sink.write(data.c_str(), data.size());
  19654. return true;
  19655. }
  19656. std::this_thread::sleep_for(std::chrono::seconds(3));
  19657. std::string data(900, 'B');
  19658. sink.write(data.c_str(), data.size());
  19659. return true;
  19660. });
  19661. });
  19662. auto port = 8093;
  19663. std::thread t([&]() { svr.listen("localhost", port); });
  19664. svr.wait_until_ready();
  19665. SSLClient cli("localhost", port);
  19666. cli.enable_server_certificate_verification(false);
  19667. cli.set_read_timeout(1, 0); // 1 second timeout
  19668. auto handle = cli.open_stream("GET", "/slow-stream");
  19669. ASSERT_TRUE(handle.is_valid());
  19670. char buf[256];
  19671. ssize_t total = 0;
  19672. ssize_t n;
  19673. bool got_error = false;
  19674. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19675. total += n;
  19676. }
  19677. if (n < 0) {
  19678. got_error = true;
  19679. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19680. handle.get_read_error() == Error::Read)
  19681. << "Actual error: " << to_string(handle.get_read_error());
  19682. }
  19683. EXPECT_TRUE(got_error || total < 1000)
  19684. << "Expected timeout but got all " << total << " bytes";
  19685. svr.stop();
  19686. t.join();
  19687. }
  19688. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19689. // Test SSL connection closed detection
  19690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19691. std::atomic<bool> close_now{false};
  19692. svr.Get("/will-close", [&](const Request &, Response &res) {
  19693. res.set_content_provider(
  19694. 10000, "text/plain",
  19695. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19696. if (offset < 100) {
  19697. std::string data(100, 'X');
  19698. sink.write(data.c_str(), data.size());
  19699. return true;
  19700. }
  19701. while (!close_now) {
  19702. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19703. }
  19704. return false;
  19705. });
  19706. });
  19707. auto port = 8094;
  19708. std::thread t([&]() { svr.listen("localhost", port); });
  19709. svr.wait_until_ready();
  19710. SSLClient cli("localhost", port);
  19711. cli.enable_server_certificate_verification(false);
  19712. auto handle = cli.open_stream("GET", "/will-close");
  19713. ASSERT_TRUE(handle.is_valid());
  19714. char buf[256];
  19715. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19716. EXPECT_GT(n, 0);
  19717. // Signal server to close
  19718. close_now = true;
  19719. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19720. // Keep reading
  19721. }
  19722. if (n < 0) {
  19723. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19724. handle.get_read_error() == Error::Read)
  19725. << "Actual error: " << to_string(handle.get_read_error());
  19726. }
  19727. svr.stop();
  19728. t.join();
  19729. }
  19730. #endif
  19731. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19732. using namespace httplib;
  19733. // Create a test file
  19734. const char *fname = "etag_testfile.txt";
  19735. const char *content = "etag-content";
  19736. {
  19737. std::ofstream ofs(fname);
  19738. ofs << content;
  19739. ASSERT_TRUE(ofs.good());
  19740. }
  19741. Server svr;
  19742. svr.set_mount_point("/static", ".");
  19743. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19744. svr.wait_until_ready();
  19745. Client cli(HOST, PORT);
  19746. // First request: should get 200 with ETag header
  19747. auto res1 = cli.Get("/static/etag_testfile.txt");
  19748. ASSERT_TRUE(res1);
  19749. ASSERT_EQ(200, res1->status);
  19750. ASSERT_TRUE(res1->has_header("ETag"));
  19751. std::string etag = res1->get_header_value("ETag");
  19752. EXPECT_FALSE(etag.empty());
  19753. // Verify ETag format: W/"hex-hex"
  19754. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19755. EXPECT_EQ('W', etag[0]);
  19756. EXPECT_EQ('/', etag[1]);
  19757. EXPECT_EQ('"', etag[2]);
  19758. EXPECT_EQ('"', etag.back());
  19759. // Exact match: expect 304 Not Modified
  19760. Headers h2 = {{"If-None-Match", etag}};
  19761. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19762. ASSERT_TRUE(res2);
  19763. EXPECT_EQ(304, res2->status);
  19764. // Wildcard match: expect 304 Not Modified
  19765. Headers h3 = {{"If-None-Match", "*"}};
  19766. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19767. ASSERT_TRUE(res3);
  19768. EXPECT_EQ(304, res3->status);
  19769. // Non-matching ETag: expect 200
  19770. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19771. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19772. ASSERT_TRUE(res4);
  19773. EXPECT_EQ(200, res4->status);
  19774. // Multiple ETags with one matching: expect 304
  19775. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19776. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19777. ASSERT_TRUE(res5);
  19778. EXPECT_EQ(304, res5->status);
  19779. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19780. // that equivalent to the single comma-separated list above, so the match on
  19781. // the second line must still be found.
  19782. Headers h6;
  19783. h6.emplace("If-None-Match", "W/\"other\"");
  19784. h6.emplace("If-None-Match", etag);
  19785. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19786. ASSERT_TRUE(res6);
  19787. EXPECT_EQ(304, res6->status);
  19788. svr.stop();
  19789. t.join();
  19790. std::remove(fname);
  19791. }
  19792. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19793. using namespace httplib;
  19794. Server svr;
  19795. svr.set_mount_point("/static", ".");
  19796. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19797. svr.wait_until_ready();
  19798. Client cli(HOST, PORT);
  19799. // Send If-None-Match: * to a non-existent file
  19800. Headers h = {{"If-None-Match", "*"}};
  19801. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19803. EXPECT_EQ(404, res->status);
  19804. svr.stop();
  19805. t.join();
  19806. }
  19807. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19808. using namespace httplib;
  19809. // Create a test file
  19810. const char *fname = "etag_boundary_testfile.txt";
  19811. const char *content = "boundary-test";
  19812. {
  19813. std::ofstream ofs(fname);
  19814. ofs << content;
  19815. ASSERT_TRUE(ofs.good());
  19816. }
  19817. Server svr;
  19818. svr.set_mount_point("/static", ".");
  19819. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19820. svr.wait_until_ready();
  19821. Client cli(HOST, PORT);
  19822. // Get the actual ETag
  19823. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19824. ASSERT_TRUE(res1);
  19825. ASSERT_EQ(200, res1->status);
  19826. ASSERT_TRUE(res1->has_header("ETag"));
  19827. std::string etag = res1->get_header_value("ETag");
  19828. // Test 1: Very long ETag value (longer than actual ETag)
  19829. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19830. Headers h1 = {{"If-None-Match", "W/"
  19831. "\"very-long-etag-value-that-is-much-longer-"
  19832. "than-the-actual-etag-value\""}};
  19833. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19834. ASSERT_TRUE(res2);
  19835. EXPECT_EQ(200, res2->status); // Should not match
  19836. // Test 2: Long string followed by wildcard
  19837. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19838. // string)
  19839. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19840. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19841. ASSERT_TRUE(res3);
  19842. EXPECT_EQ(304, res3->status); // Should match on "*"
  19843. // Test 3: Wildcard followed by long string
  19844. // Should match on "*" immediately and return 304
  19845. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19846. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19847. ASSERT_TRUE(res4);
  19848. EXPECT_EQ(304, res4->status); // Should match on "*"
  19849. // Test 4: Multiple long non-matching values
  19850. // Should NOT match and return 200 (test that all comparisons are safe)
  19851. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19852. "W/\"second-long-non-matching-value\", "
  19853. "W/\"third-long-non-matching-value\""}};
  19854. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19855. ASSERT_TRUE(res5);
  19856. EXPECT_EQ(200, res5->status); // Should not match
  19857. // Test 5: Single character that is not "*" (edge case)
  19858. Headers h5 = {{"If-None-Match", "X"}};
  19859. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19860. ASSERT_TRUE(res6);
  19861. EXPECT_EQ(200, res6->status); // Should not match
  19862. svr.stop();
  19863. t.join();
  19864. std::remove(fname);
  19865. }
  19866. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19867. using namespace httplib;
  19868. // Create a test file
  19869. const char *fname = "ims_testfile.txt";
  19870. const char *content = "if-modified-since-test";
  19871. {
  19872. std::ofstream ofs(fname);
  19873. ofs << content;
  19874. ASSERT_TRUE(ofs.good());
  19875. }
  19876. Server svr;
  19877. svr.set_mount_point("/static", ".");
  19878. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19879. svr.wait_until_ready();
  19880. Client cli(HOST, PORT);
  19881. // First request: should get 200 with Last-Modified header
  19882. auto res1 = cli.Get("/static/ims_testfile.txt");
  19883. ASSERT_TRUE(res1);
  19884. ASSERT_EQ(200, res1->status);
  19885. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19886. std::string last_modified = res1->get_header_value("Last-Modified");
  19887. EXPECT_FALSE(last_modified.empty());
  19888. // If-Modified-Since with same time: expect 304
  19889. Headers h2 = {{"If-Modified-Since", last_modified}};
  19890. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19891. ASSERT_TRUE(res2);
  19892. EXPECT_EQ(304, res2->status);
  19893. // If-Modified-Since with future time: expect 304
  19894. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19895. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19896. ASSERT_TRUE(res3);
  19897. EXPECT_EQ(304, res3->status);
  19898. // If-Modified-Since with past time: expect 200
  19899. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19900. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19901. ASSERT_TRUE(res4);
  19902. EXPECT_EQ(200, res4->status);
  19903. // If-None-Match takes precedence over If-Modified-Since
  19904. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19905. ASSERT_TRUE(res1->has_header("ETag"));
  19906. std::string etag = res1->get_header_value("ETag");
  19907. Headers h5 = {{"If-None-Match", etag},
  19908. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19909. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19910. ASSERT_TRUE(res5);
  19911. EXPECT_EQ(304, res5->status);
  19912. svr.stop();
  19913. t.join();
  19914. std::remove(fname);
  19915. }
  19916. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19917. using namespace httplib;
  19918. Server svr;
  19919. // Endpoint that returns compressible content
  19920. svr.Get("/compressible", [](const Request &, Response &res) {
  19921. // Return a large enough body to trigger compression
  19922. std::string body(1000, 'a');
  19923. res.set_content(body, "text/plain");
  19924. });
  19925. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19926. svr.wait_until_ready();
  19927. Client cli(HOST, PORT);
  19928. // Request with gzip support: should get Vary header when compressed
  19929. cli.set_compress(true);
  19930. auto res1 = cli.Get("/compressible");
  19931. ASSERT_TRUE(res1);
  19932. EXPECT_EQ(200, res1->status);
  19933. // If Content-Encoding is set, Vary should also be set
  19934. if (res1->has_header("Content-Encoding")) {
  19935. EXPECT_TRUE(res1->has_header("Vary"));
  19936. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19937. }
  19938. // Request without Accept-Encoding header: should not have compression
  19939. Headers h_no_compress;
  19940. auto res2 = cli.Get("/compressible", h_no_compress);
  19941. ASSERT_TRUE(res2);
  19942. EXPECT_EQ(200, res2->status);
  19943. // Verify Vary header is present when compression is applied
  19944. // (the exact behavior depends on server configuration)
  19945. svr.stop();
  19946. t.join();
  19947. }
  19948. TEST(ETagTest, IfRangeWithETag) {
  19949. using namespace httplib;
  19950. // Create a test file with known content
  19951. const char *fname = "if_range_testfile.txt";
  19952. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19953. {
  19954. std::ofstream ofs(fname);
  19955. ofs << content;
  19956. ASSERT_TRUE(ofs.good());
  19957. }
  19958. Server svr;
  19959. svr.set_mount_point("/static", ".");
  19960. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19961. svr.wait_until_ready();
  19962. Client cli(HOST, PORT);
  19963. // First request: get ETag
  19964. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19965. ASSERT_TRUE(res1);
  19966. ASSERT_EQ(200, res1->status);
  19967. ASSERT_TRUE(res1->has_header("ETag"));
  19968. std::string etag = res1->get_header_value("ETag");
  19969. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19970. // Since our server generates weak ETags (W/"..."), If-Range with our
  19971. // ETag should NOT result in partial content - it should return full content.
  19972. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19973. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19974. ASSERT_TRUE(res2);
  19975. // Weak ETag in If-Range -> full content (200), not partial (206)
  19976. EXPECT_EQ(200, res2->status);
  19977. EXPECT_EQ(content, res2->body);
  19978. EXPECT_FALSE(res2->has_header("Content-Range"));
  19979. // Range request with non-matching If-Range (ETag): should get 200 (full
  19980. // content)
  19981. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19982. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19983. ASSERT_TRUE(res3);
  19984. EXPECT_EQ(200, res3->status);
  19985. EXPECT_EQ(content, res3->body);
  19986. EXPECT_FALSE(res3->has_header("Content-Range"));
  19987. // Range request with strong ETag (hypothetical - our server doesn't generate
  19988. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19989. // should return full content)
  19990. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19991. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19992. ASSERT_TRUE(res4);
  19993. EXPECT_EQ(200, res4->status);
  19994. EXPECT_EQ(content, res4->body);
  19995. EXPECT_FALSE(res4->has_header("Content-Range"));
  19996. svr.stop();
  19997. t.join();
  19998. std::remove(fname);
  19999. }
  20000. TEST(ETagTest, IfRangeWithDate) {
  20001. using namespace httplib;
  20002. // Create a test file
  20003. const char *fname = "if_range_date_testfile.txt";
  20004. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20005. {
  20006. std::ofstream ofs(fname);
  20007. ofs << content;
  20008. ASSERT_TRUE(ofs.good());
  20009. }
  20010. Server svr;
  20011. svr.set_mount_point("/static", ".");
  20012. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20013. svr.wait_until_ready();
  20014. Client cli(HOST, PORT);
  20015. // First request: get Last-Modified
  20016. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20017. ASSERT_TRUE(res1);
  20018. ASSERT_EQ(200, res1->status);
  20019. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20020. std::string last_modified = res1->get_header_value("Last-Modified");
  20021. // Range request with matching If-Range (date): should get 206
  20022. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20023. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20024. ASSERT_TRUE(res2);
  20025. EXPECT_EQ(206, res2->status);
  20026. EXPECT_EQ("FGHIJ", res2->body);
  20027. // Range request with old If-Range date: should get 200 (full content)
  20028. Headers h3 = {{"Range", "bytes=5-9"},
  20029. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20030. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20031. ASSERT_TRUE(res3);
  20032. EXPECT_EQ(200, res3->status);
  20033. EXPECT_EQ(content, res3->body);
  20034. // Range request with future If-Range date: should get 206
  20035. Headers h4 = {{"Range", "bytes=0-4"},
  20036. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20037. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20038. ASSERT_TRUE(res4);
  20039. EXPECT_EQ(206, res4->status);
  20040. EXPECT_EQ("ABCDE", res4->body);
  20041. svr.stop();
  20042. t.join();
  20043. std::remove(fname);
  20044. }
  20045. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20046. using namespace httplib;
  20047. const char *fname = "etag_malformed.txt";
  20048. const char *content = "malformed-etag";
  20049. {
  20050. std::ofstream ofs(fname);
  20051. ofs << content;
  20052. ASSERT_TRUE(ofs.good());
  20053. }
  20054. Server svr;
  20055. svr.set_mount_point("/static", ".");
  20056. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20057. svr.wait_until_ready();
  20058. Client cli(HOST, PORT);
  20059. // baseline: should get 200 and an ETag
  20060. auto res1 = cli.Get("/static/etag_malformed.txt");
  20061. ASSERT_TRUE(res1);
  20062. ASSERT_EQ(200, res1->status);
  20063. ASSERT_TRUE(res1->has_header("ETag"));
  20064. // Malformed ETag value (missing quotes) should be treated as non-matching
  20065. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20066. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20067. ASSERT_TRUE(res_bad);
  20068. EXPECT_EQ(200, res_bad->status);
  20069. // Whitespace-only header value should be considered invalid / non-matching
  20070. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20071. "Host: localhost\r\n"
  20072. "If-None-Match: \r\n"
  20073. "Connection: close\r\n"
  20074. "\r\n";
  20075. std::string out;
  20076. ASSERT_TRUE(send_request(5, raw_req, &out));
  20077. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20078. svr.stop();
  20079. t.join();
  20080. std::remove(fname);
  20081. }
  20082. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20083. using namespace httplib;
  20084. const char *fname = "ims_invalid_format.txt";
  20085. const char *content = "ims-bad-format";
  20086. {
  20087. std::ofstream ofs(fname);
  20088. ofs << content;
  20089. ASSERT_TRUE(ofs.good());
  20090. }
  20091. Server svr;
  20092. svr.set_mount_point("/static", ".");
  20093. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20094. svr.wait_until_ready();
  20095. Client cli(HOST, PORT);
  20096. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20097. ASSERT_TRUE(res1);
  20098. ASSERT_EQ(200, res1->status);
  20099. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20100. // If-Modified-Since with invalid format should not result in 304
  20101. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20102. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20103. ASSERT_TRUE(res_bad);
  20104. EXPECT_EQ(200, res_bad->status);
  20105. // If-Range with invalid date format should be treated as mismatch -> full
  20106. // content (200)
  20107. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20108. {"If-Range", "invalid-date"}};
  20109. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20110. ASSERT_TRUE(res_ifrange);
  20111. EXPECT_EQ(200, res_ifrange->status);
  20112. svr.stop();
  20113. t.join();
  20114. std::remove(fname);
  20115. }
  20116. TEST(ETagTest, IfRangeWithMalformedETag) {
  20117. using namespace httplib;
  20118. const char *fname = "ifrange_malformed.txt";
  20119. const std::string content = "0123456789";
  20120. {
  20121. std::ofstream ofs(fname);
  20122. ofs << content;
  20123. ASSERT_TRUE(ofs.good());
  20124. }
  20125. Server svr;
  20126. svr.set_mount_point("/static", ".");
  20127. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20128. svr.wait_until_ready();
  20129. Client cli(HOST, PORT);
  20130. // First request: get ETag
  20131. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20132. ASSERT_TRUE(res1);
  20133. ASSERT_EQ(200, res1->status);
  20134. ASSERT_TRUE(res1->has_header("ETag"));
  20135. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20136. // full content (200)
  20137. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20138. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20139. ASSERT_TRUE(res2);
  20140. EXPECT_EQ(200, res2->status);
  20141. EXPECT_EQ(content, res2->body);
  20142. svr.stop();
  20143. t.join();
  20144. std::remove(fname);
  20145. }
  20146. TEST(ETagTest, ExtremeLargeDateValues) {
  20147. using namespace httplib;
  20148. const char *fname = "ims_extreme_date.txt";
  20149. const char *content = "ims-extreme-date";
  20150. {
  20151. std::ofstream ofs(fname);
  20152. ofs << content;
  20153. ASSERT_TRUE(ofs.good());
  20154. }
  20155. Server svr;
  20156. svr.set_mount_point("/static", ".");
  20157. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20158. svr.wait_until_ready();
  20159. Client cli(HOST, PORT);
  20160. auto res1 = cli.Get(std::string("/static/") + fname);
  20161. ASSERT_TRUE(res1);
  20162. ASSERT_EQ(200, res1->status);
  20163. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20164. // Extremely large year that may overflow date parsing routines.
  20165. Headers h_large_date = {
  20166. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20167. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20168. ASSERT_TRUE(res_bad);
  20169. // Expect server to treat this as invalid/mismatch and return full content
  20170. EXPECT_EQ(200, res_bad->status);
  20171. // If-Range with extremely large date should be treated as mismatch -> full
  20172. // content (200)
  20173. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20174. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20175. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20176. ASSERT_TRUE(res_ifrange);
  20177. EXPECT_EQ(200, res_ifrange->status);
  20178. svr.stop();
  20179. t.join();
  20180. std::remove(fname);
  20181. }
  20182. TEST(ETagTest, NegativeFileModificationTime) {
  20183. using namespace httplib;
  20184. const char *fname = "ims_negative_mtime.txt";
  20185. const std::string content = "negative-mtime";
  20186. {
  20187. std::ofstream ofs(fname);
  20188. ofs << content;
  20189. ASSERT_TRUE(ofs.good());
  20190. }
  20191. // Try to set file mtime to a negative value. This may fail on some
  20192. // platforms/filesystems; if it fails, the test will still verify server
  20193. // behaves safely by performing a regular conditional request.
  20194. #if defined(__APPLE__) || defined(__linux__)
  20195. bool set_negative = false;
  20196. do {
  20197. struct timeval times[2];
  20198. // access time: now
  20199. times[0].tv_sec = time(nullptr);
  20200. times[0].tv_usec = 0;
  20201. // modification time: negative (e.g., -1)
  20202. times[1].tv_sec = -1;
  20203. times[1].tv_usec = 0;
  20204. if (utimes(fname, times) == 0) { set_negative = true; }
  20205. } while (0);
  20206. #else
  20207. bool set_negative = false;
  20208. #endif
  20209. Server svr;
  20210. svr.set_mount_point("/static", ".");
  20211. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20212. svr.wait_until_ready();
  20213. Client cli(HOST, PORT);
  20214. auto res1 = cli.Get(std::string("/static/") + fname);
  20215. ASSERT_TRUE(res1);
  20216. ASSERT_EQ(200, res1->status);
  20217. bool has_last_modified = res1->has_header("Last-Modified");
  20218. std::string last_modified;
  20219. if (has_last_modified) {
  20220. last_modified = res1->get_header_value("Last-Modified");
  20221. }
  20222. if (set_negative) {
  20223. // If we successfully set a negative mtime, ensure server returns a
  20224. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20225. // with an old date and ensure server handles it without crash.
  20226. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20227. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20228. ASSERT_TRUE(res2);
  20229. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20230. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20231. } else {
  20232. // Could not set negative mtime on this platform; fall back to verifying
  20233. // that normal invalid/malformed dates are treated safely (non-304).
  20234. Headers h_bad_date = {
  20235. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20236. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20237. ASSERT_TRUE(res_bad);
  20238. EXPECT_EQ(200, res_bad->status);
  20239. }
  20240. svr.stop();
  20241. t.join();
  20242. std::remove(fname);
  20243. }
  20244. //==============================================================================
  20245. // Integration Tests with Server
  20246. //==============================================================================
  20247. class SSEIntegrationTest : public ::testing::Test {
  20248. protected:
  20249. void SetUp() override {
  20250. stop_server_.store(false);
  20251. events_.clear();
  20252. server_ = httplib::detail::make_unique<Server>();
  20253. setup_server();
  20254. start_server();
  20255. }
  20256. void TearDown() override {
  20257. stop_server_.store(true);
  20258. event_cv_.notify_all();
  20259. server_->stop();
  20260. if (server_thread_.joinable()) { server_thread_.join(); }
  20261. }
  20262. void setup_server() {
  20263. // Simple SSE endpoint
  20264. server_->Get("/events", [this](const Request &req, Response &res) {
  20265. auto last_id = req.get_header_value("Last-Event-ID");
  20266. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20267. res.set_chunked_content_provider(
  20268. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20269. std::unique_lock<std::mutex> lock(event_mutex_);
  20270. if (event_cv_.wait_for(
  20271. lock, std::chrono::milliseconds(200), [this] {
  20272. return !events_.empty() || stop_server_.load();
  20273. })) {
  20274. if (stop_server_.load()) { return false; }
  20275. if (!events_.empty()) {
  20276. std::string event = events_.front();
  20277. events_.erase(events_.begin());
  20278. sink.write(event.data(), event.size());
  20279. return true;
  20280. }
  20281. }
  20282. return !stop_server_.load();
  20283. });
  20284. });
  20285. // Endpoint that returns error
  20286. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20287. res.status = 500;
  20288. res.set_content("Internal Server Error", "text/plain");
  20289. });
  20290. // Endpoint for custom event types
  20291. server_->Get("/custom-events", [](const Request &, Response &res) {
  20292. res.set_chunked_content_provider(
  20293. "text/event-stream", [](size_t offset, DataSink &sink) {
  20294. if (offset == 0) {
  20295. std::string event = "event: update\ndata: updated\n\n"
  20296. "event: delete\ndata: deleted\n\n";
  20297. sink.write(event.data(), event.size());
  20298. }
  20299. return false; // End stream after sending
  20300. });
  20301. });
  20302. }
  20303. void start_server() {
  20304. port_ = server_->bind_to_any_port(HOST);
  20305. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20306. // Wait for server to start
  20307. while (!server_->is_running()) {
  20308. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20309. }
  20310. }
  20311. int get_port() const { return port_; }
  20312. void send_event(const std::string &event) {
  20313. std::lock_guard<std::mutex> lock(event_mutex_);
  20314. events_.push_back(event);
  20315. event_cv_.notify_all();
  20316. }
  20317. std::unique_ptr<Server> server_;
  20318. std::thread server_thread_;
  20319. std::mutex event_mutex_;
  20320. std::condition_variable event_cv_;
  20321. std::vector<std::string> events_;
  20322. std::atomic<bool> stop_server_{false};
  20323. std::string last_received_event_id_;
  20324. int port_ = 0;
  20325. };
  20326. //==============================================================================
  20327. // SSE Parsing Tests
  20328. //==============================================================================
  20329. class SSEParsingTest : public SSEIntegrationTest {
  20330. protected:
  20331. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20332. // A trailing sentinel event tells when the whole stream has been parsed.
  20333. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20334. auto body = stream + "event: end\ndata: end\n\n";
  20335. server_->Get("/parse", [body](const Request &, Response &res) {
  20336. res.set_content(body, "text/event-stream");
  20337. });
  20338. return collect("/parse");
  20339. }
  20340. // Runs SSEClient against path until an "end" event arrives and returns the
  20341. // messages dispatched before it
  20342. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20343. Client client(HOST, get_port());
  20344. sse::SSEClient sse(client, path);
  20345. std::mutex mutex;
  20346. std::condition_variable cv;
  20347. std::vector<sse::SSEMessage> messages;
  20348. auto done = false;
  20349. sse.on_message([&](const sse::SSEMessage &msg) {
  20350. std::lock_guard<std::mutex> lock(mutex);
  20351. // Ignore a replay from a reconnect that races with stop()
  20352. if (!done) { messages.push_back(msg); }
  20353. });
  20354. sse.on_event("end", [&](const sse::SSEMessage &) {
  20355. std::lock_guard<std::mutex> lock(mutex);
  20356. done = true;
  20357. cv.notify_all();
  20358. });
  20359. sse.set_reconnect_interval(100);
  20360. sse.start_async();
  20361. {
  20362. std::unique_lock<std::mutex> lock(mutex);
  20363. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20364. }
  20365. sse.stop();
  20366. EXPECT_TRUE(done);
  20367. return messages;
  20368. }
  20369. };
  20370. TEST_F(SSEParsingTest, SingleLineData) {
  20371. auto msgs = parse("data: hello\n\n");
  20372. ASSERT_EQ(msgs.size(), 1u);
  20373. EXPECT_EQ(msgs[0].data, "hello");
  20374. EXPECT_EQ(msgs[0].event, "message");
  20375. }
  20376. TEST_F(SSEParsingTest, MultiLineData) {
  20377. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20378. ASSERT_EQ(msgs.size(), 1u);
  20379. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20380. }
  20381. TEST_F(SSEParsingTest, CustomEventType) {
  20382. auto msgs = parse("event: update\ndata: payload\n\n");
  20383. ASSERT_EQ(msgs.size(), 1u);
  20384. EXPECT_EQ(msgs[0].event, "update");
  20385. EXPECT_EQ(msgs[0].data, "payload");
  20386. }
  20387. TEST_F(SSEParsingTest, EventIdHandling) {
  20388. auto msgs = parse("id: 12345\ndata: test\n\n");
  20389. ASSERT_EQ(msgs.size(), 1u);
  20390. EXPECT_EQ(msgs[0].id, "12345");
  20391. }
  20392. TEST_F(SSEParsingTest, EmptyEventId) {
  20393. auto msgs = parse("id:\ndata: test\n\n");
  20394. ASSERT_EQ(msgs.size(), 1u);
  20395. EXPECT_EQ(msgs[0].id, "");
  20396. }
  20397. TEST_F(SSEParsingTest, CommentsIgnored) {
  20398. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20399. ASSERT_EQ(msgs.size(), 1u);
  20400. EXPECT_EQ(msgs[0].data, "hello");
  20401. EXPECT_EQ(msgs[0].event, "message");
  20402. }
  20403. TEST_F(SSEParsingTest, ColonInValue) {
  20404. auto msgs = parse("data: hello:world:test\n\n");
  20405. ASSERT_EQ(msgs.size(), 1u);
  20406. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20407. }
  20408. TEST_F(SSEParsingTest, FieldNameOnly) {
  20409. // A line without a colon is a field name with an empty value
  20410. auto msgs = parse("data\n\n");
  20411. ASSERT_EQ(msgs.size(), 1u);
  20412. EXPECT_EQ(msgs[0].data, "");
  20413. }
  20414. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20415. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20416. ASSERT_EQ(msgs.size(), 1u);
  20417. EXPECT_EQ(msgs[0].event, "update");
  20418. EXPECT_EQ(msgs[0].data, "hello");
  20419. }
  20420. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20421. auto msgs = parse("data\r\n\r\n");
  20422. ASSERT_EQ(msgs.size(), 1u);
  20423. EXPECT_EQ(msgs[0].data, "");
  20424. }
  20425. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20426. auto msgs = parse("event: update\rdata: hello\r\r");
  20427. ASSERT_EQ(msgs.size(), 1u);
  20428. EXPECT_EQ(msgs[0].event, "update");
  20429. EXPECT_EQ(msgs[0].data, "hello");
  20430. }
  20431. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20432. // Chunk boundaries fall inside every \r\n and right before the first one
  20433. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20434. "\n\r", "\nevent: end\ndata: end\n\n"};
  20435. server_->Get("/split", [chunks](const Request &, Response &res) {
  20436. auto i = std::make_shared<size_t>(0);
  20437. res.set_chunked_content_provider(
  20438. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20439. if (*i == chunks.size()) {
  20440. sink.done();
  20441. } else {
  20442. sink.write(chunks[*i].data(), chunks[*i].size());
  20443. (*i)++;
  20444. }
  20445. return true;
  20446. });
  20447. });
  20448. auto msgs = collect("/split");
  20449. ASSERT_EQ(msgs.size(), 1u);
  20450. EXPECT_EQ(msgs[0].event, "update");
  20451. EXPECT_EQ(msgs[0].data, "hello");
  20452. }
  20453. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20454. // Only a BOM at the start of the stream is ignored
  20455. auto msgs = parse("\xEF\xBB\xBF"
  20456. "data: first\n\n"
  20457. "\xEF\xBB\xBF"
  20458. "data: second\n\n");
  20459. ASSERT_EQ(msgs.size(), 1u);
  20460. EXPECT_EQ(msgs[0].data, "first");
  20461. }
  20462. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20463. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20464. ASSERT_EQ(msgs.size(), 1u);
  20465. EXPECT_EQ(msgs[0].data, "hello");
  20466. EXPECT_EQ(msgs[0].event, "message");
  20467. }
  20468. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20469. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20470. ASSERT_EQ(msgs.size(), 2u);
  20471. EXPECT_EQ(msgs[0].data, "hello");
  20472. EXPECT_EQ(msgs[1].data, "hello");
  20473. }
  20474. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20475. // An event without data is not dispatched, and its type must not leak
  20476. // into the next event
  20477. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20478. ASSERT_EQ(msgs.size(), 1u);
  20479. EXPECT_EQ(msgs[0].event, "message");
  20480. EXPECT_EQ(msgs[0].data, "hello");
  20481. }
  20482. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20483. // The first connection sends only an id; the second echoes back the
  20484. // Last-Event-ID it was reconnected with
  20485. std::atomic<int> connection_count{0};
  20486. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20487. if (connection_count++ == 0) {
  20488. res.set_content("id: 42\n\n", "text/event-stream");
  20489. } else {
  20490. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20491. "\n\nevent: end\ndata: end\n\n",
  20492. "text/event-stream");
  20493. }
  20494. });
  20495. auto msgs = collect("/id-only");
  20496. ASSERT_EQ(msgs.size(), 1u);
  20497. EXPECT_EQ(msgs[0].data, "42");
  20498. }
  20499. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20500. // The first connection sets an id and then clears it with an empty one; the
  20501. // second reports whether it was reconnected with a Last-Event-ID
  20502. std::atomic<int> connection_count{0};
  20503. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20504. if (connection_count++ == 0) {
  20505. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20506. "text/event-stream");
  20507. } else {
  20508. res.set_content(
  20509. std::string("data: ") +
  20510. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20511. "\n\nevent: end\ndata: end\n\n",
  20512. "text/event-stream");
  20513. }
  20514. });
  20515. auto msgs = collect("/id-clear");
  20516. ASSERT_EQ(msgs.size(), 3u);
  20517. EXPECT_EQ(msgs[0].id, "1");
  20518. EXPECT_EQ(msgs[1].id, "");
  20519. EXPECT_EQ(msgs[2].data, "not sent");
  20520. }
  20521. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20522. // The first connection sets an id and then sends ids that cannot be carried
  20523. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20524. // with
  20525. std::atomic<int> connection_count{0};
  20526. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20527. if (connection_count++ == 0) {
  20528. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20529. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20530. "text/event-stream");
  20531. } else {
  20532. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20533. "\n\nevent: end\ndata: end\n\n",
  20534. "text/event-stream");
  20535. }
  20536. });
  20537. auto msgs = collect("/id-unsendable");
  20538. ASSERT_EQ(msgs.size(), 1u);
  20539. EXPECT_EQ(msgs[0].data, "42");
  20540. }
  20541. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20542. auto msgs = parse("event: notification\nid: evt-42\n"
  20543. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20544. ASSERT_EQ(msgs.size(), 1u);
  20545. EXPECT_EQ(msgs[0].event, "notification");
  20546. EXPECT_EQ(msgs[0].id, "evt-42");
  20547. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20548. }
  20549. TEST(SSEMessageTest, Clear) {
  20550. sse::SSEMessage msg;
  20551. msg.event = "custom";
  20552. msg.data = "some data";
  20553. msg.id = "123";
  20554. msg.clear();
  20555. EXPECT_EQ(msg.event, "message");
  20556. EXPECT_EQ(msg.data, "");
  20557. EXPECT_EQ(msg.id, "");
  20558. }
  20559. //==============================================================================
  20560. // SSE Integration Tests
  20561. //==============================================================================
  20562. // Test: Successful connection and on_open callback
  20563. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20564. // Add a simple endpoint that sends one event and closes
  20565. server_->Get("/simple-event", [](const Request &, Response &res) {
  20566. res.set_chunked_content_provider(
  20567. "text/event-stream", [](size_t offset, DataSink &sink) {
  20568. if (offset == 0) {
  20569. std::string event = "data: hello\n\n";
  20570. sink.write(event.data(), event.size());
  20571. }
  20572. return false; // Close stream after sending
  20573. });
  20574. });
  20575. Client client("localhost", get_port());
  20576. sse::SSEClient sse(client, "/simple-event");
  20577. std::atomic<bool> open_called{false};
  20578. std::atomic<bool> message_received{false};
  20579. sse.on_open([&open_called]() { open_called.store(true); });
  20580. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20581. if (msg.data == "hello") { message_received.store(true); }
  20582. });
  20583. sse.set_reconnect_interval(100);
  20584. sse.set_max_reconnect_attempts(1);
  20585. // Start async
  20586. sse.start_async();
  20587. // Wait for message to be processed
  20588. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20589. sse.stop();
  20590. EXPECT_TRUE(open_called.load());
  20591. EXPECT_TRUE(message_received.load());
  20592. }
  20593. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20594. // A data line that never ends.
  20595. server_->Get("/endless-line", [](const Request &, Response &res) {
  20596. res.set_chunked_content_provider(
  20597. "text/event-stream", [](size_t offset, DataSink &sink) {
  20598. if (offset == 0) { sink.write("data: ", 6); }
  20599. std::string chunk(64 * 1024, 'A');
  20600. return sink.write(chunk.data(), chunk.size());
  20601. });
  20602. });
  20603. Client client("localhost", get_port());
  20604. // Lift the payload limit, so that only the event limit can end this endless
  20605. // stream.
  20606. client.set_payload_max_length(0);
  20607. sse::SSEClient sse(client, "/endless-line");
  20608. std::atomic<bool> too_long{false};
  20609. sse.on_error([&](Error err) {
  20610. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20611. });
  20612. sse.set_max_reconnect_attempts(1);
  20613. sse.start_async();
  20614. for (int i = 0; i < 500 && !too_long; i++) {
  20615. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20616. }
  20617. sse.stop();
  20618. EXPECT_TRUE(too_long);
  20619. }
  20620. // Test: on_message callback
  20621. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20622. // Endpoint that sends multiple events then closes
  20623. server_->Get("/multi-event", [](const Request &, Response &res) {
  20624. res.set_chunked_content_provider(
  20625. "text/event-stream", [](size_t offset, DataSink &sink) {
  20626. if (offset == 0) {
  20627. std::string events = "data: message1\n\ndata: message2\n\n";
  20628. sink.write(events.data(), events.size());
  20629. }
  20630. return false;
  20631. });
  20632. });
  20633. Client client("localhost", get_port());
  20634. sse::SSEClient sse(client, "/multi-event");
  20635. std::vector<std::string> received_messages;
  20636. std::mutex messages_mutex;
  20637. sse.on_message([&](const sse::SSEMessage &msg) {
  20638. std::lock_guard<std::mutex> lock(messages_mutex);
  20639. received_messages.push_back(msg.data);
  20640. });
  20641. sse.set_reconnect_interval(100);
  20642. sse.set_max_reconnect_attempts(1);
  20643. sse.start_async();
  20644. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20645. sse.stop();
  20646. std::lock_guard<std::mutex> lock(messages_mutex);
  20647. EXPECT_GE(received_messages.size(), 2u);
  20648. if (received_messages.size() >= 2) {
  20649. EXPECT_EQ(received_messages[0], "message1");
  20650. EXPECT_EQ(received_messages[1], "message2");
  20651. }
  20652. }
  20653. // Test: on_event for specific types
  20654. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20655. Client client("localhost", get_port());
  20656. sse::SSEClient sse(client, "/custom-events");
  20657. std::atomic<bool> update_received{false};
  20658. std::atomic<bool> delete_received{false};
  20659. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20660. if (msg.data == "updated") { update_received.store(true); }
  20661. });
  20662. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20663. if (msg.data == "deleted") { delete_received.store(true); }
  20664. });
  20665. sse.set_max_reconnect_attempts(1);
  20666. sse.start_async();
  20667. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20668. sse.stop();
  20669. EXPECT_TRUE(update_received.load());
  20670. EXPECT_TRUE(delete_received.load());
  20671. }
  20672. // Test: on_error callback on connection failure
  20673. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20674. // Connect to a non-existent port
  20675. Client client("localhost", 59999);
  20676. sse::SSEClient sse(client, "/events");
  20677. std::atomic<bool> error_called{false};
  20678. Error received_error = Error::Success;
  20679. sse.on_error([&](Error err) {
  20680. error_called.store(true);
  20681. received_error = err;
  20682. });
  20683. sse.set_reconnect_interval(50);
  20684. sse.set_max_reconnect_attempts(1);
  20685. sse.start_async();
  20686. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20687. sse.stop();
  20688. EXPECT_TRUE(error_called.load());
  20689. EXPECT_NE(received_error, Error::Success);
  20690. }
  20691. // Test: Last-Event-ID header sent on reconnect
  20692. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20693. // Endpoint that sends event with ID
  20694. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20695. res.set_chunked_content_provider(
  20696. "text/event-stream", [](size_t offset, DataSink &sink) {
  20697. if (offset == 0) {
  20698. std::string event = "id: evt-123\ndata: test\n\n";
  20699. sink.write(event.data(), event.size());
  20700. }
  20701. return false;
  20702. });
  20703. });
  20704. Client client("localhost", get_port());
  20705. sse::SSEClient sse(client, "/event-with-id");
  20706. std::atomic<bool> id_received{false};
  20707. sse.on_message([&](const sse::SSEMessage &msg) {
  20708. if (!msg.id.empty()) { id_received.store(true); }
  20709. });
  20710. sse.set_reconnect_interval(100);
  20711. sse.set_max_reconnect_attempts(1);
  20712. sse.start_async();
  20713. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20714. sse.stop();
  20715. EXPECT_TRUE(id_received.load());
  20716. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20717. }
  20718. // Test: Manual stop
  20719. TEST_F(SSEIntegrationTest, ManualStop) {
  20720. // Endpoint that sends one event and stays open briefly
  20721. std::atomic<bool> handler_running{true};
  20722. server_->Get("/stay-open", [&handler_running](const Request &,
  20723. Response &res) {
  20724. res.set_chunked_content_provider(
  20725. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20726. if (offset == 0) {
  20727. std::string event = "data: connected\n\n";
  20728. sink.write(event.data(), event.size());
  20729. }
  20730. // Keep connection open while handler_running is true
  20731. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20732. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20733. }
  20734. return false;
  20735. });
  20736. });
  20737. Client client("localhost", get_port());
  20738. sse::SSEClient sse(client, "/stay-open");
  20739. std::atomic<bool> connected{false};
  20740. sse.on_open([&connected]() { connected.store(true); });
  20741. sse.set_reconnect_interval(100);
  20742. sse.set_max_reconnect_attempts(1);
  20743. sse.start_async();
  20744. // Wait for connection to establish
  20745. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20746. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20747. }
  20748. EXPECT_TRUE(connected.load());
  20749. EXPECT_TRUE(sse.is_connected());
  20750. // Signal handler to stop
  20751. handler_running.store(false);
  20752. // Stop SSE client
  20753. sse.stop();
  20754. EXPECT_FALSE(sse.is_connected());
  20755. }
  20756. // Test: SSEClient with custom headers
  20757. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20758. // Setup a server endpoint that checks for custom header
  20759. std::atomic<bool> header_received{false};
  20760. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20761. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20762. header_received.store(true);
  20763. }
  20764. res.set_chunked_content_provider("text/event-stream",
  20765. [](size_t, DataSink &) { return false; });
  20766. });
  20767. Client client("localhost", get_port());
  20768. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20769. sse::SSEClient sse(client, "/header-check", headers);
  20770. sse.set_max_reconnect_attempts(1);
  20771. sse.start_async();
  20772. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20773. sse.stop();
  20774. EXPECT_TRUE(header_received.load());
  20775. }
  20776. // Test: Reconnect interval configuration
  20777. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20778. Client client("localhost", get_port());
  20779. sse::SSEClient sse(client, "/events");
  20780. auto &result = sse.set_reconnect_interval(500);
  20781. // Builder pattern should return reference to self
  20782. EXPECT_EQ(&result, &sse);
  20783. }
  20784. // Test: Max reconnect attempts
  20785. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20786. // Connect to non-existent port to force reconnects
  20787. Client client("localhost", 59998);
  20788. sse::SSEClient sse(client, "/events");
  20789. std::atomic<int> error_count{0};
  20790. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20791. sse.set_reconnect_interval(50);
  20792. sse.set_max_reconnect_attempts(2);
  20793. auto start = std::chrono::steady_clock::now();
  20794. sse.start(); // Blocking call
  20795. auto end = std::chrono::steady_clock::now();
  20796. // Should have stopped after 2 failed attempts
  20797. EXPECT_GE(error_count.load(), 2);
  20798. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20799. auto duration =
  20800. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20801. #ifdef _WIN32
  20802. // Windows is much slower for socket connection failures
  20803. EXPECT_LT(duration.count(), 7000);
  20804. #else
  20805. EXPECT_LT(duration.count(), 1000);
  20806. #endif
  20807. }
  20808. // Test: Multi-line data in integration
  20809. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20810. // Endpoint with multi-line data
  20811. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20812. res.set_chunked_content_provider(
  20813. "text/event-stream", [](size_t offset, DataSink &sink) {
  20814. if (offset == 0) {
  20815. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20816. sink.write(event.data(), event.size());
  20817. }
  20818. return false;
  20819. });
  20820. });
  20821. Client client("localhost", get_port());
  20822. sse::SSEClient sse(client, "/multiline-data");
  20823. std::string received_data;
  20824. std::mutex data_mutex;
  20825. sse.on_message([&](const sse::SSEMessage &msg) {
  20826. std::lock_guard<std::mutex> lock(data_mutex);
  20827. received_data = msg.data;
  20828. });
  20829. sse.set_reconnect_interval(100);
  20830. sse.set_max_reconnect_attempts(1);
  20831. sse.start_async();
  20832. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20833. sse.stop();
  20834. std::lock_guard<std::mutex> lock(data_mutex);
  20835. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20836. }
  20837. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20838. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20839. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20840. DataSink &sink) {
  20841. if (offset == 0) {
  20842. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20843. sink.write(events.data(), events.size());
  20844. }
  20845. return false;
  20846. });
  20847. });
  20848. Client client("localhost", get_port());
  20849. sse::SSEClient sse(client, "/empty-data-lines");
  20850. std::mutex mutex;
  20851. std::condition_variable cv;
  20852. std::vector<std::string> received;
  20853. sse.on_message([&](const sse::SSEMessage &msg) {
  20854. std::lock_guard<std::mutex> lock(mutex);
  20855. received.push_back(msg.data);
  20856. cv.notify_all();
  20857. });
  20858. sse.set_max_reconnect_attempts(1);
  20859. sse.start_async();
  20860. {
  20861. std::unique_lock<std::mutex> lock(mutex);
  20862. cv.wait_for(lock, std::chrono::seconds(2),
  20863. [&] { return received.size() >= 3; });
  20864. }
  20865. sse.stop();
  20866. ASSERT_GE(received.size(), 3u);
  20867. EXPECT_EQ(received[0], "");
  20868. EXPECT_EQ(received[1], "\nhello");
  20869. EXPECT_EQ(received[2], "");
  20870. }
  20871. // Test: Auto-reconnect after server disconnection
  20872. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20873. std::atomic<int> connection_count{0};
  20874. std::atomic<int> message_count{0};
  20875. // Endpoint that sends one event and closes, forcing reconnect
  20876. server_->Get("/reconnect-test",
  20877. [&connection_count](const Request &, Response &res) {
  20878. connection_count.fetch_add(1);
  20879. res.set_chunked_content_provider(
  20880. "text/event-stream", [](size_t offset, DataSink &sink) {
  20881. if (offset == 0) {
  20882. std::string event = "data: hello\n\n";
  20883. sink.write(event.data(), event.size());
  20884. }
  20885. return false; // Close connection after sending
  20886. });
  20887. });
  20888. Client client("localhost", get_port());
  20889. sse::SSEClient sse(client, "/reconnect-test");
  20890. sse.on_message([&message_count](const sse::SSEMessage &) {
  20891. message_count.fetch_add(1);
  20892. });
  20893. sse.set_reconnect_interval(100);
  20894. sse.set_max_reconnect_attempts(3);
  20895. sse.start_async();
  20896. // Wait long enough for multiple reconnects
  20897. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20898. sse.stop();
  20899. // Should have connected multiple times (initial + reconnects)
  20900. EXPECT_GE(connection_count.load(), 2);
  20901. // Should have received messages from multiple connections
  20902. EXPECT_GE(message_count.load(), 2);
  20903. }
  20904. // Test: A retry field that is not all ASCII digits is ignored
  20905. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20906. std::atomic<int> connection_count{0};
  20907. server_->Get("/bad-retry",
  20908. [&connection_count](const Request &, Response &res) {
  20909. connection_count.fetch_add(1);
  20910. res.set_chunked_content_provider(
  20911. "text/event-stream", [](size_t offset, DataSink &sink) {
  20912. if (offset == 0) {
  20913. std::string event = "retry: -1\ndata: hello\n\n";
  20914. sink.write(event.data(), event.size());
  20915. }
  20916. return false;
  20917. });
  20918. });
  20919. Client client("localhost", get_port());
  20920. sse::SSEClient sse(client, "/bad-retry");
  20921. sse.set_reconnect_interval(10000);
  20922. sse.start_async();
  20923. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20924. sse.stop();
  20925. EXPECT_EQ(connection_count.load(), 1);
  20926. }
  20927. // Test: A retry field of all ASCII digits sets the reconnection time
  20928. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20929. std::mutex mutex;
  20930. std::condition_variable cv;
  20931. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20932. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20933. {
  20934. std::lock_guard<std::mutex> lock(mutex);
  20935. connected_at.push_back(std::chrono::steady_clock::now());
  20936. cv.notify_all();
  20937. }
  20938. res.set_chunked_content_provider(
  20939. "text/event-stream", [](size_t offset, DataSink &sink) {
  20940. if (offset == 0) {
  20941. std::string event = "retry: 0\ndata: hello\n\n";
  20942. sink.write(event.data(), event.size());
  20943. }
  20944. return false;
  20945. });
  20946. });
  20947. Client client("localhost", get_port());
  20948. sse::SSEClient sse(client, "/zero-retry");
  20949. sse.set_reconnect_interval(10000);
  20950. sse.start_async();
  20951. {
  20952. std::unique_lock<std::mutex> lock(mutex);
  20953. cv.wait_for(lock, std::chrono::seconds(5),
  20954. [&] { return connected_at.size() >= 2; });
  20955. }
  20956. sse.stop();
  20957. // The server-supplied interval is applied, but never below 100ms, so
  20958. // "retry: 0" does not cause a busy reconnect loop
  20959. std::lock_guard<std::mutex> lock(mutex);
  20960. ASSERT_GE(connected_at.size(), 2u);
  20961. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20962. connected_at[1] - connected_at[0])
  20963. .count();
  20964. EXPECT_GE(interval_ms, 100);
  20965. }
  20966. // Test: Last-Event-ID sent on reconnect
  20967. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20968. std::atomic<int> connection_count{0};
  20969. std::vector<std::string> received_last_event_ids;
  20970. std::mutex id_mutex;
  20971. // Endpoint that checks Last-Event-ID header and sends event with ID
  20972. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20973. int conn = connection_count.fetch_add(1);
  20974. // Capture the Last-Event-ID header from each connection
  20975. {
  20976. std::lock_guard<std::mutex> lock(id_mutex);
  20977. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20978. }
  20979. res.set_chunked_content_provider(
  20980. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20981. if (offset == 0) {
  20982. std::string event =
  20983. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20984. sink.write(event.data(), event.size());
  20985. }
  20986. return false;
  20987. });
  20988. });
  20989. Client client("localhost", get_port());
  20990. sse::SSEClient sse(client, "/reconnect-with-id");
  20991. sse.set_reconnect_interval(100);
  20992. sse.set_max_reconnect_attempts(3);
  20993. sse.start_async();
  20994. // Wait for at least 2 connections
  20995. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20996. sse.stop();
  20997. // Verify behavior
  20998. std::lock_guard<std::mutex> lock(id_mutex);
  20999. EXPECT_GE(received_last_event_ids.size(), 2u);
  21000. // First connection should have no Last-Event-ID
  21001. if (!received_last_event_ids.empty()) {
  21002. EXPECT_EQ(received_last_event_ids[0], "");
  21003. }
  21004. // Second connection should have Last-Event-ID from first connection
  21005. if (received_last_event_ids.size() >= 2) {
  21006. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21007. }
  21008. }
  21009. // Test: set_headers updates headers used on reconnect
  21010. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21011. std::vector<std::string> received_tokens;
  21012. std::mutex token_mutex;
  21013. // Endpoint that captures Authorization header
  21014. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21015. {
  21016. std::lock_guard<std::mutex> lock(token_mutex);
  21017. received_tokens.push_back(req.get_header_value("Authorization"));
  21018. }
  21019. res.set_chunked_content_provider(
  21020. "text/event-stream", [](size_t offset, DataSink &sink) {
  21021. if (offset == 0) {
  21022. std::string event = "data: hello\n\n";
  21023. sink.write(event.data(), event.size());
  21024. }
  21025. return false; // Close connection to trigger reconnect
  21026. });
  21027. });
  21028. Client client("localhost", get_port());
  21029. Headers headers = {{"Authorization", "Bearer old-token"}};
  21030. sse::SSEClient sse(client, "/auth-check", headers);
  21031. // Update headers on each successful connection
  21032. sse.on_open(
  21033. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21034. sse.set_reconnect_interval(100);
  21035. sse.set_max_reconnect_attempts(3);
  21036. sse.start_async();
  21037. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21038. sse.stop();
  21039. std::lock_guard<std::mutex> lock(token_mutex);
  21040. ASSERT_GE(received_tokens.size(), 2u);
  21041. // First connection uses original header
  21042. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21043. // Second connection uses updated header from set_headers
  21044. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21045. }
  21046. // Test: 401 allows reconnection (so on_error can refresh headers)
  21047. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21048. std::atomic<int> connection_count{0};
  21049. // Endpoint: returns 401 on first attempt, 200 on second
  21050. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21051. int conn = connection_count.fetch_add(1);
  21052. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21053. res.status = StatusCode::Unauthorized_401;
  21054. res.set_content("Unauthorized", "text/plain");
  21055. return;
  21056. }
  21057. res.set_chunked_content_provider(
  21058. "text/event-stream", [](size_t offset, DataSink &sink) {
  21059. if (offset == 0) {
  21060. std::string event = "data: authenticated\n\n";
  21061. sink.write(event.data(), event.size());
  21062. }
  21063. return false;
  21064. });
  21065. });
  21066. Client client("localhost", get_port());
  21067. Headers headers = {{"Authorization", "Bearer expired"}};
  21068. sse::SSEClient sse(client, "/auth-retry", headers);
  21069. std::atomic<bool> message_received{false};
  21070. // Refresh token on error
  21071. sse.on_error(
  21072. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21073. sse.on_message([&](const sse::SSEMessage &msg) {
  21074. if (msg.data == "authenticated") { message_received.store(true); }
  21075. });
  21076. sse.set_reconnect_interval(100);
  21077. sse.set_max_reconnect_attempts(3);
  21078. sse.start_async();
  21079. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21080. sse.stop();
  21081. // Should have reconnected after 401 and succeeded with new token
  21082. EXPECT_GE(connection_count.load(), 2);
  21083. EXPECT_TRUE(message_received.load());
  21084. }
  21085. TEST(Issue2318Test, EmptyHostString) {
  21086. {
  21087. httplib::Client cli_empty("", PORT);
  21088. auto res = cli_empty.Get("/");
  21089. ASSERT_FALSE(res);
  21090. EXPECT_EQ(httplib::Error::Connection, res.error());
  21091. }
  21092. {
  21093. httplib::Client cli(" ", PORT);
  21094. auto res = cli.Get("/");
  21095. ASSERT_FALSE(res);
  21096. EXPECT_EQ(httplib::Error::Connection, res.error());
  21097. }
  21098. }
  21099. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21100. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21101. Server svr;
  21102. // Set a small payload limit (1KB)
  21103. svr.set_payload_max_length(1024);
  21104. svr.Post("/test", [&](const Request &req, Response &res) {
  21105. res.set_content("Body size: " + std::to_string(req.body.size()),
  21106. "text/plain");
  21107. });
  21108. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21109. auto se = detail::scope_exit([&] {
  21110. svr.stop();
  21111. listen_thread.join();
  21112. });
  21113. svr.wait_until_ready();
  21114. // Create data that compresses well but exceeds limit when decompressed
  21115. // 8KB of repeated null bytes compresses to a very small size
  21116. std::string original_data(8 * 1024, '\0');
  21117. // Compress the data using gzip
  21118. std::string compressed_data;
  21119. detail::gzip_compressor compressor;
  21120. compressor.compress(original_data.data(), original_data.size(), true,
  21121. [&](const char *data, size_t size) {
  21122. compressed_data.append(data, size);
  21123. return true;
  21124. });
  21125. // Verify compression worked (compressed should be much smaller)
  21126. ASSERT_LT(compressed_data.size(), original_data.size());
  21127. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21128. // Send compressed data with Content-Encoding: gzip
  21129. Client cli(HOST, PORT);
  21130. Headers headers = {{"Content-Encoding", "gzip"}};
  21131. auto res =
  21132. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21133. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21135. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21136. }
  21137. #endif
  21138. // ============================================================================
  21139. // OpenSSL-Specific Tests
  21140. // ============================================================================
  21141. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21142. X509 *readCertificate(const std::string &strFileName) {
  21143. std::ifstream inStream(strFileName);
  21144. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21145. std::istreambuf_iterator<char>());
  21146. if (strCertPEM.empty()) return (nullptr);
  21147. BIO *pbCert = BIO_new(BIO_s_mem());
  21148. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21149. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21150. BIO_free(pbCert);
  21151. return (pCert);
  21152. }
  21153. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21154. std::ifstream inStream(strFileName);
  21155. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21156. std::istreambuf_iterator<char>());
  21157. if (strPrivateKeyPEM.empty()) return (nullptr);
  21158. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21159. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21160. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21161. BIO_free(pbPrivKey);
  21162. return (pPrivateKey);
  21163. }
  21164. TEST(BindServerTest, UpdateCerts) {
  21165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21166. int port = svr.bind_to_any_port("0.0.0.0");
  21167. ASSERT_TRUE(svr.is_valid());
  21168. ASSERT_TRUE(port > 0);
  21169. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21170. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21171. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21172. ASSERT_TRUE(cert != nullptr);
  21173. ASSERT_TRUE(ca_cert != nullptr);
  21174. ASSERT_TRUE(key != nullptr);
  21175. X509_STORE *cert_store = X509_STORE_new();
  21176. X509_STORE_add_cert(cert_store, ca_cert);
  21177. // svr.update_certs(cert, key, cert_store); // deprecated
  21178. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21179. CLIENT_CA_CERT_FILE);
  21180. ASSERT_TRUE(svr.is_valid());
  21181. svr.stop();
  21182. X509_STORE_free(cert_store);
  21183. X509_free(cert);
  21184. X509_free(ca_cert);
  21185. EVP_PKEY_free(key);
  21186. }
  21187. // Test that update_certs() updates client CA list correctly
  21188. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21189. // Start with file-based constructor
  21190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21191. ASSERT_TRUE(svr.is_valid());
  21192. // Initially no client CA list should be set
  21193. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21194. ASSERT_TRUE(ssl_ctx != nullptr);
  21195. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21196. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21197. EXPECT_EQ(0, count_before);
  21198. // Now update with client CA (PEM string)
  21199. std::string cert_pem, key_pem, ca_pem;
  21200. read_file(SERVER_CERT_FILE, cert_pem);
  21201. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21202. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21203. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21204. ASSERT_TRUE(svr.is_valid());
  21205. // Now client CA list should be set
  21206. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21207. ASSERT_TRUE(ca_list_after != nullptr);
  21208. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21209. }
  21210. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21211. // Test that the file-path SSLServer constructor properly sets the client CA
  21212. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21214. ASSERT_TRUE(svr.is_valid());
  21215. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21216. ASSERT_TRUE(ssl_ctx != nullptr);
  21217. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21218. ASSERT_TRUE(ca_list != nullptr);
  21219. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21220. }
  21221. #endif
  21222. // ============================================================================
  21223. // MbedTLS-Specific Tests
  21224. // ============================================================================
  21225. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21226. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21227. using namespace httplib::tls;
  21228. // Track if callback was invoked
  21229. bool callback_invoked = false;
  21230. // The callback receives void* ctx which is actually MbedTlsContext*
  21231. // We can access the mbedtls_ssl_config via the context
  21232. auto setup_callback = [&callback_invoked](void *ctx) {
  21233. callback_invoked = true;
  21234. // Cast to MbedTlsContext* to access the ssl config
  21235. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21236. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21237. // Use static variables to hold certificate data (simplified for test)
  21238. static mbedtls_x509_crt own_cert;
  21239. static mbedtls_pk_context own_key;
  21240. static mbedtls_x509_crt ca_chain;
  21241. static bool initialized = false;
  21242. if (!initialized) {
  21243. mbedtls_x509_crt_init(&own_cert);
  21244. mbedtls_pk_init(&own_key);
  21245. mbedtls_x509_crt_init(&ca_chain);
  21246. // Load server certificate
  21247. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21248. return false;
  21249. }
  21250. // Load server private key.
  21251. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21252. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21253. #if MBEDTLS_VERSION_MAJOR == 3
  21254. ,
  21255. mbedtls_ctr_drbg_random, nullptr
  21256. #endif
  21257. ) != 0) {
  21258. return false;
  21259. }
  21260. // Load CA chain for client verification
  21261. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21262. return false;
  21263. }
  21264. initialized = true;
  21265. }
  21266. // Configure the SSL config
  21267. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21268. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21269. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21270. // Set minimum TLS version using mbedTLS native API
  21271. #if MBEDTLS_VERSION_MAJOR >= 3
  21272. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21273. #else
  21274. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21275. MBEDTLS_SSL_MINOR_VERSION_3);
  21276. #endif
  21277. return true;
  21278. };
  21279. SSLServer svr(setup_callback);
  21280. ASSERT_TRUE(svr.is_valid());
  21281. ASSERT_TRUE(callback_invoked);
  21282. svr.Get("/test", [&](const Request &req, Response &res) {
  21283. res.set_content("test", "text/plain");
  21284. auto cert = req.peer_cert();
  21285. ASSERT_TRUE(static_cast<bool>(cert));
  21286. auto common_name = cert.subject_cn();
  21287. EXPECT_EQ("Common Name", common_name);
  21288. });
  21289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21290. auto se = detail::scope_exit([&] {
  21291. svr.stop();
  21292. t.join();
  21293. ASSERT_FALSE(svr.is_running());
  21294. });
  21295. svr.wait_until_ready();
  21296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21297. cli.enable_server_certificate_verification(false);
  21298. cli.set_connection_timeout(30);
  21299. auto res = cli.Get("/test");
  21300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21301. ASSERT_EQ(StatusCode::OK_200, res->status);
  21302. }
  21303. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21304. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21305. // keep-alive SSL session, which reads through that config in
  21306. // mbedtls_ssl_close_notify.
  21307. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21309. ASSERT_TRUE(svr.is_valid());
  21310. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21311. res.set_content("test", "text/plain");
  21312. });
  21313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21314. auto se = detail::scope_exit([&] {
  21315. svr.stop();
  21316. t.join();
  21317. ASSERT_FALSE(svr.is_running());
  21318. });
  21319. svr.wait_until_ready();
  21320. {
  21321. SSLClient cli(HOST, PORT);
  21322. cli.enable_server_certificate_verification(false);
  21323. cli.set_keep_alive(true);
  21324. auto res = cli.Get("/test");
  21325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21326. ASSERT_EQ(StatusCode::OK_200, res->status);
  21327. // cli is destructed here with the keep-alive SSL session still open.
  21328. }
  21329. }
  21330. #endif
  21331. // WebSocket Tests
  21332. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21333. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21334. // defining the meaning of these bits has been negotiated.
  21335. auto make_frame = [](uint8_t first_byte) {
  21336. std::string frame;
  21337. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21338. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21339. frame += "Hello";
  21340. return frame;
  21341. };
  21342. // RSV1 set (0x40)
  21343. {
  21344. detail::BufferStream strm;
  21345. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21346. ws::Opcode opcode;
  21347. std::string payload;
  21348. bool fin;
  21349. EXPECT_EQ(
  21350. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21351. ws::impl::FrameRead::Fail);
  21352. }
  21353. // RSV2 set (0x20)
  21354. {
  21355. detail::BufferStream strm;
  21356. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21357. ws::Opcode opcode;
  21358. std::string payload;
  21359. bool fin;
  21360. EXPECT_EQ(
  21361. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21362. ws::impl::FrameRead::Fail);
  21363. }
  21364. // RSV3 set (0x10)
  21365. {
  21366. detail::BufferStream strm;
  21367. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21368. ws::Opcode opcode;
  21369. std::string payload;
  21370. bool fin;
  21371. EXPECT_EQ(
  21372. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21373. ws::impl::FrameRead::Fail);
  21374. }
  21375. // No RSV bits set - should succeed
  21376. {
  21377. detail::BufferStream strm;
  21378. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21379. ws::Opcode opcode;
  21380. std::string payload;
  21381. bool fin;
  21382. EXPECT_EQ(
  21383. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21384. ws::impl::FrameRead::Ok);
  21385. EXPECT_EQ(ws::Opcode::Text, opcode);
  21386. EXPECT_EQ("Hello", payload);
  21387. EXPECT_TRUE(fin);
  21388. }
  21389. }
  21390. TEST(WebSocketTest, ControlFrameValidation) {
  21391. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21392. // payload length <= 125.
  21393. // Ping with FIN=0 - must be rejected
  21394. {
  21395. detail::BufferStream strm;
  21396. std::string frame;
  21397. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21398. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21399. strm.write(frame.data(), frame.size());
  21400. ws::Opcode opcode;
  21401. std::string payload;
  21402. bool fin;
  21403. EXPECT_EQ(
  21404. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21405. ws::impl::FrameRead::Fail);
  21406. }
  21407. // Close with FIN=0 - must be rejected
  21408. {
  21409. detail::BufferStream strm;
  21410. std::string frame;
  21411. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21412. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21413. strm.write(frame.data(), frame.size());
  21414. ws::Opcode opcode;
  21415. std::string payload;
  21416. bool fin;
  21417. EXPECT_EQ(
  21418. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21419. ws::impl::FrameRead::Fail);
  21420. }
  21421. // Ping with payload_len=126 (extended length) - must be rejected
  21422. {
  21423. detail::BufferStream strm;
  21424. std::string frame;
  21425. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21426. frame += static_cast<char>(126); // payload_len=126 (>125)
  21427. frame += static_cast<char>(0x00); // extended length high byte
  21428. frame += static_cast<char>(126); // extended length low byte
  21429. frame += std::string(126, 'x');
  21430. strm.write(frame.data(), frame.size());
  21431. ws::Opcode opcode;
  21432. std::string payload;
  21433. bool fin;
  21434. EXPECT_EQ(
  21435. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21436. ws::impl::FrameRead::Fail);
  21437. }
  21438. // Ping with FIN=1 and payload_len=125 - should succeed
  21439. {
  21440. detail::BufferStream strm;
  21441. std::string frame;
  21442. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21443. frame += static_cast<char>(125); // payload_len=125
  21444. frame += std::string(125, 'x');
  21445. strm.write(frame.data(), frame.size());
  21446. ws::Opcode opcode;
  21447. std::string payload;
  21448. bool fin;
  21449. EXPECT_EQ(
  21450. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21451. ws::impl::FrameRead::Ok);
  21452. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21453. EXPECT_EQ(125u, payload.size());
  21454. EXPECT_TRUE(fin);
  21455. }
  21456. }
  21457. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21458. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21459. // length MUST be 0.
  21460. // MSB set - must be rejected
  21461. {
  21462. detail::BufferStream strm;
  21463. std::string frame;
  21464. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21465. frame += static_cast<char>(127); // 64-bit extended length
  21466. frame += static_cast<char>(0x80); // MSB set (invalid)
  21467. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21468. strm.write(frame.data(), frame.size());
  21469. ws::Opcode opcode;
  21470. std::string payload;
  21471. bool fin;
  21472. EXPECT_EQ(
  21473. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21474. ws::impl::FrameRead::Fail);
  21475. }
  21476. // MSB clear - should pass length parsing (will be rejected by max_len,
  21477. // but that's a different check; use a small length to verify)
  21478. {
  21479. detail::BufferStream strm;
  21480. std::string frame;
  21481. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21482. frame += static_cast<char>(127); // 64-bit extended length
  21483. frame += std::string(7, '\0'); // high bytes = 0
  21484. frame += static_cast<char>(0x03); // length = 3
  21485. frame += "abc";
  21486. strm.write(frame.data(), frame.size());
  21487. ws::Opcode opcode;
  21488. std::string payload;
  21489. bool fin;
  21490. EXPECT_EQ(
  21491. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21492. ws::impl::FrameRead::Ok);
  21493. EXPECT_EQ(ws::Opcode::Text, opcode);
  21494. EXPECT_EQ("abc", payload);
  21495. }
  21496. }
  21497. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21498. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21499. // Valid UTF-8
  21500. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21501. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21502. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21503. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21504. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21505. // Invalid UTF-8
  21506. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21507. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21508. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21509. EXPECT_FALSE(
  21510. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21511. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21512. }
  21513. TEST(WebSocketTest, ConnectAndDisconnect) {
  21514. Server svr;
  21515. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21516. std::string msg;
  21517. while (ws.read(msg)) {}
  21518. });
  21519. auto port = svr.bind_to_any_port(HOST);
  21520. std::thread t([&]() { svr.listen_after_bind(); });
  21521. svr.wait_until_ready();
  21522. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21523. auto res = client.connect();
  21524. ASSERT_TRUE(res);
  21525. EXPECT_EQ(Error::Success, res.error());
  21526. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21527. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21528. EXPECT_TRUE(client.is_open());
  21529. client.close();
  21530. EXPECT_FALSE(client.is_open());
  21531. svr.stop();
  21532. t.join();
  21533. }
  21534. TEST(WebSocketTest, ValidURL) {
  21535. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21536. EXPECT_TRUE(ws1.is_valid());
  21537. ws::WebSocketClient ws2("ws://example.com/path");
  21538. EXPECT_TRUE(ws2.is_valid());
  21539. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21540. EXPECT_TRUE(ws3.is_valid());
  21541. #ifdef CPPHTTPLIB_SSL_ENABLED
  21542. ws::WebSocketClient wss1("wss://example.com/path");
  21543. EXPECT_TRUE(wss1.is_valid());
  21544. ws::WebSocketClient wss2("wss://example.com:443/path");
  21545. EXPECT_TRUE(wss2.is_valid());
  21546. #endif
  21547. }
  21548. TEST(WebSocketTest, InvalidURL) {
  21549. // No scheme
  21550. ws::WebSocketClient ws1("localhost:8080/path");
  21551. EXPECT_FALSE(ws1.is_valid());
  21552. // No path
  21553. ws::WebSocketClient ws2("ws://localhost:8080");
  21554. EXPECT_FALSE(ws2.is_valid());
  21555. // Empty string
  21556. ws::WebSocketClient ws3("");
  21557. EXPECT_FALSE(ws3.is_valid());
  21558. // Missing host
  21559. ws::WebSocketClient ws4("ws://:8080/path");
  21560. EXPECT_FALSE(ws4.is_valid());
  21561. // Port number overflow — should not crash
  21562. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21563. EXPECT_FALSE(ws5.is_valid());
  21564. // Port out of range
  21565. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21566. EXPECT_FALSE(ws6.is_valid());
  21567. }
  21568. TEST(WebSocketTest, UnsupportedScheme) {
  21569. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21570. ws::WebSocketClient ws1("http://localhost:8080/path");
  21571. EXPECT_FALSE(ws1.is_valid());
  21572. ws::WebSocketClient ws2("https://localhost:8080/path");
  21573. EXPECT_FALSE(ws2.is_valid());
  21574. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21575. EXPECT_FALSE(ws3.is_valid());
  21576. #else
  21577. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21578. std::invalid_argument);
  21579. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21580. std::invalid_argument);
  21581. #endif
  21582. }
  21583. TEST(WebSocketTest, ConnectWhenInvalid) {
  21584. ws::WebSocketClient ws("not a valid url");
  21585. EXPECT_FALSE(ws.is_valid());
  21586. auto res = ws.connect();
  21587. EXPECT_FALSE(res);
  21588. EXPECT_EQ(Error::Connection, res.error());
  21589. EXPECT_EQ(-1, res.status());
  21590. }
  21591. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21592. // Grab a port that is free, then close it again so nothing listens there
  21593. Server svr;
  21594. auto port = svr.bind_to_any_port(HOST);
  21595. svr.stop();
  21596. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21597. auto res = client.connect();
  21598. ASSERT_FALSE(res);
  21599. EXPECT_EQ(Error::Connection, res.error());
  21600. EXPECT_EQ(-1, res.status());
  21601. }
  21602. TEST(WebSocketTest, DefaultPort) {
  21603. ws::WebSocketClient ws1("ws://example.com/path");
  21604. EXPECT_TRUE(ws1.is_valid());
  21605. // ws:// defaults to port 80 (verified by successful parse)
  21606. #ifdef CPPHTTPLIB_SSL_ENABLED
  21607. ws::WebSocketClient ws2("wss://example.com/path");
  21608. EXPECT_TRUE(ws2.is_valid());
  21609. // wss:// defaults to port 443 (verified by successful parse)
  21610. #endif
  21611. }
  21612. TEST(WebSocketTest, IPv6LiteralAddress) {
  21613. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21614. EXPECT_TRUE(ws1.is_valid());
  21615. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21616. EXPECT_TRUE(ws2.is_valid());
  21617. }
  21618. TEST(WebSocketTest, ComplexPath) {
  21619. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21620. EXPECT_TRUE(ws1.is_valid());
  21621. ws::WebSocketClient ws2("ws://localhost:8080/");
  21622. EXPECT_TRUE(ws2.is_valid());
  21623. }
  21624. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21625. Server svr;
  21626. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21627. std::string msg;
  21628. while (ws.read(msg)) {}
  21629. });
  21630. auto port = svr.bind_to_any_port(HOST);
  21631. std::thread t([&]() { svr.listen_after_bind(); });
  21632. svr.wait_until_ready();
  21633. auto another_host = "example.com";
  21634. auto wrong_ip = "192.0.2.1";
  21635. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21636. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21637. ASSERT_TRUE(client.connect());
  21638. EXPECT_TRUE(client.is_open());
  21639. client.close();
  21640. svr.stop();
  21641. t.join();
  21642. }
  21643. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21644. Server svr;
  21645. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21646. std::string msg;
  21647. while (ws.read(msg)) {}
  21648. });
  21649. auto port = svr.bind_to_any_port(HOST);
  21650. std::thread t([&]() { svr.listen_after_bind(); });
  21651. svr.wait_until_ready();
  21652. auto wrong_ip = "192.0.2.1";
  21653. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21654. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21655. client.set_connection_timeout(1);
  21656. client.set_read_timeout(1);
  21657. client.set_write_timeout(1);
  21658. EXPECT_FALSE(client.connect());
  21659. EXPECT_FALSE(client.is_open());
  21660. svr.stop();
  21661. t.join();
  21662. }
  21663. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21664. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21665. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21666. // (RFC 6761) is only a map key and the Host header value.
  21667. auto host = "target.invalid";
  21668. Server svr;
  21669. std::string received_host;
  21670. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21671. received_host = req.get_header_value("Host");
  21672. std::string msg;
  21673. while (ws.read(msg)) {}
  21674. });
  21675. auto port = svr.bind_to_any_port(HOST);
  21676. std::thread t([&]() { svr.listen_after_bind(); });
  21677. // ASSERT_* below returns from the test body, which would leave t joinable
  21678. // and make ~thread call std::terminate.
  21679. auto se = detail::scope_exit([&] {
  21680. svr.stop();
  21681. if (t.joinable()) { t.join(); }
  21682. });
  21683. svr.wait_until_ready();
  21684. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21685. std::to_string(port) + "/ws");
  21686. client.set_hostname_addr_map({{host, HOST}});
  21687. ASSERT_TRUE(client.connect());
  21688. EXPECT_TRUE(client.is_open());
  21689. client.close();
  21690. svr.stop();
  21691. t.join();
  21692. // The mapping only redirects the connection; the identity stays host_.
  21693. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21694. }
  21695. class WebSocketIntegrationTest : public ::testing::Test {
  21696. protected:
  21697. void SetUp() override {
  21698. server_ = httplib::detail::make_unique<Server>();
  21699. setup_server();
  21700. start_server();
  21701. }
  21702. void TearDown() override {
  21703. server_->stop();
  21704. if (server_thread_.joinable()) { server_thread_.join(); }
  21705. }
  21706. void setup_server() {
  21707. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21708. std::string msg;
  21709. ws::ReadResult ret;
  21710. while ((ret = ws.read(msg))) {
  21711. if (ret == ws::Binary) {
  21712. ws.send(msg.data(), msg.size());
  21713. } else {
  21714. ws.send(msg);
  21715. }
  21716. }
  21717. });
  21718. server_->WebSocket("/ws-echo-string",
  21719. [](const Request &, ws::WebSocket &ws) {
  21720. std::string msg;
  21721. while (ws.read(msg)) {
  21722. ws.send("echo: " + msg);
  21723. }
  21724. });
  21725. server_->WebSocket(
  21726. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21727. // Echo back request metadata
  21728. ws.send("path:" + req.path);
  21729. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21730. std::string msg;
  21731. while (ws.read(msg)) {}
  21732. });
  21733. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21734. std::string msg;
  21735. ws.read(msg); // wait for a message
  21736. ws.close();
  21737. });
  21738. server_->WebSocket("/ws-close-status",
  21739. [](const Request &, ws::WebSocket &ws) {
  21740. std::string msg;
  21741. ws.read(msg); // wait for a message
  21742. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21743. });
  21744. server_->WebSocket(
  21745. "/ws-subprotocol",
  21746. [](const Request &, ws::WebSocket &ws) {
  21747. std::string msg;
  21748. while (ws.read(msg)) {
  21749. ws.send(msg);
  21750. }
  21751. },
  21752. [](const std::vector<std::string> &protocols) -> std::string {
  21753. for (const auto &p : protocols) {
  21754. if (p == "graphql-ws") { return p; }
  21755. }
  21756. return "";
  21757. });
  21758. server_->WebSocket(
  21759. "/ws-subprotocol-unoffered",
  21760. [](const Request &, ws::WebSocket &ws) {
  21761. std::string msg;
  21762. while (ws.read(msg)) {
  21763. ws.send(msg);
  21764. }
  21765. },
  21766. [](const std::vector<std::string> &) -> std::string {
  21767. return "admin";
  21768. });
  21769. }
  21770. void start_server() {
  21771. port_ = server_->bind_to_any_port(HOST);
  21772. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21773. server_->wait_until_ready();
  21774. }
  21775. std::unique_ptr<Server> server_;
  21776. std::thread server_thread_;
  21777. int port_ = 0;
  21778. };
  21779. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21780. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21781. "/ws-echo");
  21782. ASSERT_TRUE(client.connect());
  21783. ASSERT_TRUE(client.is_open());
  21784. ASSERT_TRUE(client.send("Hello WebSocket"));
  21785. std::string msg;
  21786. EXPECT_EQ(ws::Text, client.read(msg));
  21787. EXPECT_EQ("Hello WebSocket", msg);
  21788. client.close();
  21789. }
  21790. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21791. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21792. "/ws-echo");
  21793. ASSERT_TRUE(client.connect());
  21794. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21795. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21796. std::string msg;
  21797. EXPECT_EQ(ws::Binary, client.read(msg));
  21798. EXPECT_EQ(binary_data, msg);
  21799. client.close();
  21800. }
  21801. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21802. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21803. "/ws-echo");
  21804. ASSERT_TRUE(client.connect());
  21805. for (int i = 0; i < 10; i++) {
  21806. auto text = "message " + std::to_string(i);
  21807. ASSERT_TRUE(client.send(text));
  21808. std::string msg;
  21809. ASSERT_TRUE(client.read(msg));
  21810. EXPECT_EQ(text, msg);
  21811. }
  21812. client.close();
  21813. }
  21814. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21816. "/ws-close");
  21817. ASSERT_TRUE(client.connect());
  21818. // Send a message to trigger the server to close
  21819. ASSERT_TRUE(client.send("trigger close"));
  21820. // The server will close, so read should return false
  21821. std::string msg;
  21822. EXPECT_FALSE(client.read(msg));
  21823. EXPECT_FALSE(client.is_open());
  21824. }
  21825. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21826. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21827. "/ws-echo");
  21828. ASSERT_TRUE(client.connect());
  21829. // 128KB message
  21830. std::string large_data(128 * 1024, 'X');
  21831. ASSERT_TRUE(client.send(large_data));
  21832. std::string msg;
  21833. ASSERT_TRUE(client.read(msg));
  21834. EXPECT_EQ(large_data, msg);
  21835. client.close();
  21836. }
  21837. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21838. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21839. "/ws-echo");
  21840. ASSERT_TRUE(client.connect());
  21841. const int num_threads = 4;
  21842. std::vector<std::thread> threads;
  21843. std::atomic<int> send_count{0};
  21844. for (int t = 0; t < num_threads; t++) {
  21845. threads.emplace_back([&client, &send_count, t]() {
  21846. for (int i = 0; i < 5; i++) {
  21847. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21848. if (client.send(text)) { send_count++; }
  21849. }
  21850. });
  21851. }
  21852. for (auto &th : threads) {
  21853. th.join();
  21854. }
  21855. int received = 0;
  21856. std::string msg;
  21857. while (received < send_count.load()) {
  21858. if (!client.read(msg)) { break; }
  21859. received++;
  21860. }
  21861. EXPECT_EQ(send_count.load(), received);
  21862. client.close();
  21863. }
  21864. TEST_F(WebSocketIntegrationTest, ReadString) {
  21865. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21866. "/ws-echo-string");
  21867. ASSERT_TRUE(client.connect());
  21868. ASSERT_TRUE(client.send("hello"));
  21869. std::string msg;
  21870. ASSERT_TRUE(client.read(msg));
  21871. EXPECT_EQ("echo: hello", msg);
  21872. ASSERT_TRUE(client.send("world"));
  21873. ASSERT_TRUE(client.read(msg));
  21874. EXPECT_EQ("echo: world", msg);
  21875. client.close();
  21876. }
  21877. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21878. Headers headers = {{"X-Test-Header", "test-value"}};
  21879. ws::WebSocketClient client(
  21880. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21881. ASSERT_TRUE(client.connect());
  21882. std::string msg;
  21883. ASSERT_TRUE(client.read(msg));
  21884. EXPECT_EQ("path:/ws-request-info", msg);
  21885. ASSERT_TRUE(client.read(msg));
  21886. EXPECT_EQ("header:test-value", msg);
  21887. client.close();
  21888. }
  21889. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21890. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21891. "/ws-echo");
  21892. client.set_read_timeout(1, 0); // 1 second
  21893. ASSERT_TRUE(client.connect());
  21894. // Don't send anything — server echo handler waits for a message, so read()
  21895. // should time out. The connection survives it: nothing was consumed.
  21896. std::string msg;
  21897. EXPECT_EQ(client.read(msg), ws::Timeout);
  21898. EXPECT_TRUE(client.is_open());
  21899. // And it is still usable afterwards.
  21900. EXPECT_TRUE(client.send("after timeout"));
  21901. EXPECT_EQ(client.read(msg), ws::Text);
  21902. EXPECT_EQ(msg, "after timeout");
  21903. }
  21904. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21905. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21906. "/ws-echo");
  21907. client.set_read_timeout(1, 0);
  21908. ASSERT_TRUE(client.connect());
  21909. ASSERT_TRUE(client.send("first"));
  21910. std::string msg;
  21911. ASSERT_EQ(client.read(msg), ws::Text);
  21912. ASSERT_EQ(msg, "first");
  21913. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21914. // not be used with a read timeout: it would reprocess the previous message.
  21915. EXPECT_EQ(client.read(msg), ws::Timeout);
  21916. EXPECT_EQ(msg, "first");
  21917. }
  21918. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21920. "/ws-echo");
  21921. ASSERT_TRUE(client.connect());
  21922. // Setting it once the connection is open reaches the live stream, not just
  21923. // the seed for the next connect().
  21924. client.set_read_timeout(1, 0);
  21925. std::string msg;
  21926. EXPECT_EQ(client.read(msg), ws::Timeout);
  21927. EXPECT_TRUE(client.is_open());
  21928. }
  21929. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21930. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21931. "/ws-echo");
  21932. client.set_read_timeout(5, 0);
  21933. ASSERT_TRUE(client.connect());
  21934. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21935. // The server should reject it and close the connection.
  21936. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21937. client.send(oversized);
  21938. // The server's read() should have failed due to payload limit,
  21939. // so our read() should return false (connection closed).
  21940. std::string msg;
  21941. EXPECT_FALSE(client.read(msg));
  21942. }
  21943. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21945. "/ws-echo");
  21946. client.set_read_timeout(10, 0);
  21947. ASSERT_TRUE(client.connect());
  21948. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21949. // This should succeed.
  21950. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21951. ASSERT_TRUE(client.send(at_limit));
  21952. std::string msg;
  21953. ASSERT_TRUE(client.read(msg));
  21954. EXPECT_EQ(at_limit.size(), msg.size());
  21955. client.close();
  21956. }
  21957. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21959. "/nonexistent");
  21960. auto res = client.connect();
  21961. EXPECT_FALSE(res);
  21962. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21963. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21964. EXPECT_FALSE(client.is_open());
  21965. }
  21966. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21967. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21968. "/ws-echo");
  21969. ASSERT_TRUE(client.connect());
  21970. ASSERT_TRUE(client.send(""));
  21971. std::string msg;
  21972. EXPECT_EQ(ws::Text, client.read(msg));
  21973. EXPECT_EQ("", msg);
  21974. client.close();
  21975. }
  21976. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21978. "/ws-echo");
  21979. // First connection
  21980. ASSERT_TRUE(client.connect());
  21981. ASSERT_TRUE(client.send("first"));
  21982. std::string msg;
  21983. ASSERT_TRUE(client.read(msg));
  21984. EXPECT_EQ("first", msg);
  21985. client.close();
  21986. EXPECT_FALSE(client.is_open());
  21987. // Reconnect using the same client object
  21988. ASSERT_TRUE(client.connect());
  21989. ASSERT_TRUE(client.is_open());
  21990. ASSERT_TRUE(client.send("second"));
  21991. ASSERT_TRUE(client.read(msg));
  21992. EXPECT_EQ("second", msg);
  21993. client.close();
  21994. }
  21995. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21996. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21997. "/ws-close-status");
  21998. ASSERT_TRUE(client.connect());
  21999. // Trigger the server to close with GoingAway status
  22000. ASSERT_TRUE(client.send("trigger"));
  22001. // read() should return false after receiving the close frame
  22002. std::string msg;
  22003. EXPECT_FALSE(client.read(msg));
  22004. EXPECT_FALSE(client.is_open());
  22005. }
  22006. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22007. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22008. "/ws-echo");
  22009. ASSERT_TRUE(client.connect());
  22010. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22011. EXPECT_FALSE(client.is_open());
  22012. }
  22013. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22014. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22015. ws::WebSocketClient client(
  22016. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22017. ASSERT_TRUE(client.connect());
  22018. // Server should have selected graphql-ws
  22019. EXPECT_EQ("graphql-ws", client.subprotocol());
  22020. client.close();
  22021. }
  22022. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22023. Headers headers;
  22024. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22025. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22026. ws::WebSocketClient client(
  22027. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22028. ASSERT_TRUE(client.connect());
  22029. // The offer on the second field line counts too, so graphql-ws is selected
  22030. EXPECT_EQ("graphql-ws", client.subprotocol());
  22031. client.close();
  22032. }
  22033. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22034. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22035. ws::WebSocketClient client(
  22036. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22037. ASSERT_TRUE(client.connect());
  22038. // Server should not have selected any subprotocol
  22039. EXPECT_TRUE(client.subprotocol().empty());
  22040. client.close();
  22041. }
  22042. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22043. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22045. "/ws-subprotocol-unoffered",
  22046. headers);
  22047. ASSERT_TRUE(client.connect());
  22048. EXPECT_TRUE(client.subprotocol().empty());
  22049. client.close();
  22050. }
  22051. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22052. // Connect without requesting any subprotocol
  22053. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22054. "/ws-subprotocol");
  22055. ASSERT_TRUE(client.connect());
  22056. EXPECT_TRUE(client.subprotocol().empty());
  22057. client.close();
  22058. }
  22059. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22060. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22061. "/ws-echo");
  22062. client.set_tcp_nodelay(true);
  22063. client.set_connection_timeout(3, 0);
  22064. bool socket_options_called = false;
  22065. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22066. ASSERT_TRUE(client.connect());
  22067. ASSERT_TRUE(client.is_open());
  22068. EXPECT_TRUE(socket_options_called);
  22069. ASSERT_TRUE(client.send("hello"));
  22070. std::string msg;
  22071. auto result = client.read(msg);
  22072. EXPECT_EQ(result, ws::ReadResult::Text);
  22073. EXPECT_EQ(msg, "hello");
  22074. client.close();
  22075. }
  22076. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22078. "/ws-echo");
  22079. client.set_connection_timeout(std::chrono::seconds(3));
  22080. client.set_write_timeout(std::chrono::seconds(3));
  22081. // A sub-second remainder exercises the seconds/microseconds split.
  22082. client.set_read_timeout(std::chrono::milliseconds(1500));
  22083. ASSERT_TRUE(client.connect());
  22084. auto start = std::chrono::steady_clock::now();
  22085. std::string msg;
  22086. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22087. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22088. std::chrono::steady_clock::now() - start)
  22089. .count();
  22090. // Above 1s so that dropping the microseconds half of the split fails here.
  22091. // Ignoring the setter altogether would not reach this line at all: a client
  22092. // waits forever by default.
  22093. EXPECT_GE(elapsed, 1400);
  22094. EXPECT_LT(elapsed, 30000);
  22095. }
  22096. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22097. Server svr;
  22098. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22099. if (!req.has_header("Authorization")) {
  22100. res.status = StatusCode::Unauthorized_401;
  22101. res.set_content("Unauthorized", "text/plain");
  22102. return Server::HandlerResponse::Handled;
  22103. }
  22104. return Server::HandlerResponse::Unhandled;
  22105. });
  22106. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22107. std::string msg;
  22108. while (ws.read(msg)) {
  22109. ws.send(msg);
  22110. }
  22111. });
  22112. auto port = svr.bind_to_any_port("localhost");
  22113. std::thread t([&]() { svr.listen_after_bind(); });
  22114. svr.wait_until_ready();
  22115. // Without Authorization header - should be rejected before upgrade
  22116. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22117. EXPECT_FALSE(client1.connect());
  22118. // The rejection is framed like any other HTTP response
  22119. {
  22120. Client cli("localhost", port);
  22121. Headers headers = {{"Upgrade", "websocket"},
  22122. {"Connection", "Upgrade"},
  22123. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22124. {"Sec-WebSocket-Version", "13"}};
  22125. auto res = cli.Get("/ws", headers);
  22126. ASSERT_TRUE(res);
  22127. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22128. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22129. EXPECT_EQ("Unauthorized", res->body);
  22130. }
  22131. // With Authorization header - should succeed
  22132. Headers headers = {{"Authorization", "Bearer token123"}};
  22133. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22134. headers);
  22135. ASSERT_TRUE(client2.connect());
  22136. ASSERT_TRUE(client2.send("hello"));
  22137. std::string msg;
  22138. ASSERT_TRUE(client2.read(msg));
  22139. EXPECT_EQ("hello", msg);
  22140. client2.close();
  22141. svr.stop();
  22142. t.join();
  22143. }
  22144. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22145. Server svr;
  22146. std::atomic<int> pre_request_calls{0};
  22147. std::atomic<bool> route_matched{false};
  22148. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22149. pre_request_calls++;
  22150. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22151. if (req.get_header_value("Authorization") != "Bearer token123") {
  22152. res.status = StatusCode::Unauthorized_401;
  22153. res.set_content("Unauthorized", "text/plain");
  22154. return Server::HandlerResponse::Handled;
  22155. }
  22156. return Server::HandlerResponse::Unhandled;
  22157. });
  22158. std::atomic<bool> handler_called{false};
  22159. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22160. handler_called = true;
  22161. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22162. });
  22163. auto port = svr.bind_to_any_port("localhost");
  22164. std::thread t([&]() { svr.listen_after_bind(); });
  22165. svr.wait_until_ready();
  22166. // Without Authorization header - should be rejected before upgrade
  22167. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22168. "/ws/1");
  22169. EXPECT_FALSE(client1.connect());
  22170. EXPECT_FALSE(handler_called);
  22171. EXPECT_EQ(1, pre_request_calls);
  22172. EXPECT_TRUE(route_matched);
  22173. // The rejection is an ordinary HTTP response, not a protocol switch
  22174. {
  22175. Client cli("localhost", port);
  22176. Headers headers = {{"Upgrade", "websocket"},
  22177. {"Connection", "Upgrade"},
  22178. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22179. {"Sec-WebSocket-Version", "13"}};
  22180. auto res = cli.Get("/ws/1", headers);
  22181. ASSERT_TRUE(res);
  22182. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22183. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22184. EXPECT_EQ("Unauthorized", res->body);
  22185. }
  22186. EXPECT_FALSE(handler_called);
  22187. // With Authorization header - should succeed
  22188. Headers headers = {{"Authorization", "Bearer token123"}};
  22189. ws::WebSocketClient client2(
  22190. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22191. ASSERT_TRUE(client2.connect());
  22192. std::string msg;
  22193. ASSERT_TRUE(client2.read(msg));
  22194. EXPECT_EQ("/ws/:id 2", msg);
  22195. EXPECT_TRUE(handler_called);
  22196. client2.close();
  22197. svr.stop();
  22198. t.join();
  22199. }
  22200. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22201. Server svr;
  22202. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22203. // A read timeout is how a handler gets control back. Without it, a handler
  22204. // parked in read() can never write on the connection it is reading.
  22205. ws.set_read_timeout(std::chrono::milliseconds(100));
  22206. std::string msg;
  22207. while (ws.is_open()) {
  22208. auto r = ws.read(msg);
  22209. if (r == httplib::ws::Timeout) {
  22210. ws.send("tick");
  22211. continue;
  22212. }
  22213. if (r == httplib::ws::Fail) { break; }
  22214. ws.send(msg);
  22215. }
  22216. });
  22217. auto port = svr.bind_to_any_port("localhost");
  22218. std::thread t([&]() { svr.listen_after_bind(); });
  22219. svr.wait_until_ready();
  22220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22221. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22222. ASSERT_TRUE(client.connect());
  22223. // The client sends nothing, so anything it receives came out of the
  22224. // handler's timeout path.
  22225. std::string msg;
  22226. ASSERT_EQ(client.read(msg), ws::Text);
  22227. EXPECT_EQ("tick", msg);
  22228. client.close();
  22229. svr.stop();
  22230. t.join();
  22231. }
  22232. // Stream::read may return fewer bytes than asked for. This is that contract at
  22233. // its worst -- one byte per call -- which is what a frame header straddling a
  22234. // read buffer's boundary looks like to the frame parser.
  22235. class WsByteAtATimeStream : public Stream {
  22236. public:
  22237. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22238. bool is_readable() const override { return true; }
  22239. bool wait_readable() const override { return true; }
  22240. bool wait_writable() const override { return true; }
  22241. ssize_t read(char *ptr, size_t size) override {
  22242. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22243. *ptr = data_[pos_++];
  22244. return 1;
  22245. }
  22246. ssize_t write(const char *, size_t size) override {
  22247. return static_cast<ssize_t>(size);
  22248. }
  22249. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22250. ip = "127.0.0.1";
  22251. port = 0;
  22252. }
  22253. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22254. ip = "127.0.0.1";
  22255. port = 0;
  22256. }
  22257. socket_t socket() const override { return INVALID_SOCKET; }
  22258. time_t duration() const override { return 0; }
  22259. private:
  22260. std::string data_;
  22261. size_t pos_ = 0;
  22262. };
  22263. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22264. // The payload uses the 16-bit extended length, so the header, the length
  22265. // and the mask key are all multi-byte fields here. Each used to be read
  22266. // with a single read() call, which fails as soon as one is split. The
  22267. // payload is also a little over one read chunk, so it is read in two.
  22268. std::string body;
  22269. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22270. body += static_cast<char>(i % 251);
  22271. }
  22272. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22273. std::string frame;
  22274. frame += static_cast<char>(0x81); // FIN + Text
  22275. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22276. frame += static_cast<char>(body.size() >> 8);
  22277. frame += static_cast<char>(body.size() & 0xff);
  22278. for (size_t i = 0; i < 4; i++) {
  22279. frame += static_cast<char>(mask[i]);
  22280. }
  22281. for (size_t i = 0; i < body.size(); i++) {
  22282. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22283. }
  22284. WsByteAtATimeStream strm(frame);
  22285. ws::Opcode opcode;
  22286. std::string payload;
  22287. bool fin = false;
  22288. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22289. /*expect_masked=*/true, body.size()),
  22290. ws::impl::FrameRead::Ok);
  22291. EXPECT_TRUE(fin);
  22292. EXPECT_EQ(opcode, ws::Opcode::Text);
  22293. EXPECT_EQ(payload, body);
  22294. }
  22295. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22296. std::string body(2000, 'x');
  22297. std::string frame;
  22298. frame += static_cast<char>(0x82); // FIN + Binary
  22299. frame += static_cast<char>(126); // 16-bit length follows
  22300. frame += static_cast<char>(body.size() >> 8);
  22301. frame += static_cast<char>(body.size() & 0xff);
  22302. frame += body;
  22303. detail::BufferStream strm;
  22304. strm.write(frame.data(), frame.size());
  22305. ws::Opcode opcode;
  22306. std::string payload;
  22307. bool fin;
  22308. EXPECT_EQ(
  22309. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22310. ws::impl::FrameRead::Ok);
  22311. EXPECT_EQ(body, payload);
  22312. }
  22313. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22314. // The header announces the largest payload allowed, and only 3 bytes of it
  22315. // ever arrive.
  22316. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22317. std::string frame;
  22318. frame += static_cast<char>(0x82); // FIN + Binary
  22319. frame += static_cast<char>(127); // 64-bit length follows
  22320. for (int shift = 56; shift >= 0; shift -= 8) {
  22321. frame += static_cast<char>((len >> shift) & 0xff);
  22322. }
  22323. frame += "abc";
  22324. detail::BufferStream strm;
  22325. strm.write(frame.data(), frame.size());
  22326. ws::Opcode opcode;
  22327. std::string payload;
  22328. bool fin;
  22329. EXPECT_EQ(
  22330. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22331. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22332. ws::impl::FrameRead::Fail);
  22333. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22334. }
  22335. TEST(WebSocketTest, QueryStringInHandshake) {
  22336. Server svr;
  22337. std::mutex mtx;
  22338. std::string received_target;
  22339. std::string received_token;
  22340. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22341. {
  22342. std::lock_guard<std::mutex> lock(mtx);
  22343. received_target = req.target;
  22344. if (req.has_param("token")) {
  22345. received_token = req.get_param_value("token");
  22346. }
  22347. }
  22348. std::string msg;
  22349. while (ws.read(msg)) {
  22350. ws.send(msg);
  22351. }
  22352. });
  22353. auto port = svr.bind_to_any_port("localhost");
  22354. std::thread t([&]() { svr.listen_after_bind(); });
  22355. svr.wait_until_ready();
  22356. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22357. "/ws?token=ABC&session=123");
  22358. ASSERT_TRUE(client.connect());
  22359. // Round-trip ensures the handler has run and captured the request.
  22360. ASSERT_TRUE(client.send("hello"));
  22361. std::string msg;
  22362. ASSERT_TRUE(client.read(msg));
  22363. EXPECT_EQ("hello", msg);
  22364. client.close();
  22365. {
  22366. std::lock_guard<std::mutex> lock(mtx);
  22367. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22368. EXPECT_EQ("ABC", received_token);
  22369. }
  22370. svr.stop();
  22371. t.join();
  22372. }
  22373. // Run a handshake against a throwaway server and hand the request the server
  22374. // received back to the caller, so tests can assert on the headers the client
  22375. // actually put on the wire.
  22376. static void capture_websocket_handshake_request(
  22377. const Headers &client_headers,
  22378. std::function<void(const Request &, int port)> verify) {
  22379. Server svr;
  22380. std::mutex mtx;
  22381. Request received;
  22382. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22383. {
  22384. std::lock_guard<std::mutex> lock(mtx);
  22385. received = req;
  22386. }
  22387. std::string msg;
  22388. while (ws.read(msg)) {
  22389. ws.send(msg);
  22390. }
  22391. });
  22392. auto port = svr.bind_to_any_port("localhost");
  22393. std::thread t([&]() { svr.listen_after_bind(); });
  22394. auto se = detail::scope_exit([&] {
  22395. svr.stop();
  22396. t.join();
  22397. });
  22398. svr.wait_until_ready();
  22399. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22400. client_headers);
  22401. ASSERT_TRUE(client.connect());
  22402. ASSERT_TRUE(client.send("hello"));
  22403. std::string msg;
  22404. ASSERT_TRUE(client.read(msg));
  22405. client.close();
  22406. {
  22407. std::lock_guard<std::mutex> lock(mtx);
  22408. verify(received, port);
  22409. }
  22410. }
  22411. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22412. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22413. // Non-default port must be present in the Host header. Default ports
  22414. // (80/443) are omitted; that logic is covered by
  22415. // MakeHostAndPortStringTest.
  22416. EXPECT_EQ("localhost:" + std::to_string(port),
  22417. req.get_header_value("Host"));
  22418. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22419. req.get_header_value("User-Agent"));
  22420. EXPECT_FALSE(req.has_header("Accept"));
  22421. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22422. EXPECT_FALSE(req.has_header("Content-Length"));
  22423. });
  22424. }
  22425. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22426. capture_websocket_handshake_request(
  22427. {{"Host", "example.com"},
  22428. {"User-Agent", "custom-agent"},
  22429. {"X-Custom", "value"}},
  22430. [](const Request &req, int) {
  22431. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22432. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22433. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22434. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22435. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22436. });
  22437. }
  22438. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22439. capture_websocket_handshake_request(
  22440. {{"Upgrade", "bogus"},
  22441. {"Connection", "close"},
  22442. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22443. {"Sec-WebSocket-Version", "8"}},
  22444. [](const Request &req, int) {
  22445. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22446. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22447. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22448. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22449. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22450. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22451. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22452. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22453. req.get_header_value("Sec-WebSocket-Key"));
  22454. });
  22455. }
  22456. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22457. // A header the client refuses to send must abort the handshake before any
  22458. // part of it reaches the wire; a lone request line would otherwise sit in
  22459. // the peer's buffer as a truncated request.
  22460. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22461. ASSERT_NE(INVALID_SOCKET, srv);
  22462. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22463. sockaddr_in addr{};
  22464. addr.sin_family = AF_INET;
  22465. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22466. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22467. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22468. ASSERT_EQ(0, ::listen(srv, 1));
  22469. sockaddr_in bound{};
  22470. socklen_t bound_len = sizeof(bound);
  22471. ASSERT_EQ(
  22472. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22473. auto port = ntohs(bound.sin_port);
  22474. ssize_t received = -1;
  22475. std::thread t([&] {
  22476. // Bound every blocking call so a regression fails the test with a bad
  22477. // value instead of hanging the suite.
  22478. fd_set rfds;
  22479. FD_ZERO(&rfds);
  22480. FD_SET(srv, &rfds);
  22481. timeval tv{5, 0};
  22482. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22483. 0) {
  22484. return;
  22485. }
  22486. sockaddr_in cli_addr{};
  22487. socklen_t cli_len = sizeof(cli_addr);
  22488. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22489. if (cli == INVALID_SOCKET) { return; }
  22490. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22491. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22492. char buf[4096];
  22493. received = ::recv(cli, buf, sizeof(buf), 0);
  22494. });
  22495. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22496. // connect() has already shut the socket down by the time it returns false,
  22497. // so the peer sees EOF without waiting for the client to be destroyed.
  22498. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22499. {{"X-Bad", "a\r\nInjected: 1"}});
  22500. EXPECT_FALSE(client.connect());
  22501. t.join();
  22502. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22503. EXPECT_EQ(0, received);
  22504. }
  22505. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22506. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22507. // contains "upgrade" as a substring is a different token and must not
  22508. // start a WebSocket handshake.
  22509. auto make_request = [](const std::vector<std::string> &connection_values) {
  22510. Request req;
  22511. req.method = "GET";
  22512. req.headers.emplace("Upgrade", "websocket");
  22513. for (const auto &value : connection_values) {
  22514. req.headers.emplace("Connection", value);
  22515. }
  22516. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22517. req.headers.emplace("Sec-WebSocket-Version", "13");
  22518. return req;
  22519. };
  22520. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22521. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22522. EXPECT_TRUE(
  22523. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22524. EXPECT_TRUE(
  22525. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22526. EXPECT_TRUE(
  22527. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22528. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22529. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22530. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22531. EXPECT_FALSE(
  22532. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22533. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22534. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22535. }
  22536. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22537. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22538. // asks recipients to match each protocol-name case-insensitively, and RFC
  22539. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22540. // client naming websocket alongside another protocol, or on a second field
  22541. // line, is offering websocket; a value that merely contains "websocket" as a
  22542. // substring is a different protocol name and is not.
  22543. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22544. Request req;
  22545. req.method = "GET";
  22546. for (const auto &value : upgrade_values) {
  22547. req.headers.emplace("Upgrade", value);
  22548. }
  22549. req.headers.emplace("Connection", "Upgrade");
  22550. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22551. req.headers.emplace("Sec-WebSocket-Version", "13");
  22552. return req;
  22553. };
  22554. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22555. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22556. EXPECT_TRUE(
  22557. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22558. EXPECT_TRUE(
  22559. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22560. EXPECT_TRUE(
  22561. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22562. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22563. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22564. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22565. EXPECT_FALSE(
  22566. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22567. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22568. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22569. }
  22570. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22571. Server svr;
  22572. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22573. auto port = svr.bind_to_any_port("localhost");
  22574. std::thread t([&]() { svr.listen_after_bind(); });
  22575. auto se = detail::scope_exit([&] {
  22576. svr.stop();
  22577. t.join();
  22578. });
  22579. svr.wait_until_ready();
  22580. Headers headers = {{"Upgrade", "websocket"},
  22581. {"Connection", "notupgrade"},
  22582. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22583. {"Sec-WebSocket-Version", "13"}};
  22584. Client cli("localhost", port);
  22585. auto res = cli.Get("/ws", headers);
  22586. // The route exists only as a WebSocket route, so a request that fails the
  22587. // handshake check falls through to ordinary routing.
  22588. ASSERT_TRUE(res);
  22589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22590. }
  22591. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22592. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22593. // Connection value is the only thing left for the client to reject.
  22594. Server svr;
  22595. svr.Get("/ws", [](const Request &req, Response &res) {
  22596. res.status = StatusCode::SwitchingProtocol_101;
  22597. res.set_header("Upgrade", "websocket");
  22598. res.set_header("Connection", "notupgrade");
  22599. res.set_header("Sec-WebSocket-Accept",
  22600. detail::websocket_accept_key(
  22601. req.get_header_value("Sec-WebSocket-Key")));
  22602. });
  22603. auto port = svr.bind_to_any_port("localhost");
  22604. std::thread t([&]() { svr.listen_after_bind(); });
  22605. auto se = detail::scope_exit([&] {
  22606. svr.stop();
  22607. t.join();
  22608. });
  22609. svr.wait_until_ready();
  22610. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22611. auto res = client.connect();
  22612. EXPECT_FALSE(res);
  22613. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22614. EXPECT_FALSE(client.is_open());
  22615. }
  22616. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22617. Server svr;
  22618. svr.Get("/ws", [](const Request &req, Response &res) {
  22619. res.status = StatusCode::SwitchingProtocol_101;
  22620. res.set_header("Upgrade", "websocket");
  22621. res.set_header("Connection", "Upgrade");
  22622. res.set_header("Sec-WebSocket-Accept",
  22623. detail::websocket_accept_key(
  22624. req.get_header_value("Sec-WebSocket-Key")));
  22625. res.set_header("Sec-WebSocket-Protocol", "admin");
  22626. });
  22627. auto port = svr.bind_to_any_port("localhost");
  22628. std::thread t([&]() { svr.listen_after_bind(); });
  22629. auto se = detail::scope_exit([&] {
  22630. svr.stop();
  22631. t.join();
  22632. });
  22633. svr.wait_until_ready();
  22634. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22635. // Server selects a subprotocol the client never offered
  22636. {
  22637. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22638. ws::WebSocketClient client(url, headers);
  22639. auto res = client.connect();
  22640. EXPECT_FALSE(res);
  22641. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22642. EXPECT_FALSE(client.is_open());
  22643. EXPECT_TRUE(client.subprotocol().empty());
  22644. }
  22645. // Client offered none but the server named one anyway
  22646. {
  22647. ws::WebSocketClient client(url);
  22648. auto res = client.connect();
  22649. EXPECT_FALSE(res);
  22650. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22651. EXPECT_FALSE(client.is_open());
  22652. EXPECT_TRUE(client.subprotocol().empty());
  22653. }
  22654. }
  22655. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22656. // The socket path doubles as the URL host, so it must not contain '/'.
  22657. const char *shard = getenv("GTEST_SHARD_INDEX");
  22658. const std::string sock_path =
  22659. shard ? std::string("httplib-ws-") + shard + ".sock"
  22660. : std::string("httplib-ws.sock");
  22661. std::remove(sock_path.c_str());
  22662. Server svr;
  22663. std::mutex mtx;
  22664. std::string received_host;
  22665. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22666. {
  22667. std::lock_guard<std::mutex> lock(mtx);
  22668. received_host = req.get_header_value("Host");
  22669. }
  22670. std::string msg;
  22671. while (ws.read(msg)) {
  22672. ws.send(msg);
  22673. }
  22674. });
  22675. svr.set_address_family(AF_UNIX);
  22676. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22677. auto se = detail::scope_exit([&] {
  22678. svr.stop();
  22679. t.join();
  22680. std::remove(sock_path.c_str());
  22681. });
  22682. svr.wait_until_ready();
  22683. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22684. client.set_address_family(AF_UNIX);
  22685. ASSERT_TRUE(client.connect());
  22686. ASSERT_TRUE(client.send("hello"));
  22687. std::string msg;
  22688. ASSERT_TRUE(client.read(msg));
  22689. client.close();
  22690. {
  22691. std::lock_guard<std::mutex> lock(mtx);
  22692. // There is no host:port for a Unix socket, so the same "localhost"
  22693. // placeholder the HTTP client uses is expected.
  22694. EXPECT_EQ("localhost", received_host);
  22695. }
  22696. }
  22697. // Two threads must never parse WebSocket frames from the same stream.
  22698. // close() used to read the peer's Close reply with its own frame read, so it
  22699. // raced a reader thread that was in the middle of a payload: the payload loop
  22700. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22701. // so bytes taken by close() were replaced with bytes from further along the
  22702. // stream. The message kept its length and silently changed content.
  22703. //
  22704. // The raw peer below sends a frame header plus part of the payload, waits for
  22705. // the handler to call close(), and only then sends the rest. Whichever thread
  22706. // would win the race for those bytes, the message must arrive intact, because
  22707. // close() must not touch the stream while read() owns it.
  22708. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22709. #ifndef _WIN32
  22710. signal(SIGPIPE, SIG_IGN);
  22711. #endif
  22712. const size_t payload_len = 120; // fits the 7-bit length field
  22713. const size_t prefix_len = 8;
  22714. const int attempts = 8;
  22715. std::string expected(payload_len, '\0');
  22716. for (size_t i = 0; i < payload_len; i++) {
  22717. expected[i] = static_cast<char>('a' + i % 26);
  22718. }
  22719. std::atomic<bool> peer_stalled{false};
  22720. std::atomic<bool> handler_done{false};
  22721. std::mutex received_mutex;
  22722. std::vector<std::string> received;
  22723. // Bound every wait, so a regression fails the test instead of hanging the
  22724. // suite.
  22725. auto wait_for = [](const std::atomic<bool> &flag) {
  22726. for (int i = 0; i < 500 && !flag; i++) {
  22727. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22728. }
  22729. };
  22730. Server svr;
  22731. svr.set_websocket_ping_interval(0);
  22732. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22733. std::thread reader([&]() {
  22734. std::string msg;
  22735. while (ws.read(msg)) {
  22736. std::lock_guard<std::mutex> guard(received_mutex);
  22737. received.push_back(msg);
  22738. }
  22739. });
  22740. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22741. // inside read_websocket_frame() when close() runs.
  22742. wait_for(peer_stalled);
  22743. ws.close();
  22744. reader.join();
  22745. handler_done = true;
  22746. });
  22747. auto port = svr.bind_to_any_port("127.0.0.1");
  22748. std::thread t([&]() { svr.listen_after_bind(); });
  22749. auto se = detail::scope_exit([&] {
  22750. svr.stop();
  22751. t.join();
  22752. });
  22753. svr.wait_until_ready();
  22754. auto send_bytes = [](socket_t s, const std::string &data) {
  22755. #ifdef _WIN32
  22756. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22757. #else
  22758. auto n = ::send(s, data.data(), data.size(), 0);
  22759. #endif
  22760. return n == static_cast<decltype(n)>(data.size());
  22761. };
  22762. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22763. // Every length used here fits the 7-bit length field.
  22764. auto masked_header = [](uint8_t first_byte, size_t len) {
  22765. std::string h;
  22766. h += static_cast<char>(first_byte);
  22767. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22768. h.append(4, '\0'); // mask key
  22769. return h;
  22770. };
  22771. for (int attempt = 0; attempt < attempts; attempt++) {
  22772. peer_stalled = false;
  22773. handler_done = false;
  22774. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22775. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22776. auto se_sock = detail::scope_exit([&] {
  22777. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22778. });
  22779. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22780. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22781. sockaddr_in addr{};
  22782. addr.sin_family = AF_INET;
  22783. addr.sin_port = htons(static_cast<uint16_t>(port));
  22784. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22785. ASSERT_EQ(
  22786. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22787. << "attempt " << attempt;
  22788. ASSERT_TRUE(send_bytes(sock,
  22789. "GET /ws HTTP/1.1\r\n"
  22790. "Host: 127.0.0.1\r\n"
  22791. "Upgrade: websocket\r\n"
  22792. "Connection: Upgrade\r\n"
  22793. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22794. "Sec-WebSocket-Version: 13\r\n"
  22795. "\r\n"))
  22796. << "attempt " << attempt;
  22797. std::string response;
  22798. while (response.find("\r\n\r\n") == std::string::npos) {
  22799. char buf[512];
  22800. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22801. if (n <= 0) { break; }
  22802. response.append(buf, static_cast<size_t>(n));
  22803. }
  22804. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22805. << "attempt " << attempt;
  22806. // Send the header of a Binary message but only the first prefix_len bytes
  22807. // of its payload, leaving the reader thread stalled inside the payload.
  22808. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22809. expected.substr(0, prefix_len)))
  22810. << "attempt " << attempt;
  22811. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22812. peer_stalled = true;
  22813. // Let close() send its Close frame and park in its own read before the
  22814. // rest of the payload arrives, so both threads are waiting for it.
  22815. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22816. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22817. close_frame += static_cast<char>(0x03); // status 1000
  22818. close_frame += static_cast<char>(0xE8);
  22819. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22820. << "attempt " << attempt;
  22821. // Closing the peer releases the reader thread even on the buggy path,
  22822. // where it waits for bytes another thread already consumed.
  22823. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22824. detail::close_socket(sock);
  22825. sock = INVALID_SOCKET;
  22826. wait_for(handler_done);
  22827. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22828. }
  22829. std::lock_guard<std::mutex> guard(received_mutex);
  22830. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22831. << "a message in flight when close() ran was dropped";
  22832. for (size_t i = 0; i < received.size(); i++) {
  22833. EXPECT_EQ(expected, received[i]) << "message " << i;
  22834. }
  22835. }
  22836. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22837. // returning the socket, or INVALID_SOCKET.
  22838. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22839. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22840. if (sock == INVALID_SOCKET) { return sock; }
  22841. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22842. sockaddr_in addr{};
  22843. addr.sin_family = AF_INET;
  22844. addr.sin_port = htons(static_cast<uint16_t>(port));
  22845. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22846. std::string req = "GET " + path +
  22847. " HTTP/1.1\r\n"
  22848. "Host: 127.0.0.1\r\n"
  22849. "Upgrade: websocket\r\n"
  22850. "Connection: Upgrade\r\n"
  22851. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22852. "Sec-WebSocket-Version: 13\r\n"
  22853. "\r\n";
  22854. std::string res;
  22855. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22856. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22857. static_cast<int>(req.size())) {
  22858. char c;
  22859. while (res.find("\r\n\r\n") == std::string::npos &&
  22860. ::recv(sock, &c, 1, 0) == 1) {
  22861. res += c;
  22862. }
  22863. }
  22864. if (res.find(" 101 ") == std::string::npos) {
  22865. detail::close_socket(sock);
  22866. return INVALID_SOCKET;
  22867. }
  22868. return sock;
  22869. }
  22870. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22871. // The payload must fit the 7-bit length field.
  22872. static std::string masked_frame(uint8_t first_byte,
  22873. const std::string &payload) {
  22874. std::string f;
  22875. f += static_cast<char>(first_byte);
  22876. f += static_cast<char>(0x80 | payload.size());
  22877. f.append(4, '\0');
  22878. return f + payload;
  22879. }
  22880. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22881. std::atomic<bool> done{false};
  22882. std::string received;
  22883. Server svr;
  22884. svr.set_websocket_ping_interval(0);
  22885. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22886. std::string msg;
  22887. if (ws.read(msg) == ws::Binary) { received = msg; }
  22888. done = true;
  22889. });
  22890. auto port = svr.bind_to_any_port("127.0.0.1");
  22891. std::thread t([&]() { svr.listen_after_bind(); });
  22892. auto se = detail::scope_exit([&] {
  22893. svr.stop();
  22894. t.join();
  22895. });
  22896. svr.wait_until_ready();
  22897. auto sock = connect_raw_websocket(port, "/ws");
  22898. ASSERT_NE(INVALID_SOCKET, sock);
  22899. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22900. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22901. masked_frame(0x89, "p") + // FIN + Ping
  22902. masked_frame(0x80, "lo"); // FIN + Continuation
  22903. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22904. for (int i = 0; i < 500 && !done; i++) {
  22905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22906. }
  22907. ASSERT_TRUE(done);
  22908. EXPECT_EQ("Hello", received);
  22909. }
  22910. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22911. Server svr;
  22912. svr.set_websocket_ping_interval(0);
  22913. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22914. std::string msg;
  22915. while (ws.read(msg)) {}
  22916. });
  22917. auto port = svr.bind_to_any_port("127.0.0.1");
  22918. std::thread t([&]() { svr.listen_after_bind(); });
  22919. auto se = detail::scope_exit([&] {
  22920. svr.stop();
  22921. t.join();
  22922. });
  22923. svr.wait_until_ready();
  22924. // Each Close payload and the reply it should get: an echo when valid, 1002
  22925. // otherwise.
  22926. std::vector<std::pair<std::string, std::string>> cases = {
  22927. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22928. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22929. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22930. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22931. };
  22932. for (const auto &c : cases) {
  22933. auto sock = connect_raw_websocket(port, "/ws");
  22934. ASSERT_NE(INVALID_SOCKET, sock);
  22935. auto close_frame = masked_frame(0x88, c.first);
  22936. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22937. std::string reply;
  22938. char buf[256];
  22939. while (reply.size() < 2 + c.second.size()) {
  22940. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22941. if (n <= 0) { break; }
  22942. reply.append(buf, static_cast<size_t>(n));
  22943. }
  22944. detail::close_socket(sock);
  22945. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22946. c.second,
  22947. reply);
  22948. }
  22949. }
  22950. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22951. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22952. protected:
  22953. void SetUp() override {
  22954. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22955. SERVER_PRIVATE_KEY_FILE);
  22956. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22957. std::string msg;
  22958. ws::ReadResult ret;
  22959. while ((ret = ws.read(msg))) {
  22960. if (ret == ws::Binary) {
  22961. ws.send(msg.data(), msg.size());
  22962. } else {
  22963. ws.send(msg);
  22964. }
  22965. }
  22966. });
  22967. port_ = server_->bind_to_any_port(HOST);
  22968. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22969. server_->wait_until_ready();
  22970. }
  22971. void TearDown() override {
  22972. server_->stop();
  22973. if (server_thread_.joinable()) { server_thread_.join(); }
  22974. }
  22975. std::unique_ptr<SSLServer> server_;
  22976. std::thread server_thread_;
  22977. int port_ = 0;
  22978. };
  22979. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  22980. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22981. {
  22982. ws::WebSocketClient client(url);
  22983. client.enable_server_certificate_verification(false);
  22984. auto calls = 0;
  22985. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  22986. calls++;
  22987. return false;
  22988. });
  22989. EXPECT_FALSE(client.connect());
  22990. EXPECT_GT(calls, 0);
  22991. }
  22992. {
  22993. ws::WebSocketClient client(url);
  22994. client.enable_server_certificate_verification(false);
  22995. client.set_session_verifier([](tls::session_t) {
  22996. return SSLVerifierResponse::CertificateRejected;
  22997. });
  22998. EXPECT_FALSE(client.connect());
  22999. }
  23000. {
  23001. ws::WebSocketClient client(url);
  23002. client.enable_server_certificate_verification(false);
  23003. client.set_session_verifier([](tls::session_t) {
  23004. return SSLVerifierResponse::CertificateAccepted;
  23005. });
  23006. EXPECT_TRUE(client.connect());
  23007. }
  23008. }
  23009. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23010. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23011. "/ws-echo");
  23012. client.enable_server_certificate_verification(false);
  23013. ASSERT_TRUE(client.connect());
  23014. ASSERT_TRUE(client.is_open());
  23015. ASSERT_TRUE(client.send("Hello WSS"));
  23016. std::string msg;
  23017. EXPECT_EQ(ws::Text, client.read(msg));
  23018. EXPECT_EQ("Hello WSS", msg);
  23019. client.close();
  23020. }
  23021. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23022. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23023. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23024. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23025. // client (without calling close() first) is the only path that runs
  23026. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23027. // bug exactly.
  23028. //
  23029. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23030. // when linked against an instrumented libssl; run under Valgrind to catch it
  23031. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23032. // suite (the freed session otherwise stalls on the close handshake) — this test
  23033. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23034. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23035. {
  23036. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23037. "/ws-echo");
  23038. client.enable_server_certificate_verification(false);
  23039. client.set_read_timeout(2, 0);
  23040. client.set_write_timeout(2, 0);
  23041. ASSERT_TRUE(client.connect());
  23042. ASSERT_TRUE(client.is_open());
  23043. ASSERT_TRUE(client.send("still open"));
  23044. // Intentionally do NOT call client.close(): leaving scope runs
  23045. // shutdown_and_close() with the WebSocket still open, which must send the
  23046. // close frame while the TLS session is still alive.
  23047. }
  23048. }
  23049. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23050. // shutdown_and_close() at the start of connect(), reproducing the same
  23051. // use-after-free within the test body rather than at scope exit. The second
  23052. // connect must succeed and echo, proving the close handshake ran over a live
  23053. // session. See the note above about memory-tool requirements.
  23054. TEST_F(WebSocketSSLIntegrationTest,
  23055. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23056. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23057. "/ws-echo");
  23058. client.enable_server_certificate_verification(false);
  23059. client.set_read_timeout(2, 0);
  23060. client.set_write_timeout(2, 0);
  23061. ASSERT_TRUE(client.connect());
  23062. ASSERT_TRUE(client.is_open());
  23063. ASSERT_TRUE(client.send("still open"));
  23064. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23065. // the still-open connection, which must not touch a freed TLS session.
  23066. ASSERT_TRUE(client.connect());
  23067. ASSERT_TRUE(client.is_open());
  23068. ASSERT_TRUE(client.send("after reconnect"));
  23069. std::string msg;
  23070. EXPECT_EQ(ws::Text, client.read(msg));
  23071. EXPECT_EQ("after reconnect", msg);
  23072. client.close();
  23073. }
  23074. #endif
  23075. #ifdef CPPHTTPLIB_SSL_ENABLED
  23076. class WebSocketSSLCATest : public ::testing::Test {
  23077. protected:
  23078. void SetUp() override {
  23079. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23080. SERVER_PRIVATE_KEY_FILE);
  23081. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23082. std::string msg;
  23083. while (ws.read(msg)) {
  23084. ws.send(msg);
  23085. }
  23086. });
  23087. port_ = server_->bind_to_any_port("127.0.0.1");
  23088. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23089. server_->wait_until_ready();
  23090. }
  23091. void TearDown() override {
  23092. server_->stop();
  23093. if (server_thread_.joinable()) { server_thread_.join(); }
  23094. }
  23095. std::string url() const {
  23096. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23097. }
  23098. std::unique_ptr<SSLServer> server_;
  23099. std::thread server_thread_;
  23100. int port_ = 0;
  23101. };
  23102. // A custom CA loaded as PEM verifies the server with full certificate
  23103. // verification enabled
  23104. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23105. ws::WebSocketClient client(url());
  23106. std::string cert;
  23107. read_file(SERVER_CERT2_FILE, cert);
  23108. client.load_ca_cert_store(cert.c_str(), cert.size());
  23109. ASSERT_TRUE(client.connect());
  23110. ASSERT_TRUE(client.send("hello"));
  23111. std::string msg;
  23112. EXPECT_EQ(ws::Text, client.read(msg));
  23113. EXPECT_EQ("hello", msg);
  23114. client.close();
  23115. }
  23116. // A custom CA that does not cover the server must fail verification (the
  23117. // custom CA is exclusive; system certs are not loaded alongside it)
  23118. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23119. ws::WebSocketClient client(url());
  23120. std::string cert;
  23121. read_file(CLIENT_CA_CERT_FILE, cert);
  23122. client.load_ca_cert_store(cert.c_str(), cert.size());
  23123. auto res = client.connect();
  23124. ASSERT_FALSE(res);
  23125. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23126. EXPECT_EQ(-1, res.status());
  23127. EXPECT_NE(0u, res.ssl_backend_error());
  23128. }
  23129. // The same CA as a file path rather than PEM in memory
  23130. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23131. ws::WebSocketClient client(url());
  23132. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23133. ASSERT_TRUE(client.connect());
  23134. ASSERT_TRUE(client.send("hello"));
  23135. std::string msg;
  23136. EXPECT_EQ(ws::Text, client.read(msg));
  23137. EXPECT_EQ("hello", msg);
  23138. client.close();
  23139. }
  23140. // ...and a CA file that does not cover the server still fails, so it is the
  23141. // path above that decides the outcome
  23142. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23143. ws::WebSocketClient client(url());
  23144. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23145. ASSERT_FALSE(client.connect());
  23146. }
  23147. // Regression test: reconnecting with a native custom CA store used to reuse
  23148. // a store handle the previous TLS context had already freed (use-after-free
  23149. // under the OpenSSL backend). The context now lives as long as the client.
  23150. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23151. ws::WebSocketClient client(url());
  23152. std::string cert;
  23153. read_file(SERVER_CERT2_FILE, cert);
  23154. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23155. ASSERT_TRUE(client.connect());
  23156. client.close();
  23157. ASSERT_TRUE(client.connect());
  23158. ASSERT_TRUE(client.send("again"));
  23159. std::string msg;
  23160. EXPECT_EQ(ws::Text, client.read(msg));
  23161. EXPECT_EQ("again", msg);
  23162. client.close();
  23163. }
  23164. // Regression test: a certificate with a trusted chain but no identity match
  23165. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23166. // verification entirely for IP hosts, so this connection succeeded there.
  23167. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23168. // chain verification while the identity check must still fail.
  23169. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23171. ASSERT_TRUE(svr.is_valid());
  23172. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23173. std::string msg;
  23174. while (ws.read(msg)) {
  23175. ws.send(msg);
  23176. }
  23177. });
  23178. auto port = svr.bind_to_any_port("127.0.0.1");
  23179. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23180. auto se = detail::scope_exit([&] {
  23181. svr.stop();
  23182. t.join();
  23183. });
  23184. svr.wait_until_ready();
  23185. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23186. "/echo");
  23187. std::string cert;
  23188. read_file(SERVER_CERT_FILE, cert);
  23189. client.load_ca_cert_store(cert.c_str(), cert.size());
  23190. ASSERT_FALSE(client.connect());
  23191. }
  23192. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23193. // SNI, so nothing binds the host name to the TLS session. These bind the
  23194. // server to "localhost" instead, the only shape that exercises the SNI and
  23195. // hostname-verification path with certificate verification left enabled.
  23196. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23197. protected:
  23198. void Start(const char *cert_file) {
  23199. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23200. SERVER_PRIVATE_KEY_FILE);
  23201. ASSERT_TRUE(server_->is_valid());
  23202. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23203. std::string msg;
  23204. while (ws.read(msg)) {
  23205. ws.send(msg);
  23206. }
  23207. });
  23208. port_ = server_->bind_to_any_port("localhost");
  23209. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23210. server_->wait_until_ready();
  23211. }
  23212. void TearDown() override {
  23213. if (server_) { server_->stop(); }
  23214. if (server_thread_.joinable()) { server_thread_.join(); }
  23215. }
  23216. std::string url() const {
  23217. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23218. }
  23219. std::unique_ptr<SSLServer> server_;
  23220. std::thread server_thread_;
  23221. int port_ = 0;
  23222. };
  23223. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23224. // out and the connection is usable
  23225. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23226. Start(SERVER_CERT2_FILE);
  23227. ws::WebSocketClient client(url());
  23228. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23229. ASSERT_TRUE(client.connect());
  23230. ASSERT_TRUE(client.send("hello"));
  23231. std::string msg;
  23232. EXPECT_EQ(ws::Text, client.read(msg));
  23233. EXPECT_EQ("hello", msg);
  23234. client.close();
  23235. }
  23236. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23237. // while the identity check must still reject "localhost"
  23238. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23239. Start(SERVER_CERT_FILE);
  23240. ws::WebSocketClient client(url());
  23241. client.set_ca_cert_path(SERVER_CERT_FILE);
  23242. auto res = client.connect();
  23243. ASSERT_FALSE(res);
  23244. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23245. EXPECT_EQ(-1, res.status());
  23246. }
  23247. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23248. // disabled: the chain is still checked, only the identity check is skipped
  23249. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23250. Start(SERVER_CERT_FILE);
  23251. ws::WebSocketClient client(url());
  23252. client.set_ca_cert_path(SERVER_CERT_FILE);
  23253. client.enable_server_hostname_verification(false);
  23254. ASSERT_TRUE(client.connect());
  23255. ASSERT_TRUE(client.send("hello"));
  23256. std::string msg;
  23257. EXPECT_EQ(ws::Text, client.read(msg));
  23258. EXPECT_EQ("hello", msg);
  23259. client.close();
  23260. }
  23261. // A CA that did not sign the server certificate fails the chain, even though
  23262. // the name would match
  23263. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23264. Start(SERVER_CERT2_FILE);
  23265. ws::WebSocketClient client(url());
  23266. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23267. ASSERT_FALSE(client.connect());
  23268. }
  23269. // With verification disabled, neither the chain nor the name is checked
  23270. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23271. Start(SERVER_CERT_FILE);
  23272. ws::WebSocketClient client(url());
  23273. client.enable_server_certificate_verification(false);
  23274. ASSERT_TRUE(client.connect());
  23275. ASSERT_TRUE(client.send("hello"));
  23276. std::string msg;
  23277. EXPECT_EQ(ws::Text, client.read(msg));
  23278. EXPECT_EQ("hello", msg);
  23279. client.close();
  23280. }
  23281. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23282. protected:
  23283. void SetUp() override {
  23284. server_ = httplib::detail::make_unique<SSLServer>(
  23285. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23286. ASSERT_TRUE(server_->is_valid());
  23287. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23288. std::string msg;
  23289. while (ws.read(msg)) {
  23290. ws.send(msg);
  23291. }
  23292. });
  23293. port_ = server_->bind_to_any_port("localhost");
  23294. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23295. server_->wait_until_ready();
  23296. }
  23297. void TearDown() override {
  23298. server_->stop();
  23299. if (server_thread_.joinable()) { server_thread_.join(); }
  23300. }
  23301. std::string url() const {
  23302. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23303. }
  23304. void ConnectWithClientCert(const std::string &client_cert_file,
  23305. const std::string &client_private_key_file,
  23306. const char *private_key_password) {
  23307. std::string cert_pem, key_pem;
  23308. read_file(client_cert_file, cert_pem);
  23309. read_file(client_private_key_file, key_pem);
  23310. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23311. key_pem.c_str(), key_pem.size(),
  23312. private_key_password};
  23313. ws::WebSocketClient client(url(), pem);
  23314. ASSERT_TRUE(client.is_valid());
  23315. client.enable_server_certificate_verification(false);
  23316. ASSERT_TRUE(client.connect());
  23317. ASSERT_TRUE(client.send("hello"));
  23318. std::string msg;
  23319. EXPECT_EQ(ws::Text, client.read(msg));
  23320. EXPECT_EQ("hello", msg);
  23321. client.close();
  23322. }
  23323. std::unique_ptr<SSLServer> server_;
  23324. std::thread server_thread_;
  23325. int port_ = 0;
  23326. };
  23327. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23328. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23329. }
  23330. // Control for the tests above: the fixture's server really does require a
  23331. // client certificate, so it is the PEM the constructor installed that decides
  23332. // the outcome.
  23333. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23334. ws::WebSocketClient client(url());
  23335. ASSERT_TRUE(client.is_valid());
  23336. client.enable_server_certificate_verification(false);
  23337. EXPECT_FALSE(client.connect());
  23338. }
  23339. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23340. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23341. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23342. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23343. }
  23344. #endif
  23345. #if !defined(_WIN32)
  23346. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23347. auto secret_dir = std::string("./symlink_test_secret");
  23348. auto served_dir = std::string("./symlink_test_served");
  23349. auto secret_file = secret_dir + "/secret.txt";
  23350. auto symlink_path = served_dir + "/escape";
  23351. // Setup: create directories and files
  23352. mkdir(secret_dir.c_str(), 0755);
  23353. mkdir(served_dir.c_str(), 0755);
  23354. {
  23355. std::ofstream ofs(secret_file);
  23356. ofs << "SECRET_DATA";
  23357. }
  23358. // Create symlink using absolute path so it resolves correctly
  23359. #ifdef PATH_MAX
  23360. char abs_secret[PATH_MAX];
  23361. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23362. #else
  23363. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23364. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23365. ASSERT_NE(nullptr, abs_secret);
  23366. #endif
  23367. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23368. auto se = detail::scope_exit([&] {
  23369. unlink(symlink_path.c_str());
  23370. unlink(secret_file.c_str());
  23371. rmdir(served_dir.c_str());
  23372. rmdir(secret_dir.c_str());
  23373. });
  23374. Server svr;
  23375. svr.set_mount_point("/", served_dir);
  23376. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23377. auto se2 = detail::scope_exit([&] {
  23378. svr.stop();
  23379. listen_thread.join();
  23380. });
  23381. svr.wait_until_ready();
  23382. Client cli("localhost", PORT);
  23383. // Symlink pointing outside base dir should be blocked
  23384. auto res = cli.Get("/escape/secret.txt");
  23385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23386. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23387. }
  23388. #endif
  23389. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23390. // "GET /smuggled" request), reads the first response, and only then sends the
  23391. // embedded request as the body. Returns how many times /smuggled ran.
  23392. //
  23393. // The body is sent AFTER receiving the first response (as in the original
  23394. // PoC) so that the stream_line_reader cannot buffer it together with the
  23395. // headers of the first request.
  23396. static int count_smuggled_requests(const std::string &outer_head,
  23397. std::string &first_response) {
  23398. Server svr;
  23399. svr.set_mount_point("/", "./www");
  23400. std::atomic<int> smuggled_count(0);
  23401. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23402. smuggled_count++;
  23403. res.set_content("oops", "text/plain");
  23404. });
  23405. svr.Post("/post", [&](const Request &req, Response &res) {
  23406. res.set_content(req.body, "text/plain");
  23407. });
  23408. auto port = svr.bind_to_any_port("localhost");
  23409. thread t = thread([&] { svr.listen_after_bind(); });
  23410. auto se = detail::scope_exit([&] {
  23411. svr.stop();
  23412. t.join();
  23413. });
  23414. svr.wait_until_ready();
  23415. auto error = Error::Success;
  23416. auto sock = detail::create_client_socket(
  23417. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23418. /*connection_timeout_sec=*/2, 0,
  23419. /*read_timeout_sec=*/2, 0,
  23420. /*write_timeout_sec=*/2, 0, std::string(), error);
  23421. EXPECT_NE(INVALID_SOCKET, sock);
  23422. if (sock == INVALID_SOCKET) { return -1; }
  23423. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23424. // The "smuggled" request will be sent as the body of the outer request
  23425. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23426. "Host: localhost\r\n"
  23427. "Connection: close\r\n"
  23428. "\r\n";
  23429. auto head = outer_head;
  23430. auto len = std::to_string(smuggled.size());
  23431. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23432. pos = head.find("{len}", pos + len.size())) {
  23433. head.replace(pos, 5, len);
  23434. }
  23435. // Step 1: Send only the outer request headers (no body yet)
  23436. auto sent = send(sock, head.data(), head.size(), 0);
  23437. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23438. // Step 2: Read the first response
  23439. char buf[4096];
  23440. for (;;) {
  23441. auto n = recv(sock, buf, sizeof(buf), 0);
  23442. if (n <= 0) break;
  23443. first_response.append(buf, static_cast<size_t>(n));
  23444. // Stop once we have a complete response (headers + body)
  23445. auto hdr_end = first_response.find("\r\n\r\n");
  23446. if (hdr_end != std::string::npos) {
  23447. // Check for Content-Length to know when the body is complete
  23448. auto cl_pos = first_response.find("Content-Length:");
  23449. if (cl_pos != std::string::npos) {
  23450. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23451. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23452. auto cl = std::stoul(
  23453. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23454. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23455. } else {
  23456. break; // No Content-Length, assume headers-only response
  23457. }
  23458. }
  23459. }
  23460. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23461. // vulnerable server the keep-alive loop reads this as a second request. The
  23462. // server may already have closed the connection, so the result is ignored.
  23463. send(sock, smuggled.data(), smuggled.size(), 0);
  23464. // Half-close so that a server which drained the body sees EOF and closes,
  23465. // instead of the read below waiting for the read timeout.
  23466. #ifdef _WIN32
  23467. ::shutdown(sock, SD_SEND);
  23468. #else
  23469. ::shutdown(sock, SHUT_WR);
  23470. #endif
  23471. // Step 4: Read until the server closes the connection
  23472. for (;;) {
  23473. auto n = recv(sock, buf, sizeof(buf), 0);
  23474. if (n <= 0) break;
  23475. }
  23476. return smuggled_count.load();
  23477. }
  23478. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23479. // A GET request with Content-Length to a static file handler must have its
  23480. // body drained before the keep-alive connection is reused. Otherwise the
  23481. // unread body bytes are interpreted as the next HTTP request.
  23482. std::string first_response;
  23483. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23484. "Host: localhost\r\n"
  23485. "Content-Length: {len}\r\n"
  23486. "\r\n",
  23487. first_response));
  23488. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23489. }
  23490. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23491. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23492. // be answered with 400 and the connection closed. Treating it as "no body"
  23493. // leaves the body to be parsed as the next request.
  23494. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23495. const char *targets[] = {
  23496. "GET /file", // handler that never reads the body
  23497. "GET /not-found", // no handler matches (404)
  23498. "POST /post", // handler that reads the body
  23499. };
  23500. for (auto target : targets) {
  23501. for (auto value : values) {
  23502. std::string first_response;
  23503. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23504. " HTTP/1.1\r\n"
  23505. "Host: localhost\r\n"
  23506. "Content-Length: " +
  23507. value + "\r\n\r\n",
  23508. first_response))
  23509. << target << " with Content-Length: " << value;
  23510. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23511. << target << " with Content-Length: " << value;
  23512. }
  23513. }
  23514. }
  23515. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23516. // A 400 for an unparseable request line leaves the rest of the message
  23517. // unread, so the connection must be closed rather than reused.
  23518. std::string first_response;
  23519. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23520. "Host: localhost\r\n"
  23521. "Content-Length: {len}\r\n"
  23522. "\r\n",
  23523. first_response));
  23524. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23525. }
  23526. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23527. // Same as above for a header block that fails to parse.
  23528. std::string first_response;
  23529. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23530. "Host: localhost\r\n"
  23531. "Bad Header\r\n"
  23532. "Content-Length: {len}\r\n"
  23533. "\r\n",
  23534. first_response));
  23535. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23536. }
  23537. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23538. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23539. // server must not read another request on that connection, even when the
  23540. // request had no body to drain.
  23541. std::string first_response;
  23542. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23543. "Host: localhost\r\n"
  23544. "\r\n",
  23545. first_response));
  23546. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23547. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23548. }
  23549. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23550. // A content reader that stops early leaves the stream inside the body.
  23551. // Draining the whole Content-Length from there, or reading the body again,
  23552. // reads into the next request, and whatever follows is parsed as a request
  23553. // of its own.
  23554. Server svr;
  23555. std::atomic<int> smuggled_count(0);
  23556. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23557. svr.Post("/upload", [](const Request &req, Response &res,
  23558. const ContentReader &content_reader) {
  23559. // Stop at the last chunk, so the whole body has been read however it
  23560. // arrives.
  23561. auto length = req.get_header_value_u64("Content-Length");
  23562. size_t total = 0;
  23563. auto consumed = content_reader([&](const char *, size_t n) {
  23564. total += n;
  23565. return total < length;
  23566. });
  23567. EXPECT_FALSE(consumed);
  23568. if (req.has_param("retry")) {
  23569. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23570. }
  23571. // Replace the 400 the aborted read set, which would close the connection.
  23572. res.set_redirect("/done");
  23573. });
  23574. auto port = svr.bind_to_any_port(HOST);
  23575. thread t = thread([&] { svr.listen_after_bind(); });
  23576. auto se = detail::scope_exit([&] {
  23577. svr.stop();
  23578. t.join();
  23579. });
  23580. svr.wait_until_ready();
  23581. // A front end sees the second request as a POST whose body is the GET. The
  23582. // first body is as long as the POST's headers, so draining it again reads
  23583. // exactly those and leaves the GET to be parsed next.
  23584. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23585. "Host: localhost\r\n"
  23586. "\r\n";
  23587. std::string second_head = "POST /post HTTP/1.1\r\n"
  23588. "Host: localhost\r\n"
  23589. "Content-Length: " +
  23590. std::to_string(inner.size()) +
  23591. "\r\n"
  23592. "\r\n";
  23593. for (auto target : {"/upload", "/upload?retry"}) {
  23594. smuggled_count = 0;
  23595. std::string request = "POST " + std::string(target) +
  23596. " HTTP/1.1\r\n"
  23597. "Host: localhost\r\n"
  23598. "Content-Length: " +
  23599. std::to_string(second_head.size()) +
  23600. "\r\n"
  23601. "\r\n" +
  23602. std::string(second_head.size(), 'A') + second_head +
  23603. inner;
  23604. std::string response;
  23605. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23606. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23607. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23608. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23609. EXPECT_EQ(0, smuggled_count.load()) << target;
  23610. }
  23611. }
  23612. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23613. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23614. // must be rejected with 400 Bad Request.
  23615. Server svr;
  23616. svr.Post("/test", [&](const Request &, Response &res) {
  23617. res.set_content("ok", "text/plain");
  23618. });
  23619. thread t = thread([&] { svr.listen(HOST, PORT); });
  23620. auto se = detail::scope_exit([&] {
  23621. svr.stop();
  23622. t.join();
  23623. ASSERT_FALSE(svr.is_running());
  23624. });
  23625. svr.wait_until_ready();
  23626. // Exact "chunked"
  23627. {
  23628. auto req = "POST /test HTTP/1.1\r\n"
  23629. "Host: localhost\r\n"
  23630. "Content-Length: 5\r\n"
  23631. "Transfer-Encoding: chunked\r\n"
  23632. "Connection: close\r\n"
  23633. "\r\n"
  23634. "hello";
  23635. std::string response;
  23636. ASSERT_TRUE(send_request(1, req, &response));
  23637. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23638. response.substr(0, response.find("\r\n")));
  23639. }
  23640. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23641. {
  23642. auto req = "POST /test HTTP/1.1\r\n"
  23643. "Host: localhost\r\n"
  23644. "Content-Length: 5\r\n"
  23645. "Transfer-Encoding: gzip, chunked\r\n"
  23646. "Connection: close\r\n"
  23647. "\r\n"
  23648. "hello";
  23649. std::string response;
  23650. ASSERT_TRUE(send_request(1, req, &response));
  23651. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23652. response.substr(0, response.find("\r\n")));
  23653. }
  23654. }
  23655. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23656. Server svr;
  23657. svr.Post("/test", [&](const Request &, Response &res) {
  23658. res.set_content("ok", "text/plain");
  23659. });
  23660. thread t = thread([&] { svr.listen(HOST, PORT); });
  23661. auto se = detail::scope_exit([&] {
  23662. svr.stop();
  23663. t.join();
  23664. ASSERT_FALSE(svr.is_running());
  23665. });
  23666. svr.wait_until_ready();
  23667. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23668. // length cannot be determined, so the server must answer 400 and close
  23669. // rather than treat the request as bodyless and leave the body in the
  23670. // socket for the next request to pick up.
  23671. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23672. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23673. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23674. std::string response;
  23675. ASSERT_TRUE(send_request(1, req, &response));
  23676. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23677. response.substr(0, response.find("\r\n")))
  23678. << transfer_encoding;
  23679. }
  23680. // RFC 9110 5.3: the codings may also be split across several
  23681. // Transfer-Encoding lines, which combine in the order they were received.
  23682. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23683. // just like the single-line "chunked, gzip" above.
  23684. {
  23685. auto req = "POST /test HTTP/1.1\r\n"
  23686. "Host: localhost\r\n"
  23687. "Transfer-Encoding: chunked\r\n"
  23688. "Transfer-Encoding: gzip\r\n"
  23689. "\r\n"
  23690. "0\r\n\r\n";
  23691. std::string response;
  23692. ASSERT_TRUE(send_request(1, req, &response));
  23693. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23694. response.substr(0, response.find("\r\n")));
  23695. }
  23696. // A sequence ending in chunked stays valid.
  23697. auto req = "POST /test HTTP/1.1\r\n"
  23698. "Host: localhost\r\n"
  23699. "Transfer-Encoding: gzip, chunked\r\n"
  23700. "Connection: close\r\n"
  23701. "\r\n"
  23702. "0\r\n\r\n";
  23703. std::string response;
  23704. ASSERT_TRUE(send_request(1, req, &response));
  23705. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23706. // ...including when it is spread over several lines.
  23707. auto split_req = "POST /test HTTP/1.1\r\n"
  23708. "Host: localhost\r\n"
  23709. "Transfer-Encoding: gzip\r\n"
  23710. "Transfer-Encoding: chunked\r\n"
  23711. "Connection: close\r\n"
  23712. "\r\n"
  23713. "0\r\n\r\n";
  23714. std::string split_response;
  23715. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23716. EXPECT_EQ("HTTP/1.1 200 OK",
  23717. split_response.substr(0, split_response.find("\r\n")));
  23718. }
  23719. // Regression for issue #2450: a DELETE without Content-Length on a
  23720. // keep-alive connection must not let the post-response drain consume the
  23721. // next request's bytes.
  23722. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23723. Server svr;
  23724. std::atomic<int> delete_count(0);
  23725. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23726. delete_count++;
  23727. res.status = StatusCode::NoContent_204;
  23728. });
  23729. auto port = svr.bind_to_any_port(HOST);
  23730. thread t = thread([&] { svr.listen_after_bind(); });
  23731. auto se = detail::scope_exit([&] {
  23732. svr.stop();
  23733. t.join();
  23734. });
  23735. svr.wait_until_ready();
  23736. auto error = Error::Success;
  23737. auto sock = detail::create_client_socket(
  23738. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23739. /*connection_timeout_sec=*/2, 0,
  23740. /*read_timeout_sec=*/2, 0,
  23741. /*write_timeout_sec=*/2, 0, std::string(), error);
  23742. ASSERT_NE(INVALID_SOCKET, sock);
  23743. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23744. auto send_request_and_read_response = [&](const std::string &req,
  23745. std::string &out) -> bool {
  23746. auto sent = send(sock, req.data(), req.size(), 0);
  23747. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23748. char buf[4096];
  23749. for (;;) {
  23750. auto n = recv(sock, buf, sizeof(buf), 0);
  23751. if (n <= 0) { return !out.empty(); }
  23752. out.append(buf, static_cast<size_t>(n));
  23753. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23754. }
  23755. };
  23756. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23757. "Host: localhost\r\n"
  23758. "\r\n";
  23759. std::string resp1;
  23760. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23761. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23762. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23763. "Host: localhost\r\n"
  23764. "Connection: close\r\n"
  23765. "\r\n";
  23766. std::string resp2;
  23767. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23768. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23769. EXPECT_EQ(2, delete_count.load());
  23770. }
  23771. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23772. Server svr;
  23773. svr.Post("/ingest", [&](const Request &, Response &res,
  23774. const ContentReader &content_reader) {
  23775. auto consumed = content_reader([](const char *, size_t) { return false; });
  23776. EXPECT_FALSE(consumed);
  23777. res.status = StatusCode::Conflict_409;
  23778. res.set_header("Connection", "close");
  23779. });
  23780. auto port = svr.bind_to_any_port(HOST);
  23781. thread t = thread([&] { svr.listen_after_bind(); });
  23782. auto se = detail::scope_exit([&] {
  23783. svr.stop();
  23784. t.join();
  23785. });
  23786. svr.wait_until_ready();
  23787. auto error = Error::Success;
  23788. auto sock = detail::create_client_socket(
  23789. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23790. /*connection_timeout_sec=*/2, 0,
  23791. /*read_timeout_sec=*/1, 0,
  23792. /*write_timeout_sec=*/2, 0, std::string(), error);
  23793. ASSERT_NE(INVALID_SOCKET, sock);
  23794. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23795. std::string request = "POST /ingest HTTP/1.1\r\n"
  23796. "Host: localhost\r\n"
  23797. "Transfer-Encoding: chunked\r\n"
  23798. "\r\n"
  23799. "4\r\n"
  23800. "data\r\n";
  23801. auto sent = send(sock, request.data(), request.size(), 0);
  23802. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23803. std::string response;
  23804. ssize_t received = 0;
  23805. do {
  23806. char buf[4096];
  23807. received = recv(sock, buf, sizeof(buf), 0);
  23808. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23809. } while (received > 0);
  23810. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23811. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23812. EXPECT_EQ(0, received);
  23813. }
  23814. namespace no_proxy_test {
  23815. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23816. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23817. // calling listen().
  23818. class ScopedServer {
  23819. public:
  23820. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23821. ~ScopedServer() {
  23822. svr_.stop();
  23823. if (th_.joinable()) { th_.join(); }
  23824. }
  23825. Server &svr() { return svr_; }
  23826. int port() const { return port_; }
  23827. void listen() {
  23828. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23829. svr_.wait_until_ready();
  23830. }
  23831. private:
  23832. Server svr_;
  23833. std::thread th_;
  23834. int port_ = 0;
  23835. };
  23836. class ProxyAndTargetServers {
  23837. public:
  23838. ProxyAndTargetServers() {
  23839. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23840. proxy_hits_++;
  23841. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23842. res.set_content("via-proxy", "text/plain");
  23843. });
  23844. target_.Get(".*", [this](const Request &req, Response &res) {
  23845. target_hits_++;
  23846. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23847. res.set_content("direct", "text/plain");
  23848. });
  23849. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23850. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23851. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23852. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23853. proxy_mock_.wait_until_ready();
  23854. target_.wait_until_ready();
  23855. }
  23856. ~ProxyAndTargetServers() {
  23857. proxy_mock_.stop();
  23858. target_.stop();
  23859. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23860. if (target_thread_.joinable()) { target_thread_.join(); }
  23861. }
  23862. Server &proxy_mock() { return proxy_mock_; }
  23863. Server &target() { return target_; }
  23864. int proxy_port() const { return proxy_port_; }
  23865. int target_port() const { return target_port_; }
  23866. int proxy_hits() const { return proxy_hits_.load(); }
  23867. int target_hits() const { return target_hits_.load(); }
  23868. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23869. void reset_counters() {
  23870. proxy_hits_ = 0;
  23871. target_hits_ = 0;
  23872. last_had_proxy_authz_ = false;
  23873. }
  23874. private:
  23875. Server proxy_mock_;
  23876. Server target_;
  23877. std::thread proxy_thread_;
  23878. std::thread target_thread_;
  23879. int proxy_port_ = 0;
  23880. int target_port_ = 0;
  23881. std::atomic<int> proxy_hits_{0};
  23882. std::atomic<int> target_hits_{0};
  23883. std::atomic<bool> last_had_proxy_authz_{false};
  23884. };
  23885. inline std::unique_ptr<Client> make_client(const std::string &host,
  23886. ProxyAndTargetServers &s) {
  23887. auto cli = detail::make_unique<Client>(host, s.target_port());
  23888. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23889. cli->set_proxy("127.0.0.1", s.proxy_port());
  23890. return cli;
  23891. }
  23892. } // namespace no_proxy_test
  23893. using no_proxy_test::make_client;
  23894. using no_proxy_test::ProxyAndTargetServers;
  23895. TEST(NoProxyTest, ExactHostnameBypasses) {
  23896. ProxyAndTargetServers s;
  23897. auto cli = make_client("example.com", s);
  23898. cli->set_no_proxy({"example.com"});
  23899. auto res = cli->Get("/");
  23900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23901. EXPECT_EQ(0, s.proxy_hits());
  23902. EXPECT_EQ(1, s.target_hits());
  23903. }
  23904. TEST(NoProxyTest, SubdomainBypasses) {
  23905. ProxyAndTargetServers s;
  23906. auto cli = make_client("foo.example.com", s);
  23907. cli->set_no_proxy({"example.com"});
  23908. auto res = cli->Get("/");
  23909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23910. EXPECT_EQ(0, s.proxy_hits());
  23911. EXPECT_EQ(1, s.target_hits());
  23912. }
  23913. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23914. // Regression guard: "evilexample.com" must not be considered a subdomain
  23915. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23916. // check would let traffic bypass the proxy and leak credentials direct
  23917. // to the attacker host.
  23918. ProxyAndTargetServers s;
  23919. auto cli = make_client("evilexample.com", s);
  23920. cli->set_no_proxy({"example.com"});
  23921. auto res = cli->Get("/");
  23922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23923. EXPECT_GE(s.proxy_hits(), 1);
  23924. EXPECT_EQ(0, s.target_hits());
  23925. }
  23926. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23927. ProxyAndTargetServers s;
  23928. auto cli = make_client("example.com.evil.com", s);
  23929. cli->set_no_proxy({"example.com"});
  23930. auto res = cli->Get("/");
  23931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23932. EXPECT_GE(s.proxy_hits(), 1);
  23933. EXPECT_EQ(0, s.target_hits());
  23934. }
  23935. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23936. ProxyAndTargetServers s;
  23937. auto cli = make_client("example.com", s);
  23938. cli->set_no_proxy({".example.com"});
  23939. auto res = cli->Get("/");
  23940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23941. EXPECT_EQ(0, s.proxy_hits());
  23942. EXPECT_EQ(1, s.target_hits());
  23943. }
  23944. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23945. ProxyAndTargetServers s;
  23946. auto cli = make_client("Example.COM", s);
  23947. cli->set_no_proxy({"EXAMPLE.com"});
  23948. auto res = cli->Get("/");
  23949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23950. EXPECT_EQ(0, s.proxy_hits());
  23951. EXPECT_EQ(1, s.target_hits());
  23952. }
  23953. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23954. ProxyAndTargetServers s;
  23955. auto cli = make_client("example.com.", s);
  23956. cli->set_no_proxy({"example.com"});
  23957. auto res = cli->Get("/");
  23958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23959. EXPECT_EQ(0, s.proxy_hits());
  23960. EXPECT_EQ(1, s.target_hits());
  23961. }
  23962. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23963. // Trailing dots must be normalized on BOTH sides — host and entry.
  23964. // An implementation that only strips the host-side trailing dot would
  23965. // fail to match host "example.com" against entry "example.com." because
  23966. // a literal substring search would compare 11 chars against 12.
  23967. ProxyAndTargetServers s;
  23968. auto cli = make_client("example.com", s);
  23969. cli->set_no_proxy({"example.com."});
  23970. auto res = cli->Get("/");
  23971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23972. EXPECT_EQ(0, s.proxy_hits());
  23973. EXPECT_EQ(1, s.target_hits());
  23974. }
  23975. TEST(NoProxyTest, WildcardBypassesEverything) {
  23976. ProxyAndTargetServers s;
  23977. auto cli = make_client("anything.invalid.test", s);
  23978. cli->set_no_proxy({"*"});
  23979. auto res = cli->Get("/");
  23980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23981. EXPECT_EQ(0, s.proxy_hits());
  23982. EXPECT_EQ(1, s.target_hits());
  23983. }
  23984. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23985. ProxyAndTargetServers s;
  23986. Client cli("127.0.0.1", s.target_port());
  23987. cli.set_proxy("127.0.0.1", s.proxy_port());
  23988. cli.set_no_proxy({"127.0.0.1"});
  23989. auto res = cli.Get("/");
  23990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23991. EXPECT_EQ(0, s.proxy_hits());
  23992. EXPECT_EQ(1, s.target_hits());
  23993. }
  23994. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23995. ProxyAndTargetServers s;
  23996. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23997. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23998. cli.set_proxy("127.0.0.1", s.proxy_port());
  23999. cli.set_no_proxy({"::1"});
  24000. auto res = cli.Get("/");
  24001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24002. EXPECT_EQ(0, s.proxy_hits());
  24003. EXPECT_EQ(1, s.target_hits());
  24004. }
  24005. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24006. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24007. // must still be recognized as IPv6 for CIDR matching. Implementations
  24008. // that detect IPv6 only when the host begins with '[' would parse the
  24009. // host as a hostname and miss the match.
  24010. ProxyAndTargetServers s;
  24011. Client cli("fe80::1", s.target_port());
  24012. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24013. cli.set_proxy("127.0.0.1", s.proxy_port());
  24014. cli.set_no_proxy({"fe80::/10"});
  24015. auto res = cli.Get("/");
  24016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24017. EXPECT_EQ(0, s.proxy_hits());
  24018. EXPECT_EQ(1, s.target_hits());
  24019. }
  24020. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24021. ProxyAndTargetServers s;
  24022. Client cli("::1", s.target_port());
  24023. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24024. cli.set_proxy("127.0.0.1", s.proxy_port());
  24025. cli.set_no_proxy({"[::1]"});
  24026. auto res = cli.Get("/");
  24027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24028. EXPECT_EQ(0, s.proxy_hits());
  24029. EXPECT_EQ(1, s.target_hits());
  24030. }
  24031. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24032. ProxyAndTargetServers s;
  24033. Client cli("fe80::1", s.target_port());
  24034. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24035. cli.set_proxy("127.0.0.1", s.proxy_port());
  24036. cli.set_no_proxy({"[fe80::]/10"});
  24037. auto res = cli.Get("/");
  24038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24039. EXPECT_EQ(0, s.proxy_hits());
  24040. EXPECT_EQ(1, s.target_hits());
  24041. }
  24042. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24043. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24044. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24045. // tricks via address-family conversion.
  24046. ProxyAndTargetServers s;
  24047. Client cli("::ffff:127.0.0.1", s.target_port());
  24048. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24049. cli.set_proxy("127.0.0.1", s.proxy_port());
  24050. cli.set_no_proxy({"127.0.0.1"});
  24051. auto res = cli.Get("/");
  24052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24053. EXPECT_GE(s.proxy_hits(), 1);
  24054. EXPECT_EQ(0, s.target_hits());
  24055. }
  24056. TEST(NoProxyTest, IPv4CidrMatch) {
  24057. ProxyAndTargetServers s;
  24058. Client cli("127.0.0.1", s.target_port());
  24059. cli.set_proxy("127.0.0.1", s.proxy_port());
  24060. cli.set_no_proxy({"127.0.0.0/8"});
  24061. auto res = cli.Get("/");
  24062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24063. EXPECT_EQ(0, s.proxy_hits());
  24064. EXPECT_EQ(1, s.target_hits());
  24065. }
  24066. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24067. ProxyAndTargetServers s;
  24068. Client cli("127.0.0.1", s.target_port());
  24069. cli.set_proxy("127.0.0.1", s.proxy_port());
  24070. cli.set_no_proxy({"10.0.0.0/8"});
  24071. auto res = cli.Get("/");
  24072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24073. EXPECT_GE(s.proxy_hits(), 1);
  24074. EXPECT_EQ(0, s.target_hits());
  24075. }
  24076. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24077. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24078. // IPv4 target matches.
  24079. ProxyAndTargetServers s;
  24080. Client cli("127.0.0.1", s.target_port());
  24081. cli.set_proxy("127.0.0.1", s.proxy_port());
  24082. cli.set_no_proxy({"0.0.0.0/0"});
  24083. auto res = cli.Get("/");
  24084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24085. EXPECT_EQ(0, s.proxy_hits());
  24086. EXPECT_EQ(1, s.target_hits());
  24087. }
  24088. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24089. ProxyAndTargetServers s;
  24090. Client cli("127.0.0.1", s.target_port());
  24091. cli.set_proxy("127.0.0.1", s.proxy_port());
  24092. cli.set_no_proxy({"127.0.0.1"});
  24093. auto res = cli.Get("/");
  24094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24095. EXPECT_EQ(0, s.proxy_hits());
  24096. EXPECT_EQ(1, s.target_hits());
  24097. }
  24098. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24099. ProxyAndTargetServers s;
  24100. Client cli("127.0.0.1", s.target_port());
  24101. cli.set_proxy("127.0.0.1", s.proxy_port());
  24102. cli.set_no_proxy({"127.0.0.0/33"});
  24103. auto res = cli.Get("/");
  24104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24105. EXPECT_GE(s.proxy_hits(), 1);
  24106. EXPECT_EQ(0, s.target_hits());
  24107. }
  24108. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24109. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24110. ProxyAndTargetServers s;
  24111. Client cli("127.0.0.1", s.target_port());
  24112. cli.set_proxy("127.0.0.1", s.proxy_port());
  24113. cli.set_no_proxy({"127.0.0.1/"});
  24114. auto res = cli.Get("/");
  24115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24116. EXPECT_GE(s.proxy_hits(), 1);
  24117. EXPECT_EQ(0, s.target_hits());
  24118. }
  24119. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24120. ProxyAndTargetServers s;
  24121. auto cli = make_client("internal.corp", s);
  24122. cli->set_proxy_basic_auth("u", "p");
  24123. cli->set_no_proxy({"internal.corp"});
  24124. auto res = cli->Get("/");
  24125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24126. EXPECT_EQ(1, s.target_hits());
  24127. EXPECT_EQ(0, s.proxy_hits());
  24128. EXPECT_FALSE(s.last_had_proxy_authz())
  24129. << "Proxy-Authorization must not be sent direct to the target";
  24130. }
  24131. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24132. ProxyAndTargetServers s;
  24133. auto cli = make_client("public.example", s);
  24134. cli->set_proxy_basic_auth("u", "p");
  24135. cli->set_no_proxy({"internal.corp"}); // does not match
  24136. auto res = cli->Get("/");
  24137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24138. EXPECT_GE(s.proxy_hits(), 1);
  24139. EXPECT_TRUE(s.last_had_proxy_authz());
  24140. }
  24141. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24142. std::atomic<int> hits{0};
  24143. std::atomic<int> hits_with_authz{0};
  24144. no_proxy_test::ScopedServer proxy_mock;
  24145. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24146. hits++;
  24147. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24148. if (req.target.find("/redir") != std::string::npos) {
  24149. res.set_redirect("http://other.example/landed");
  24150. } else {
  24151. res.set_content("via-proxy", "text/plain");
  24152. }
  24153. });
  24154. proxy_mock.listen();
  24155. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24156. hits = 0;
  24157. hits_with_authz = 0;
  24158. Client cli("public.example", 80);
  24159. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24160. cli.set_proxy_basic_auth(c.first, c.second);
  24161. cli.set_follow_location(true);
  24162. // The redirect to another host goes through the proxy as well
  24163. auto res = cli.Get("/redir");
  24164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24165. EXPECT_EQ(2, hits.load());
  24166. EXPECT_EQ(2, hits_with_authz.load());
  24167. }
  24168. }
  24169. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24170. ProxyAndTargetServers s;
  24171. auto cli = make_client("anything.test", s);
  24172. auto res = cli->Get("/");
  24173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24174. EXPECT_GE(s.proxy_hits(), 1);
  24175. EXPECT_EQ(0, s.target_hits());
  24176. }
  24177. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24178. ProxyAndTargetServers s;
  24179. auto cli = make_client("example.com", s);
  24180. cli->set_no_proxy({"example.com:8080"});
  24181. auto res = cli->Get("/");
  24182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24183. EXPECT_GE(s.proxy_hits(), 1);
  24184. EXPECT_EQ(0, s.target_hits());
  24185. }
  24186. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24187. ProxyAndTargetServers s;
  24188. auto cli = make_client("anything.test", s);
  24189. cli->set_no_proxy({"", " ", "\t"});
  24190. auto res = cli->Get("/");
  24191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24192. EXPECT_GE(s.proxy_hits(), 1);
  24193. EXPECT_EQ(0, s.target_hits());
  24194. }
  24195. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24196. // An entry with leading/trailing whitespace must still match — env-style
  24197. // values are commonly pasted with stray spaces and an implementation
  24198. // that feeds the raw token directly to inet_pton would fail to match
  24199. // valid CIDRs because of the spaces.
  24200. ProxyAndTargetServers s;
  24201. Client cli("127.0.0.1", s.target_port());
  24202. cli.set_proxy("127.0.0.1", s.proxy_port());
  24203. cli.set_no_proxy({" 127.0.0.0/8 "});
  24204. auto res = cli.Get("/");
  24205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24206. EXPECT_EQ(0, s.proxy_hits());
  24207. EXPECT_EQ(1, s.target_hits());
  24208. }
  24209. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24210. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24211. // go direct and must NOT carry Proxy-Authorization.
  24212. std::atomic<int> proxy_hits{0};
  24213. std::atomic<int> target_hits{0};
  24214. std::atomic<bool> target_saw_authz{false};
  24215. no_proxy_test::ScopedServer proxy_mock, target;
  24216. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24217. proxy_hits++;
  24218. res.status = 302;
  24219. res.set_header("Location", "http://127.0.0.1:" +
  24220. std::to_string(target.port()) + "/landed");
  24221. });
  24222. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24223. target_hits++;
  24224. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24225. res.set_content("direct", "text/plain");
  24226. });
  24227. proxy_mock.listen();
  24228. target.listen();
  24229. Client cli("public.example", target.port());
  24230. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24231. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24232. cli.set_proxy_basic_auth("u", "p");
  24233. cli.set_no_proxy({"127.0.0.1"});
  24234. cli.set_follow_location(true);
  24235. auto res = cli.Get("/redir");
  24236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24237. EXPECT_GE(proxy_hits.load(), 1);
  24238. EXPECT_GE(target_hits.load(), 1);
  24239. EXPECT_FALSE(target_saw_authz.load());
  24240. }
  24241. #ifdef CPPHTTPLIB_SSL_ENABLED
  24242. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24243. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24244. // proxy creds would be sent to the (possibly hostile) origin.
  24245. std::atomic<int> target_hits{0};
  24246. std::atomic<bool> target_saw_proxy_authz{false};
  24247. no_proxy_test::ScopedServer target;
  24248. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24249. target_hits++;
  24250. if (req.has_header("Proxy-Authorization")) {
  24251. target_saw_proxy_authz = true;
  24252. }
  24253. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24254. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24255. "nonce=\"abc\", algorithm=MD5");
  24256. });
  24257. target.listen();
  24258. // The proxy address is set to the target's port: the bypass MUST kick in;
  24259. // if it doesn't, the test still routes "via proxy" to the same server and
  24260. // the Proxy-Authorization assertion below catches the leak.
  24261. Client cli("evil.example", target.port());
  24262. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24263. cli.set_proxy("127.0.0.1", target.port());
  24264. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24265. cli.set_no_proxy({"evil.example"});
  24266. auto res = cli.Get("/x");
  24267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24268. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24269. EXPECT_EQ(1, target_hits.load());
  24270. EXPECT_FALSE(target_saw_proxy_authz.load());
  24271. }
  24272. #endif
  24273. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24274. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24275. std::atomic<int> proxy_hits{0};
  24276. std::atomic<int> bypass_hits{0};
  24277. std::atomic<bool> proxy_saw_c_url{false};
  24278. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24279. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24280. proxy_hits++;
  24281. if (req.path.find("/start") != std::string::npos) {
  24282. res.status = 302;
  24283. res.set_header("Location", "http://127.0.0.1:" +
  24284. std::to_string(bypass_server.port()) +
  24285. "/middle");
  24286. return;
  24287. }
  24288. if (req.path.find("/end") != std::string::npos) {
  24289. proxy_saw_c_url = true;
  24290. res.set_content("c-via-proxy", "text/plain");
  24291. return;
  24292. }
  24293. res.set_content("unexpected", "text/plain");
  24294. });
  24295. // public.example's "advertised" port is arbitrary (the request never lands
  24296. // there — it goes through the proxy), but use a dynamic value to stay
  24297. // friendly with sharded parallel runs.
  24298. int public_port = bypass_server.port();
  24299. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24300. bypass_hits++;
  24301. res.status = 302;
  24302. res.set_header("Location", "http://public.example:" +
  24303. std::to_string(public_port) + "/end");
  24304. });
  24305. proxy_mock.listen();
  24306. bypass_server.listen();
  24307. Client cli("public.example", public_port);
  24308. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24309. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24310. cli.set_no_proxy({"127.0.0.1"});
  24311. cli.set_follow_location(true);
  24312. auto res = cli.Get("/start");
  24313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24314. EXPECT_EQ(StatusCode::OK_200, res->status);
  24315. EXPECT_EQ("c-via-proxy", res->body);
  24316. EXPECT_GE(proxy_hits.load(), 2);
  24317. EXPECT_GE(bypass_hits.load(), 1);
  24318. EXPECT_TRUE(proxy_saw_c_url.load());
  24319. }
  24320. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24321. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24322. // request reconnects to the correct endpoint.
  24323. std::atomic<int> proxy_hits{0};
  24324. std::atomic<int> target_hits{0};
  24325. no_proxy_test::ScopedServer proxy_mock, target;
  24326. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24327. proxy_hits++;
  24328. res.set_content("via-proxy", "text/plain");
  24329. });
  24330. target.svr().Get(".*", [&](const Request &, Response &res) {
  24331. target_hits++;
  24332. res.set_content("direct", "text/plain");
  24333. });
  24334. proxy_mock.listen();
  24335. target.listen();
  24336. Client cli("public.example", target.port());
  24337. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24338. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24339. cli.set_keep_alive(true);
  24340. auto res1 = cli.Get("/a");
  24341. ASSERT_TRUE(res1);
  24342. EXPECT_EQ("via-proxy", res1->body);
  24343. EXPECT_EQ(1, proxy_hits.load());
  24344. EXPECT_EQ(0, target_hits.load());
  24345. cli.set_no_proxy({"public.example"});
  24346. auto res2 = cli.Get("/b");
  24347. ASSERT_TRUE(res2);
  24348. EXPECT_EQ("direct", res2->body);
  24349. EXPECT_EQ(1, proxy_hits.load());
  24350. EXPECT_EQ(1, target_hits.load());
  24351. }
  24352. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24353. namespace proxy_tunnel_test {
  24354. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24355. class ScopedSSLServer {
  24356. public:
  24357. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24358. port_ = svr_.bind_to_any_port("127.0.0.1");
  24359. }
  24360. ~ScopedSSLServer() {
  24361. svr_.stop();
  24362. if (th_.joinable()) { th_.join(); }
  24363. }
  24364. SSLServer &svr() { return svr_; }
  24365. int port() const { return port_; }
  24366. void listen() {
  24367. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24368. svr_.wait_until_ready();
  24369. }
  24370. private:
  24371. SSLServer svr_;
  24372. std::thread th_;
  24373. int port_ = 0;
  24374. };
  24375. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24376. class ScopedConnectProxy {
  24377. public:
  24378. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24379. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24380. if (listen_fd_ < 0) { return; }
  24381. int yes = 1;
  24382. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24383. sockaddr_in a{};
  24384. a.sin_family = AF_INET;
  24385. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24386. a.sin_port = 0;
  24387. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24388. return;
  24389. }
  24390. socklen_t alen = sizeof(a);
  24391. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24392. 0) {
  24393. return;
  24394. }
  24395. port_ = ntohs(a.sin_port);
  24396. if (::listen(listen_fd_, 1) != 0) { return; }
  24397. th_ = std::thread([this] { run(); });
  24398. }
  24399. ~ScopedConnectProxy() {
  24400. stop_ = true;
  24401. if (listen_fd_ >= 0) {
  24402. ::shutdown(listen_fd_, SHUT_RDWR);
  24403. ::close(listen_fd_);
  24404. }
  24405. if (th_.joinable()) { th_.join(); }
  24406. }
  24407. int port() const { return port_; }
  24408. int connect_hits() const { return connect_hits_.load(); }
  24409. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24410. std::string connect_request() const {
  24411. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24412. return connect_request_;
  24413. }
  24414. private:
  24415. void run() {
  24416. while (!stop_.load()) {
  24417. fd_set rfds;
  24418. FD_ZERO(&rfds);
  24419. FD_SET(listen_fd_, &rfds);
  24420. timeval tv{0, 100 * 1000};
  24421. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24422. if (sel <= 0) { continue; }
  24423. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24424. if (client_fd < 0) { continue; }
  24425. std::string req;
  24426. char buf[2048];
  24427. while (req.find("\r\n\r\n") == std::string::npos) {
  24428. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24429. if (n <= 0) { break; }
  24430. req.append(buf, static_cast<size_t>(n));
  24431. }
  24432. if (req.compare(0, 7, "CONNECT") != 0) {
  24433. ::close(client_fd);
  24434. continue;
  24435. }
  24436. connect_hits_++;
  24437. {
  24438. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24439. connect_request_ = req;
  24440. }
  24441. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24442. ::send(client_fd, ok, std::strlen(ok), 0);
  24443. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24444. sockaddr_in o{};
  24445. o.sin_family = AF_INET;
  24446. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24447. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24448. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24449. 0) {
  24450. ::close(client_fd);
  24451. ::close(origin_fd);
  24452. continue;
  24453. }
  24454. auto forward = [](int from, int to) {
  24455. char b[8192];
  24456. for (;;) {
  24457. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24458. if (n <= 0) { break; }
  24459. ssize_t off = 0;
  24460. while (off < n) {
  24461. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24462. if (s <= 0) {
  24463. off = n;
  24464. break;
  24465. }
  24466. off += s;
  24467. }
  24468. }
  24469. ::shutdown(to, SHUT_WR);
  24470. };
  24471. std::thread t1([&] { forward(client_fd, origin_fd); });
  24472. std::thread t2([&] { forward(origin_fd, client_fd); });
  24473. t1.join();
  24474. t2.join();
  24475. ::close(client_fd);
  24476. ::close(origin_fd);
  24477. }
  24478. }
  24479. int forward_port_ = -1;
  24480. int listen_fd_ = -1;
  24481. int port_ = 0;
  24482. std::thread th_;
  24483. std::atomic<bool> stop_{false};
  24484. std::atomic<int> connect_hits_{0};
  24485. mutable std::mutex connect_request_mutex_;
  24486. std::string connect_request_;
  24487. };
  24488. // Sends one request through the CONNECT proxy to the TLS origin with a
  24489. // credential configured for each hop, and checks that each credential reaches
  24490. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24491. // origin's (every header in origin_headers) on the tunnelled request.
  24492. void CredentialsStayWithTheirHop(
  24493. const std::function<void(SSLClient &)> &set_credentials,
  24494. const std::string &scheme,
  24495. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24496. std::atomic<int> origin_hits{0};
  24497. std::atomic<bool> origin_saw_proxy_authz{false};
  24498. std::atomic<bool> origin_saw_headers{false};
  24499. ScopedSSLServer origin;
  24500. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24501. origin_hits++;
  24502. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24503. origin_saw_headers =
  24504. std::all_of(origin_headers.begin(), origin_headers.end(),
  24505. [&](const std::string &h) { return req.has_header(h); });
  24506. res.set_content("ok", "text/plain");
  24507. });
  24508. origin.listen();
  24509. ScopedConnectProxy proxy(origin.port());
  24510. ASSERT_NE(0, proxy.port());
  24511. // Pinned to 127.0.0.1 for the same reason as the test below.
  24512. SSLClient cli("127.0.0.1", origin.port());
  24513. cli.enable_server_certificate_verification(false);
  24514. cli.set_proxy("127.0.0.1", proxy.port());
  24515. set_credentials(cli);
  24516. auto res = cli.Get("/x");
  24517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24518. EXPECT_EQ(StatusCode::OK_200, res->status);
  24519. EXPECT_EQ(1, origin_hits.load());
  24520. EXPECT_EQ(1, proxy.connect_hits());
  24521. EXPECT_TRUE(origin_saw_headers.load());
  24522. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24523. << "Proxy-Authorization must not be sent inside the tunnel";
  24524. auto connect_req = proxy.connect_request();
  24525. EXPECT_NE(std::string::npos,
  24526. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24527. for (const auto &h : origin_headers) {
  24528. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24529. << h << " must not be sent to the proxy on CONNECT";
  24530. }
  24531. }
  24532. } // namespace proxy_tunnel_test
  24533. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24534. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24535. [](SSLClient &cli) {
  24536. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24537. cli.set_basic_auth("origin-user", "origin-pass");
  24538. },
  24539. "Basic");
  24540. }
  24541. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24542. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24543. [](SSLClient &cli) {
  24544. cli.set_proxy_bearer_token_auth("proxy-token");
  24545. cli.set_bearer_token_auth("origin-token");
  24546. },
  24547. "Bearer");
  24548. }
  24549. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24550. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24551. [](SSLClient &cli) {
  24552. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24553. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24554. {"Cookie", "sid=origin-session"},
  24555. {"X-Api-Key", "origin-key"}});
  24556. },
  24557. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24558. }
  24559. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24560. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24561. // retry; otherwise proxy creds would be sent to the origin.
  24562. std::atomic<int> origin_hits{0};
  24563. std::atomic<bool> origin_saw_proxy_authz{false};
  24564. proxy_tunnel_test::ScopedSSLServer origin;
  24565. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24566. origin_hits++;
  24567. if (req.has_header("Proxy-Authorization")) {
  24568. origin_saw_proxy_authz = true;
  24569. }
  24570. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24571. res.set_header("Proxy-Authenticate",
  24572. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24573. "algorithm=MD5");
  24574. });
  24575. origin.listen();
  24576. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24577. ASSERT_NE(0, proxy.port());
  24578. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24579. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24580. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24581. // and answer with its own status, making this test flaky.
  24582. SSLClient cli("127.0.0.1", origin.port());
  24583. cli.enable_server_certificate_verification(false);
  24584. cli.set_proxy("127.0.0.1", proxy.port());
  24585. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24586. auto res = cli.Get("/x");
  24587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24588. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24589. EXPECT_EQ(1, origin_hits.load());
  24590. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24591. EXPECT_EQ(1, proxy.connect_hits());
  24592. }
  24593. #endif