test.cc 914 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. } // namespace detail
  480. } // namespace httplib
  481. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  482. struct {
  483. const char *line;
  484. const char *version;
  485. int status;
  486. const char *reason;
  487. } cases[] = {
  488. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  489. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  490. // The reason phrase may be empty, or left out along with its space.
  491. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  492. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  493. };
  494. for (const auto &c : cases) {
  495. std::string version;
  496. int status = 0;
  497. std::string reason = "unset";
  498. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  499. << c.line;
  500. EXPECT_EQ(c.version, version);
  501. EXPECT_EQ(c.status, status);
  502. EXPECT_EQ(c.reason, reason);
  503. }
  504. }
  505. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  506. const char *lines[] = {
  507. "HTTP/2 200 OK\r\n",
  508. "HTTP/1.2 200 OK\r\n",
  509. "HTTP/1.1 20 OK\r\n",
  510. "HTTP/1.1 2000 OK\r\n",
  511. "HTTP/1.1 2x0 OK\r\n",
  512. "HTTP/1.1 200 OK\r\n",
  513. "HTTP/1.1 200OK\r\n",
  514. "HTTP/1.1 200 O\rK\r\n",
  515. "HTTP/1.1 200 OK",
  516. "HTTP/1.1 200 OK\r\nX",
  517. "",
  518. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  519. "HTTP/1.1 200 OK\n",
  520. #endif
  521. };
  522. for (auto line : lines) {
  523. std::string version;
  524. int status = 0;
  525. std::string reason;
  526. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  527. << line;
  528. }
  529. }
  530. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  531. // Long enough to overflow the stack when matched with std::regex.
  532. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  533. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  538. EXPECT_EQ(200, status);
  539. EXPECT_EQ(long_reason, reason);
  540. }
  541. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  542. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  543. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  544. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  545. EXPECT_EQ("", detail::file_extension("noext"));
  546. EXPECT_EQ("", detail::file_extension("a."));
  547. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  548. EXPECT_EQ("", detail::file_extension("a.b-c"));
  549. // Long enough to overflow the stack when matched with std::regex.
  550. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  551. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  552. }
  553. // Forward declaration: in split builds split.py strips `inline` and moves the
  554. // definition into httplib.cc, so detail::base64_encode is not visible from the
  555. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  556. // in both header-only and split builds.
  557. namespace httplib {
  558. namespace detail {
  559. std::string base64_encode(const std::string &in);
  560. } // namespace detail
  561. } // namespace httplib
  562. TEST(Base64EncodeTest, KnownAnswers) {
  563. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  564. // where the accumulator's top bit is already set before the next shift.
  565. EXPECT_EQ("", detail::base64_encode(""));
  566. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  567. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  568. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  569. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  570. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  571. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  572. // High bytes keep the top bit set across several rounds.
  573. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  574. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  575. }
  576. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  577. string unescapedCharacters = "-_.!~*'()";
  578. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  579. }
  580. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  581. string reservedCharacters = ";,/?:@&=+$";
  582. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  583. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  584. }
  585. TEST(ClientQueryOrder, PreserveOrder) {
  586. // This test reproduces Issue #2259: client may reorder query parameters
  587. // when sending a GET request. The expected behavior is that the client
  588. // preserves the original query string order when the caller supplied it
  589. // as part of the path.
  590. Server svr;
  591. svr.Get("/", [&](const Request &req, Response &res) {
  592. // Echo back the raw target so the test can assert ordering
  593. res.set_content(req.target, "text/plain");
  594. });
  595. std::thread t{[&] { svr.listen(HOST, PORT); }};
  596. auto se = detail::scope_exit([&] {
  597. svr.stop();
  598. t.join();
  599. ASSERT_FALSE(svr.is_running());
  600. });
  601. svr.wait_until_ready();
  602. Client cli(HOST, PORT);
  603. ASSERT_TRUE(cli.is_valid());
  604. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  605. auto res = cli.Get(original);
  606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  607. // Expect the echoed target to exactly match the original path (order
  608. // preserved)
  609. EXPECT_EQ(res->body, original);
  610. }
  611. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  612. string chineseCharacters = U8("中国語");
  613. string russianCharacters = U8("дом");
  614. string brazilianCharacters = U8("óculos");
  615. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  616. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  617. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  618. "%D0%B4%D0%BE%D0%BC");
  619. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  620. }
  621. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  622. string unescapedCharacters = "-_.!~*'()";
  623. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  624. }
  625. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  626. string reservedCharacters = ";,/?:@&=+$";
  627. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  628. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  629. }
  630. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  631. string chineseCharacters = U8("中国語");
  632. string russianCharacters = U8("дом");
  633. string brazilianCharacters = U8("óculos");
  634. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  635. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  636. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  637. "%D0%B4%D0%BE%D0%BC");
  638. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  639. }
  640. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  641. // Issue #2082 use case: encoding path component with ampersand
  642. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  643. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  644. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  645. }
  646. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  647. string unescapedCharacters = "-_.!~*'()";
  648. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  649. }
  650. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  651. string reservedCharacters = ";,/?:@&=+$#";
  652. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  653. }
  654. TEST(EncodeUriTest, TestUTF8Characters) {
  655. string chineseCharacters = U8("中国語");
  656. string russianCharacters = U8("дом");
  657. string brazilianCharacters = U8("óculos");
  658. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  659. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  660. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  661. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  662. }
  663. TEST(EncodeUriTest, TestCompleteUri) {
  664. string uri =
  665. "https://example.com/path/to/resource?query=value&param=test#fragment";
  666. EXPECT_EQ(
  667. httplib::encode_uri(uri),
  668. "https://example.com/path/to/resource?query=value&param=test#fragment");
  669. }
  670. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  671. string uri =
  672. "https://example.com/path with spaces/file name.html?q=hello world";
  673. EXPECT_EQ(httplib::encode_uri(uri),
  674. "https://example.com/path%20with%20spaces/"
  675. "file%20name.html?q=hello%20world");
  676. }
  677. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  678. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  679. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  680. }
  681. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  682. string unescapedCharacters = "-_.!~*'()";
  683. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  684. }
  685. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  686. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  687. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  688. string encodedBrazilian = "%C3%B3culos";
  689. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  690. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  691. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  692. }
  693. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  694. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  695. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  696. "Piri Tommy Villiers - on & on");
  697. }
  698. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  699. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  700. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  701. }
  702. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  703. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  704. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  705. }
  706. TEST(DecodeUriTest, TestUTF8Characters) {
  707. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  708. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  709. string encodedBrazilian = "%C3%B3culos";
  710. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  711. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  712. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  713. }
  714. TEST(DecodeUriTest, TestCompleteUri) {
  715. string encodedUri = "https://example.com/path%20with%20spaces/"
  716. "file%20name.html?q=hello%20world";
  717. EXPECT_EQ(
  718. httplib::decode_uri(encodedUri),
  719. "https://example.com/path with spaces/file name.html?q=hello world");
  720. }
  721. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  722. string original =
  723. "https://example.com/path with spaces/file name.html?q=hello world";
  724. string encoded = httplib::encode_uri(original);
  725. string decoded = httplib::decode_uri(encoded);
  726. EXPECT_EQ(decoded, original);
  727. }
  728. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  729. // decode_uri is the inverse of encode_uri: an escaped reserved character
  730. // stays encoded so it is not promoted into a real delimiter, while
  731. // non-reserved escapes still decode (like JS decodeURI).
  732. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  733. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  734. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  735. "%3F%3A%40%26%3D%2B%24%2C%3B");
  736. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  737. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  738. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  739. "http://example.com/a%2Fb");
  740. // decode_uri_component still decodes the reserved character.
  741. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  742. }
  743. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  744. string original = "Piri Tommy Villiers - on & on";
  745. string encoded = httplib::encode_uri_component(original);
  746. string decoded = httplib::decode_uri_component(encoded);
  747. EXPECT_EQ(decoded, original);
  748. }
  749. TEST(TrimTests, TrimStringTests) {
  750. EXPECT_EQ("abc", detail::trim_copy("abc"));
  751. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  752. EXPECT_TRUE(detail::trim_copy("").empty());
  753. }
  754. TEST(AsciiTest, LocaleIndependentClassification) {
  755. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  756. // which consult the global C locale: std::isalnum(0xC5) can return true
  757. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  758. // helpers must classify every byte by the ASCII grammar alone.
  759. for (int i = 0; i < 256; i++) {
  760. auto c = static_cast<char>(i);
  761. auto is_digit = i >= '0' && i <= '9';
  762. auto is_upper = i >= 'A' && i <= 'Z';
  763. auto is_lower = i >= 'a' && i <= 'z';
  764. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  765. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  766. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  767. << "byte " << i;
  768. }
  769. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  770. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  771. // Non-ASCII bytes must be percent-encoded, never passed through as
  772. // alphanumeric.
  773. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  774. }
  775. TEST(FromCharsTest, Double) {
  776. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  777. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  778. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  779. auto parse = [](const std::string &s, double &v) {
  780. return detail::from_chars(s.data(), s.data() + s.size(), v);
  781. };
  782. double v = -1.0;
  783. // Representative quality values.
  784. EXPECT_EQ(parse("0", v).ec, std::errc{});
  785. EXPECT_DOUBLE_EQ(v, 0.0);
  786. EXPECT_EQ(parse("1", v).ec, std::errc{});
  787. EXPECT_DOUBLE_EQ(v, 1.0);
  788. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  789. EXPECT_DOUBLE_EQ(v, 0.8);
  790. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  791. EXPECT_DOUBLE_EQ(v, 0.001);
  792. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  793. EXPECT_DOUBLE_EQ(v, 1.0);
  794. // A missing integer or fractional part is tolerated.
  795. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  796. EXPECT_DOUBLE_EQ(v, 0.5);
  797. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  798. EXPECT_DOUBLE_EQ(v, 5.0);
  799. // Values outside [0, 1] still parse; the caller range-checks them.
  800. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  801. EXPECT_DOUBLE_EQ(v, 123.456);
  802. // Stops at the first byte that is not part of the number and reports where.
  803. std::string trailing = "0.9, text/html";
  804. auto r = parse(trailing, v);
  805. EXPECT_EQ(r.ec, std::errc{});
  806. EXPECT_DOUBLE_EQ(v, 0.9);
  807. EXPECT_EQ(*r.ptr, ',');
  808. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  809. // outright, and an 'e'/'E' simply ends the number.
  810. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  811. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  812. std::string exp_input = "1.5e3";
  813. r = parse(exp_input, v);
  814. EXPECT_EQ(r.ec, std::errc{});
  815. EXPECT_DOUBLE_EQ(v, 1.5);
  816. EXPECT_EQ(*r.ptr, 'e');
  817. // Invalid inputs.
  818. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  819. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  820. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  821. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  822. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  823. // Pathological but well-formed inputs must stay bounded (no overflow, no
  824. // out-of-bounds table access) and stay within [0, 1] for the caller.
  825. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  826. std::errc{});
  827. EXPECT_DOUBLE_EQ(v, 0.0);
  828. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  829. std::errc{});
  830. EXPECT_GE(v, 0.0);
  831. EXPECT_LE(v, 1.0);
  832. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  833. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  834. }
  835. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  836. // Simple case without quality values
  837. std::vector<std::string> result1;
  838. EXPECT_TRUE(detail::parse_accept_header(
  839. "text/html,application/json,text/plain", result1));
  840. EXPECT_EQ(result1.size(), 3U);
  841. EXPECT_EQ(result1[0], "text/html");
  842. EXPECT_EQ(result1[1], "application/json");
  843. EXPECT_EQ(result1[2], "text/plain");
  844. // With quality values
  845. std::vector<std::string> result2;
  846. EXPECT_TRUE(detail::parse_accept_header(
  847. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  848. EXPECT_EQ(result2.size(), 3U);
  849. EXPECT_EQ(result2[0], "application/json"); // highest q value
  850. EXPECT_EQ(result2[1], "text/html");
  851. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  852. }
  853. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  854. // Mixed with and without quality values
  855. std::vector<std::string> result;
  856. EXPECT_TRUE(detail::parse_accept_header(
  857. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  858. EXPECT_EQ(result.size(), 3U);
  859. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  860. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  861. EXPECT_EQ(result[2], "application/json"); // q=0.5
  862. }
  863. TEST(ParseAcceptHeaderTest, EdgeCases) {
  864. // Empty header
  865. std::vector<std::string> empty_result;
  866. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  867. EXPECT_TRUE(empty_result.empty());
  868. // Single type
  869. std::vector<std::string> single_result;
  870. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  871. EXPECT_EQ(single_result.size(), 1U);
  872. EXPECT_EQ(single_result[0], "application/json");
  873. // Wildcard types
  874. std::vector<std::string> wildcard_result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  877. EXPECT_EQ(wildcard_result.size(), 3U);
  878. EXPECT_EQ(wildcard_result[0], "application/json");
  879. EXPECT_EQ(wildcard_result[1], "text/*");
  880. EXPECT_EQ(wildcard_result[2], "*/*");
  881. }
  882. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  883. // Common browser Accept header
  884. std::vector<std::string> browser_result;
  885. EXPECT_TRUE(
  886. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  887. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  888. browser_result));
  889. EXPECT_EQ(browser_result.size(), 6U);
  890. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  891. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  892. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  893. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  894. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  895. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  896. // API client header
  897. std::vector<std::string> api_result;
  898. EXPECT_TRUE(detail::parse_accept_header(
  899. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  900. api_result));
  901. EXPECT_EQ(api_result.size(), 3U);
  902. EXPECT_EQ(api_result[0], "application/json");
  903. EXPECT_EQ(api_result[1], "application/xml");
  904. EXPECT_EQ(api_result[2], "text/plain");
  905. }
  906. TEST(ParseAcceptHeaderTest, SpecialCases) {
  907. // Quality value with 3 decimal places
  908. std::vector<std::string> decimal_result;
  909. EXPECT_TRUE(detail::parse_accept_header(
  910. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  911. EXPECT_EQ(decimal_result.size(), 2U);
  912. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  913. EXPECT_EQ(decimal_result[1], "text/html");
  914. // Zero quality (should still be included but with lowest priority)
  915. std::vector<std::string> zero_q_result;
  916. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  917. zero_q_result));
  918. EXPECT_EQ(zero_q_result.size(), 2U);
  919. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  920. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  921. // No spaces around commas
  922. std::vector<std::string> no_space_result;
  923. EXPECT_TRUE(detail::parse_accept_header(
  924. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  925. no_space_result));
  926. EXPECT_EQ(no_space_result.size(), 3U);
  927. EXPECT_EQ(no_space_result[0], "text/html");
  928. EXPECT_EQ(no_space_result[1], "application/json");
  929. EXPECT_EQ(no_space_result[2], "text/plain");
  930. }
  931. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  932. // Quality values always use '.' as the decimal separator, so parsing must
  933. // not depend on the process locale. An embedding application may have
  934. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  935. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  936. std::string saved = cur ? cur : "C";
  937. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  938. "fr_FR.UTF-8"};
  939. bool switched = false;
  940. for (const auto loc : comma_locales) {
  941. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  942. std::localeconv()->decimal_point[0] == ',') {
  943. switched = true;
  944. break;
  945. }
  946. }
  947. if (!switched) {
  948. std::setlocale(LC_NUMERIC, saved.c_str());
  949. GTEST_SKIP() << "no comma-decimal locale available on this host";
  950. }
  951. // The higher-weighted type appears later in the list, so a correct parse
  952. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  953. // sensitive parse reads both weights as 0 and leaves the original order.
  954. std::vector<std::string> result;
  955. EXPECT_TRUE(detail::parse_accept_header(
  956. "application/json;q=0.1,text/html;q=0.9", result));
  957. ASSERT_EQ(result.size(), 2U);
  958. EXPECT_EQ(result[0], "text/html");
  959. EXPECT_EQ(result[1], "application/json");
  960. std::setlocale(LC_NUMERIC, saved.c_str());
  961. }
  962. TEST(ParseAcceptHeaderTest, InvalidCases) {
  963. std::vector<std::string> result;
  964. // Invalid quality value (> 1.0)
  965. EXPECT_FALSE(
  966. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  967. // Invalid quality value (< 0.0)
  968. EXPECT_FALSE(
  969. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  970. // Invalid quality value (not a number)
  971. EXPECT_FALSE(detail::parse_accept_header(
  972. "text/html;q=invalid,application/json", result));
  973. // A valid numeric prefix does not make the entire quality value valid.
  974. EXPECT_FALSE(detail::parse_accept_header(
  975. "text/html;q=0.5junk,application/json", result));
  976. // Empty quality value
  977. EXPECT_FALSE(
  978. detail::parse_accept_header("text/html;q=,application/json", result));
  979. // Invalid media type format (no slash and not wildcard)
  980. EXPECT_FALSE(
  981. detail::parse_accept_header("invalidtype,application/json", result));
  982. // Valid cases should still work
  983. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  984. EXPECT_EQ(result.size(), 1U);
  985. EXPECT_EQ(result[0], "*/*");
  986. EXPECT_TRUE(detail::parse_accept_header("*", result));
  987. EXPECT_EQ(result.size(), 1U);
  988. EXPECT_EQ(result[0], "*");
  989. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  990. EXPECT_EQ(result.size(), 1U);
  991. EXPECT_EQ(result[0], "text/*");
  992. }
  993. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  994. // elements, so a leading, trailing or doubled comma is a legal Accept value
  995. // and must not be answered with 400 Bad Request.
  996. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  997. struct {
  998. const char *value;
  999. std::vector<std::string> expected;
  1000. } cases[] = {
  1001. {",application/json", {"application/json"}},
  1002. {"text/html,", {"text/html"}},
  1003. {"text/html,,*/*", {"text/html", "*/*"}},
  1004. // An empty element may be spelled with whitespace in it
  1005. {"text/html, , application/json", {"text/html", "application/json"}},
  1006. // Nothing but empty elements is an empty list, which means the same
  1007. // thing as no Accept header at all
  1008. {",,,", {}},
  1009. // Quality values still apply across ignored empty elements
  1010. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1011. };
  1012. for (const auto &c : cases) {
  1013. std::vector<std::string> result;
  1014. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1015. << "value: " << c.value;
  1016. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1017. }
  1018. // An invalid entry is still rejected when empty elements surround it
  1019. std::vector<std::string> result;
  1020. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1021. }
  1022. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1023. // or ';' inside one does not end the list element or the parameter. Section
  1024. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1025. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1026. struct {
  1027. const char *value;
  1028. std::vector<std::string> expected;
  1029. } cases[] = {
  1030. {"text/html;profile=\"a,b\",application/json",
  1031. {"text/html", "application/json"}},
  1032. // A "q=" inside a quoted value is not the weight
  1033. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1034. {"text/html", "application/json"}},
  1035. // The weight after a quoted value still applies
  1036. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1037. {"application/json", "text/html"}},
  1038. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1039. {"application/json", "text/html"}},
  1040. {"text/html;profile=\"a\\\"b\",application/json",
  1041. {"text/html", "application/json"}},
  1042. // An escaped backslash does not escape the '"' after it
  1043. {"text/html;profile=\"a\\\\\",application/json",
  1044. {"text/html", "application/json"}},
  1045. };
  1046. for (const auto &c : cases) {
  1047. std::vector<std::string> result;
  1048. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1049. << "value: " << c.value;
  1050. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1051. }
  1052. }
  1053. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1054. Server svr;
  1055. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1056. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1057. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1058. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1059. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1060. res.set_content("ok", "text/plain");
  1061. });
  1062. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1063. EXPECT_TRUE(false);
  1064. res.set_content("bad request", "text/plain");
  1065. });
  1066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1067. auto se = detail::scope_exit([&] {
  1068. svr.stop();
  1069. listen_thread.join();
  1070. ASSERT_FALSE(svr.is_running());
  1071. });
  1072. svr.wait_until_ready();
  1073. Client cli("localhost", PORT);
  1074. {
  1075. auto res = cli.Get(
  1076. "/accept_ok",
  1077. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1079. EXPECT_EQ(StatusCode::OK_200, res->status);
  1080. }
  1081. {
  1082. auto res = cli.Get("/accept_bad_request",
  1083. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1085. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1086. }
  1087. }
  1088. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1089. Server svr;
  1090. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1091. res.set_content("ok", "text/plain");
  1092. });
  1093. std::atomic<int> start_count{0};
  1094. std::atomic<bool> running_when_called{false};
  1095. svr.set_start_handler([&]() {
  1096. running_when_called = svr.is_running();
  1097. start_count++;
  1098. });
  1099. auto port = svr.bind_to_any_port(HOST);
  1100. std::thread t([&]() { svr.listen_after_bind(); });
  1101. auto se = detail::scope_exit([&] {
  1102. svr.stop();
  1103. t.join();
  1104. ASSERT_FALSE(svr.is_running());
  1105. });
  1106. svr.wait_until_ready();
  1107. // A successful request proves the accept loop is running, which the start
  1108. // handler precedes; so by now the handler must have run exactly once.
  1109. Client cli(HOST, port);
  1110. cli.set_connection_timeout(std::chrono::seconds(5));
  1111. auto res = cli.Get("/");
  1112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1113. EXPECT_EQ(StatusCode::OK_200, res->status);
  1114. EXPECT_EQ(1, start_count.load());
  1115. EXPECT_TRUE(running_when_called.load());
  1116. }
  1117. TEST(DivideTest, DivideStringTests) {
  1118. auto divide = [](const std::string &str, char d) {
  1119. std::string lhs;
  1120. std::string rhs;
  1121. detail::divide(str, d,
  1122. [&](const char *lhs_data, std::size_t lhs_size,
  1123. const char *rhs_data, std::size_t rhs_size) {
  1124. lhs.assign(lhs_data, lhs_size);
  1125. rhs.assign(rhs_data, rhs_size);
  1126. });
  1127. return std::make_pair(std::move(lhs), std::move(rhs));
  1128. };
  1129. {
  1130. const auto res = divide("", '=');
  1131. EXPECT_EQ(res.first, "");
  1132. EXPECT_EQ(res.second, "");
  1133. }
  1134. {
  1135. const auto res = divide("=", '=');
  1136. EXPECT_EQ(res.first, "");
  1137. EXPECT_EQ(res.second, "");
  1138. }
  1139. {
  1140. const auto res = divide(" ", '=');
  1141. EXPECT_EQ(res.first, " ");
  1142. EXPECT_EQ(res.second, "");
  1143. }
  1144. {
  1145. const auto res = divide("a", '=');
  1146. EXPECT_EQ(res.first, "a");
  1147. EXPECT_EQ(res.second, "");
  1148. }
  1149. {
  1150. const auto res = divide("a=", '=');
  1151. EXPECT_EQ(res.first, "a");
  1152. EXPECT_EQ(res.second, "");
  1153. }
  1154. {
  1155. const auto res = divide("=b", '=');
  1156. EXPECT_EQ(res.first, "");
  1157. EXPECT_EQ(res.second, "b");
  1158. }
  1159. {
  1160. const auto res = divide("a=b", '=');
  1161. EXPECT_EQ(res.first, "a");
  1162. EXPECT_EQ(res.second, "b");
  1163. }
  1164. {
  1165. const auto res = divide("a=b=", '=');
  1166. EXPECT_EQ(res.first, "a");
  1167. EXPECT_EQ(res.second, "b=");
  1168. }
  1169. {
  1170. const auto res = divide("a=b=c", '=');
  1171. EXPECT_EQ(res.first, "a");
  1172. EXPECT_EQ(res.second, "b=c");
  1173. }
  1174. }
  1175. TEST(SplitTest, ParseQueryString) {
  1176. string s = "key1=val1&key2=val2&key3=val3";
  1177. Params dic;
  1178. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1179. [&](const char *b, const char *e) {
  1180. string key, val;
  1181. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1182. if (key.empty()) {
  1183. key.assign(b2, e2);
  1184. } else {
  1185. val.assign(b2, e2);
  1186. }
  1187. });
  1188. dic.emplace(key, val);
  1189. });
  1190. EXPECT_EQ("val1", dic.find("key1")->second);
  1191. EXPECT_EQ("val2", dic.find("key2")->second);
  1192. EXPECT_EQ("val3", dic.find("key3")->second);
  1193. }
  1194. TEST(SplitTest, ParseInvalidQueryTests) {
  1195. {
  1196. string s = " ";
  1197. Params dict;
  1198. detail::parse_query_text(s, dict);
  1199. EXPECT_TRUE(dict.empty());
  1200. }
  1201. {
  1202. string s = " = =";
  1203. Params dict;
  1204. detail::parse_query_text(s, dict);
  1205. EXPECT_TRUE(dict.empty());
  1206. }
  1207. }
  1208. TEST(ParseQueryTest, ParseQueryString) {
  1209. {
  1210. std::string s = "key1=val1&key2=val2&key3=val3";
  1211. Params dic;
  1212. detail::parse_query_text(s, dic);
  1213. EXPECT_EQ("val1", dic.find("key1")->second);
  1214. EXPECT_EQ("val2", dic.find("key2")->second);
  1215. EXPECT_EQ("val3", dic.find("key3")->second);
  1216. }
  1217. {
  1218. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1219. Params dic;
  1220. detail::parse_query_text(s, dic);
  1221. EXPECT_EQ("", dic.find("key1")->second);
  1222. EXPECT_EQ("val1", dic.find("key2")->second);
  1223. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1224. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1225. }
  1226. }
  1227. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1228. Params dic;
  1229. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1230. dic.emplace("key1", "val1");
  1231. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1232. dic.emplace("key2", "val2");
  1233. dic.emplace("key3", "val3");
  1234. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1235. }
  1236. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1237. Params params;
  1238. params.emplace("a", "1");
  1239. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1240. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1241. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1242. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1243. // Long enough to overflow the stack when matched with std::regex.
  1244. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1245. EXPECT_EQ("/p?" + long_query + "&a=1",
  1246. append_query_params("/p?" + long_query, params));
  1247. }
  1248. // Joins every entry of a Headers or Params into "key=value " so a whole
  1249. // traversal can be compared in one assertion. Both are instantiations of the
  1250. // same insertion-ordered container, so one helper serves both.
  1251. template <typename Map> static std::string entries_to_string(const Map &m) {
  1252. std::string s;
  1253. for (const auto &entry : m) {
  1254. s += entry.first + "=" + entry.second + " ";
  1255. }
  1256. return s;
  1257. }
  1258. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1259. // Params used to be a std::multimap, which sorted by name and handed the
  1260. // caller's query back alphabetised. A client signing its query string could
  1261. // not reproduce the order it asked for.
  1262. Params dic;
  1263. dic.emplace("zulu", "1");
  1264. dic.emplace("alpha", "2");
  1265. dic.emplace("mike", "3");
  1266. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1267. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1268. }
  1269. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1270. Params dic;
  1271. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1272. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1273. }
  1274. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1275. Request req;
  1276. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1277. req.params);
  1278. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1279. EXPECT_EQ("first", req.get_param_value("tag"));
  1280. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1281. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1282. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1283. EXPECT_EQ("", req.get_param_value("tag", 3));
  1284. }
  1285. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1286. // Params shares its container with Headers, which matches field names
  1287. // case-insensitively. Parameter names must not pick that up.
  1288. Params dic;
  1289. dic.emplace("Key", "upper");
  1290. dic.emplace("key", "lower");
  1291. EXPECT_EQ(2U, dic.size());
  1292. EXPECT_EQ(1U, dic.count("Key"));
  1293. EXPECT_EQ(1U, dic.count("key"));
  1294. EXPECT_EQ("upper", dic.find("Key")->second);
  1295. EXPECT_EQ("lower", dic.find("key")->second);
  1296. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1297. }
  1298. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1299. Server svr;
  1300. std::string order;
  1301. svr.Get("/order", [&](const Request &req, Response &res) {
  1302. order = entries_to_string(req.params);
  1303. res.set_content("ok", "text/plain");
  1304. });
  1305. auto port = svr.bind_to_any_port(HOST);
  1306. thread t = thread([&] { svr.listen_after_bind(); });
  1307. auto se = detail::scope_exit([&] {
  1308. svr.stop();
  1309. t.join();
  1310. ASSERT_FALSE(svr.is_running());
  1311. });
  1312. svr.wait_until_ready();
  1313. Client cli(HOST, port);
  1314. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1315. ASSERT_TRUE(res);
  1316. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1317. }
  1318. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1319. Server svr;
  1320. std::string field_order, file_order;
  1321. svr.Post("/order", [&](const Request &req, Response &res) {
  1322. for (const auto &field : req.form.fields) {
  1323. field_order += field.first + "=" + field.second.content + " ";
  1324. }
  1325. for (const auto &file : req.form.files) {
  1326. file_order += file.first + "=" + file.second.filename + " ";
  1327. }
  1328. res.set_content("ok", "text/plain");
  1329. });
  1330. auto port = svr.bind_to_any_port(HOST);
  1331. thread t = thread([&] { svr.listen_after_bind(); });
  1332. auto se = detail::scope_exit([&] {
  1333. svr.stop();
  1334. t.join();
  1335. ASSERT_FALSE(svr.is_running());
  1336. });
  1337. svr.wait_until_ready();
  1338. UploadFormDataItems items = {
  1339. {"zulu", "1", "", ""},
  1340. {"alpha", "2", "", ""},
  1341. {"mike", "3", "", ""},
  1342. {"zebra", "z", "z.txt", "text/plain"},
  1343. {"apple", "a", "a.txt", "text/plain"},
  1344. };
  1345. Client cli(HOST, port);
  1346. auto res = cli.Post("/order", items);
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1349. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1350. }
  1351. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1352. Server svr;
  1353. std::vector<std::string> values;
  1354. std::string first, second, out_of_range, order;
  1355. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1356. values = req.form.get_fields("tag");
  1357. first = req.form.get_field("tag", 0);
  1358. second = req.form.get_field("tag", 1);
  1359. out_of_range = req.form.get_field("tag", 2);
  1360. for (const auto &field : req.form.fields) {
  1361. order += field.first + "=" + field.second.content + " ";
  1362. }
  1363. res.set_content("ok", "text/plain");
  1364. });
  1365. auto port = svr.bind_to_any_port(HOST);
  1366. thread t = thread([&] { svr.listen_after_bind(); });
  1367. auto se = detail::scope_exit([&] {
  1368. svr.stop();
  1369. t.join();
  1370. ASSERT_FALSE(svr.is_running());
  1371. });
  1372. svr.wait_until_ready();
  1373. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1374. // not adjacent in the container.
  1375. UploadFormDataItems items = {
  1376. {"tag", "first", "", ""},
  1377. {"other", "x", "", ""},
  1378. {"tag", "second", "", ""},
  1379. };
  1380. Client cli(HOST, port);
  1381. auto res = cli.Post("/repeated", items);
  1382. ASSERT_TRUE(res);
  1383. ASSERT_EQ(2U, values.size());
  1384. EXPECT_EQ("first", values[0]);
  1385. EXPECT_EQ("second", values[1]);
  1386. EXPECT_EQ("first", first);
  1387. EXPECT_EQ("second", second);
  1388. // std::multimap already kept entries sharing a name in insertion order, so
  1389. // everything above passes without this change too. The whole traversal is
  1390. // what tells the two apart: sorting by name would hoist "other" to the front
  1391. // and the two "tag" parts would end up adjacent.
  1392. EXPECT_EQ("tag=first other=x tag=second ", order);
  1393. // Advancing past the last entry of a name used to run off the container;
  1394. // the container's saturating increment makes it return the default instead.
  1395. EXPECT_EQ("", out_of_range);
  1396. }
  1397. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1398. // Server::read_content() keeps a FormFields::iterator alive across the
  1399. // content callbacks that fill the part it points at. The container is
  1400. // vector-backed, so a later emplace can reallocate and invalidate an older
  1401. // iterator; 64 parts grow the vector through seven reallocations, which
  1402. // checks that every part's content still lands in its own entry.
  1403. const size_t part_count = 64;
  1404. // One formula for both the parts sent and the values expected back, so the
  1405. // two cannot drift apart.
  1406. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1407. auto content_of = [](size_t i) {
  1408. return std::string(64, static_cast<char>('a' + (i % 26)));
  1409. };
  1410. Server svr;
  1411. std::vector<std::pair<std::string, std::string>> received;
  1412. svr.Post("/many", [&](const Request &req, Response &res) {
  1413. for (const auto &field : req.form.fields) {
  1414. received.emplace_back(field.first, field.second.content);
  1415. }
  1416. res.set_content("ok", "text/plain");
  1417. });
  1418. auto port = svr.bind_to_any_port(HOST);
  1419. thread t = thread([&] { svr.listen_after_bind(); });
  1420. auto se = detail::scope_exit([&] {
  1421. svr.stop();
  1422. t.join();
  1423. ASSERT_FALSE(svr.is_running());
  1424. });
  1425. svr.wait_until_ready();
  1426. UploadFormDataItems items;
  1427. for (size_t i = 0; i < part_count; i++) {
  1428. items.push_back({name_of(i), content_of(i), "", ""});
  1429. }
  1430. Client cli(HOST, port);
  1431. auto res = cli.Post("/many", items);
  1432. ASSERT_TRUE(res);
  1433. ASSERT_EQ(part_count, received.size());
  1434. for (size_t i = 0; i < part_count; i++) {
  1435. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1436. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1437. }
  1438. }
  1439. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1440. string content_type = "multipart/form-data; boundary=something";
  1441. string boundary;
  1442. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1443. EXPECT_TRUE(ret);
  1444. EXPECT_EQ(boundary, "something");
  1445. }
  1446. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1447. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1448. string boundary;
  1449. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1450. EXPECT_TRUE(ret);
  1451. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1452. }
  1453. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1454. string content_type =
  1455. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1456. string boundary;
  1457. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1458. EXPECT_TRUE(ret);
  1459. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1460. }
  1461. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1462. string content_type =
  1463. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1464. string boundary;
  1465. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1466. EXPECT_TRUE(ret);
  1467. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1468. }
  1469. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1470. const string boundary(70, 'a');
  1471. string content_type = "multipart/form-data; boundary=" + boundary;
  1472. string parsed;
  1473. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1474. EXPECT_TRUE(ret);
  1475. EXPECT_EQ(parsed, boundary);
  1476. }
  1477. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1478. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1479. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1480. string parsed;
  1481. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1482. EXPECT_FALSE(ret);
  1483. }
  1484. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1485. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1486. // is 72 characters on the wire and still valid.
  1487. const string boundary(70, 'a');
  1488. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1489. string parsed;
  1490. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1491. EXPECT_EQ(parsed, boundary);
  1492. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1493. parsed.clear();
  1494. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1495. }
  1496. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1497. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1498. // The parameter parser must not treat that '=' as the key/value separator.
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1501. "charset=UTF-8";
  1502. string parsed;
  1503. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1504. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1507. // A ';' inside the quoted-string is part of the value, not a parameter
  1508. // separator, so it must not truncate the boundary.
  1509. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1510. string parsed;
  1511. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1512. EXPECT_EQ(parsed, "a;b");
  1513. }
  1514. TEST(ParseDispositionParamsTest, QuotedValues) {
  1515. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1516. // ';' and '=' are ordinary characters inside one.
  1517. struct {
  1518. const char *value;
  1519. std::vector<std::pair<const char *, const char *>> expected;
  1520. } cases[] = {
  1521. {"name=\"file1\"; filename=\"a.txt\"",
  1522. {{"name", "file1"}, {"filename", "a.txt"}}},
  1523. // Whitespace around '=' and ';' is still trimmed
  1524. {"name=\"file2\" ;filename = \"a.html\"",
  1525. {{"name", "file2"}, {"filename", "a.html"}}},
  1526. // '=' inside the value used to leave only the text after the last one
  1527. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1528. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1529. {"name=\"x=y\"", {{"name", "x=y"}}},
  1530. // ';' inside the value used to truncate the pair and leave a bogus one
  1531. {"name=\"file3\"; filename=\"a;b.txt\"",
  1532. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1533. // An unquoted value keeps working, and so does filename*
  1534. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1535. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1536. // A parameter with no key is dropped rather than turned into one whose
  1537. // key is the value
  1538. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1539. };
  1540. for (const auto &c : cases) {
  1541. Params params;
  1542. detail::parse_disposition_params(c.value, params);
  1543. for (const auto &kv : c.expected) {
  1544. auto it = params.find(kv.first);
  1545. ASSERT_NE(it, params.end())
  1546. << "value: " << c.value << ", key: " << kv.first;
  1547. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1548. }
  1549. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1550. }
  1551. }
  1552. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1553. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1554. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1555. Server svr;
  1556. std::string field_value, file_name, file_filename;
  1557. bool has_field = false, has_file = false;
  1558. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1559. has_field = req.form.has_field("x=y");
  1560. field_value = req.form.get_field("x=y");
  1561. has_file = req.form.has_file("file1");
  1562. const auto &file = req.form.get_file("file1");
  1563. file_name = file.name;
  1564. file_filename = file.filename;
  1565. res.set_content("ok", "text/plain");
  1566. });
  1567. auto port = svr.bind_to_any_port(HOST);
  1568. thread t = thread([&] { svr.listen_after_bind(); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. t.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. UploadFormDataItems items = {
  1576. {"x=y", "field-value", "", ""},
  1577. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1578. };
  1579. Client cli(HOST, port);
  1580. auto res = cli.Post("/quoted", items);
  1581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1582. ASSERT_EQ(StatusCode::OK_200, res->status);
  1583. EXPECT_TRUE(has_field);
  1584. EXPECT_EQ("field-value", field_value);
  1585. EXPECT_TRUE(has_file);
  1586. EXPECT_EQ("file1", file_name);
  1587. EXPECT_EQ("a;b=report.pdf", file_filename);
  1588. }
  1589. TEST(GetHeaderValueTest, DefaultValue) {
  1590. Headers headers = {{"Dummy", "Dummy"}};
  1591. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1592. EXPECT_STREQ("text/plain", val);
  1593. }
  1594. TEST(GetHeaderValueTest, DefaultValueInt) {
  1595. Headers headers = {{"Dummy", "Dummy"}};
  1596. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1597. EXPECT_EQ(100ull, val);
  1598. }
  1599. TEST(GetHeaderValueTest, RegularValue) {
  1600. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1601. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1602. EXPECT_STREQ("text/html", val);
  1603. }
  1604. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1605. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1606. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1607. EXPECT_STREQ("text/html", val);
  1608. }
  1609. TEST(GetHeaderValueTest, SetContent) {
  1610. Response res;
  1611. res.set_content("html", "text/html");
  1612. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1613. res.set_content("text", "text/plain");
  1614. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1615. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1616. }
  1617. TEST(GetHeaderValueTest, RegularValueInt) {
  1618. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1619. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1620. EXPECT_EQ(100ull, val);
  1621. }
  1622. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1623. Headers headers = {{"Content-Length", "x"}};
  1624. auto is_invalid_value = false;
  1625. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1626. is_invalid_value);
  1627. EXPECT_EQ(0ull, val);
  1628. EXPECT_TRUE(is_invalid_value);
  1629. }
  1630. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1631. // An all-digit value that overflows size_t must be reported as invalid, not
  1632. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1633. // a large length to a small one on 32-bit builds, leaving the framing length
  1634. // wrong while is_invalid_value stayed false.
  1635. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1636. auto is_invalid_value = false;
  1637. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1638. is_invalid_value);
  1639. EXPECT_TRUE(is_invalid_value);
  1640. // A well-formed length is unaffected.
  1641. Headers ok = {{"Content-Length", "1234"}};
  1642. is_invalid_value = false;
  1643. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1644. is_invalid_value);
  1645. EXPECT_EQ(1234ull, val);
  1646. EXPECT_FALSE(is_invalid_value);
  1647. }
  1648. TEST(GetHeaderValueTest, Range) {
  1649. {
  1650. Headers headers = {make_range_header({{1, -1}})};
  1651. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1652. EXPECT_STREQ("bytes=1-", val);
  1653. }
  1654. {
  1655. Headers headers = {make_range_header({{-1, 1}})};
  1656. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1657. EXPECT_STREQ("bytes=-1", val);
  1658. }
  1659. {
  1660. Headers headers = {make_range_header({{1, 10}})};
  1661. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1662. EXPECT_STREQ("bytes=1-10", val);
  1663. }
  1664. {
  1665. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1666. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1667. EXPECT_STREQ("bytes=1-10, 100-", val);
  1668. }
  1669. {
  1670. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1671. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1672. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1673. }
  1674. {
  1675. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1676. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1677. EXPECT_STREQ("bytes=0-0, -1", val);
  1678. }
  1679. }
  1680. TEST(BearerTokenAuthTest, SchemeValidation) {
  1681. // A value shorter than "Bearer " must not throw from the fixed-length
  1682. // substr, and a non-Bearer scheme must not be reported as a token.
  1683. struct {
  1684. const char *value;
  1685. const char *expected;
  1686. } cases[] = {
  1687. {"x", ""},
  1688. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1689. {"Bearer abc123", "abc123"},
  1690. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1691. };
  1692. for (const auto &c : cases) {
  1693. Request req;
  1694. req.set_header("Authorization", c.value);
  1695. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1696. }
  1697. }
  1698. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1699. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1700. // to depend on the standard library (libstdc++ handed back duplicates in
  1701. // reverse insertion order, libc++ in insertion order).
  1702. Request req;
  1703. req.set_header("Accept-Encoding", "gzip");
  1704. req.set_header("Accept-Encoding", "deflate");
  1705. req.set_header("Accept-Encoding", "br");
  1706. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1707. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1708. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1709. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1710. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1711. }
  1712. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1713. Request req;
  1714. req.set_header("X-Test", "only");
  1715. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1716. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1717. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1718. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1719. }
  1720. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1721. Request req;
  1722. req.set_header("X-First", "1");
  1723. req.set_header("X-Test", "2");
  1724. req.params.emplace("first", "1");
  1725. req.params.emplace("test", "2");
  1726. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1727. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1728. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1729. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1730. // The second one is negative when read as a signed value
  1731. const auto max_id = (std::numeric_limits<size_t>::max)();
  1732. for (auto id : {max_id / 2, max_id}) {
  1733. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1734. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1735. EXPECT_EQ("", req.get_param_value("test", id));
  1736. EXPECT_EQ("", req.form.get_field("test", id));
  1737. EXPECT_EQ("", req.form.get_file("test", id).content);
  1738. }
  1739. }
  1740. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1741. Headers headers;
  1742. headers.emplace("Host", "example.com");
  1743. headers.emplace("Accept-Encoding", "gzip");
  1744. headers.emplace("User-Agent", "test");
  1745. headers.emplace("Accept-Encoding", "deflate");
  1746. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1747. "Accept-Encoding=deflate ",
  1748. entries_to_string(headers));
  1749. }
  1750. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1751. Headers headers = {{"Content-Type", "text/html"},
  1752. {"CONTENT-TYPE", "text/xml"}};
  1753. EXPECT_EQ(2U, headers.count("content-type"));
  1754. auto it = headers.find("content-type");
  1755. ASSERT_TRUE(it != headers.end());
  1756. EXPECT_EQ("text/html", it->second);
  1757. }
  1758. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1759. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1760. // drop only those fields and leave everything positioned between them.
  1761. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1762. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1763. auto rng = headers.equal_range("a");
  1764. headers.erase(rng.first, rng.second);
  1765. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1766. }
  1767. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1768. Headers headers = {
  1769. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1770. EXPECT_EQ(3U, headers.erase("A"));
  1771. EXPECT_EQ(0U, headers.count("A"));
  1772. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1773. }
  1774. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1775. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1776. headers.emplace_front("Host", "example.com");
  1777. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1778. entries_to_string(headers));
  1779. }
  1780. TEST(ParseHeaderValueTest, Range) {
  1781. {
  1782. Ranges ranges;
  1783. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1784. EXPECT_TRUE(ret);
  1785. EXPECT_EQ(1u, ranges.size());
  1786. EXPECT_EQ(1u, ranges[0].first);
  1787. EXPECT_EQ(-1, ranges[0].second);
  1788. }
  1789. {
  1790. Ranges ranges;
  1791. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1792. EXPECT_TRUE(ret);
  1793. EXPECT_EQ(1u, ranges.size());
  1794. EXPECT_EQ(-1, ranges[0].first);
  1795. EXPECT_EQ(1u, ranges[0].second);
  1796. }
  1797. {
  1798. Ranges ranges;
  1799. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1800. EXPECT_TRUE(ret);
  1801. EXPECT_EQ(1u, ranges.size());
  1802. EXPECT_EQ(1u, ranges[0].first);
  1803. EXPECT_EQ(10u, ranges[0].second);
  1804. }
  1805. {
  1806. Ranges ranges;
  1807. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1808. EXPECT_FALSE(ret);
  1809. }
  1810. {
  1811. Ranges ranges;
  1812. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1813. EXPECT_TRUE(ret);
  1814. EXPECT_EQ(2u, ranges.size());
  1815. EXPECT_EQ(1u, ranges[0].first);
  1816. EXPECT_EQ(10u, ranges[0].second);
  1817. EXPECT_EQ(100u, ranges[1].first);
  1818. EXPECT_EQ(-1, ranges[1].second);
  1819. }
  1820. {
  1821. Ranges ranges;
  1822. auto ret =
  1823. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1824. EXPECT_TRUE(ret);
  1825. EXPECT_EQ(3u, ranges.size());
  1826. EXPECT_EQ(1u, ranges[0].first);
  1827. EXPECT_EQ(10u, ranges[0].second);
  1828. EXPECT_EQ(100u, ranges[1].first);
  1829. EXPECT_EQ(200u, ranges[1].second);
  1830. EXPECT_EQ(300u, ranges[2].first);
  1831. EXPECT_EQ(400u, ranges[2].second);
  1832. }
  1833. {
  1834. Ranges ranges;
  1835. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1836. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1837. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1838. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1839. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1840. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1841. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1842. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1843. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1844. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1845. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1846. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1847. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1848. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1849. EXPECT_FALSE(
  1850. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1851. EXPECT_TRUE(ranges.empty());
  1852. }
  1853. {
  1854. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1855. // remainder of the representation, so it stays accepted.
  1856. Ranges ranges;
  1857. auto ret =
  1858. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1859. EXPECT_TRUE(ret);
  1860. ASSERT_EQ(1u, ranges.size());
  1861. EXPECT_EQ(0, ranges[0].first);
  1862. EXPECT_EQ(-1, ranges[0].second);
  1863. }
  1864. // RFC 9110 14.1: range unit names are case-insensitive.
  1865. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1866. Ranges ranges;
  1867. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1868. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1869. }
  1870. }
  1871. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1872. Request req;
  1873. req.set_header("Accept-Encoding", "gzip");
  1874. Response res;
  1875. res.set_header("Content-Type", "text/plain");
  1876. auto ret = detail::encoding_type(req, res);
  1877. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1878. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1879. #else
  1880. EXPECT_TRUE(ret == detail::EncodingType::None);
  1881. #endif
  1882. }
  1883. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1884. Request req;
  1885. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1886. Response res;
  1887. res.set_header("Content-Type", "text/plain");
  1888. auto ret = detail::encoding_type(req, res);
  1889. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1890. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1891. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1892. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1893. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1894. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1895. #else
  1896. EXPECT_TRUE(ret == detail::EncodingType::None);
  1897. #endif
  1898. }
  1899. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1900. Request req;
  1901. req.set_header("Accept-Encoding",
  1902. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1903. Response res;
  1904. res.set_header("Content-Type", "text/plain");
  1905. auto ret = detail::encoding_type(req, res);
  1906. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1907. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1908. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1909. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1910. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1911. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1912. #else
  1913. EXPECT_TRUE(ret == detail::EncodingType::None);
  1914. #endif
  1915. }
  1916. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1917. // All supported encodings rejected with q=0 should return None
  1918. Request req;
  1919. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1920. Response res;
  1921. res.set_header("Content-Type", "text/plain");
  1922. auto ret = detail::encoding_type(req, res);
  1923. EXPECT_TRUE(ret == detail::EncodingType::None);
  1924. }
  1925. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1926. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1927. Request req;
  1928. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1929. Response res;
  1930. res.set_header("Content-Type", "text/plain");
  1931. auto ret = detail::encoding_type(req, res);
  1932. EXPECT_TRUE(ret == detail::EncodingType::None);
  1933. }
  1934. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1935. Request req;
  1936. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1937. Response res;
  1938. res.set_header("Content-Type", "text/plain");
  1939. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1940. }
  1941. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1942. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1943. Request req;
  1944. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1945. Response res;
  1946. res.set_header("Content-Type", "text/plain");
  1947. auto ret = detail::encoding_type(req, res);
  1948. EXPECT_TRUE(ret == detail::EncodingType::None);
  1949. }
  1950. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1951. // RFC 7231: Accept-Encoding values are case-insensitive
  1952. Request req;
  1953. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1954. Response res;
  1955. res.set_header("Content-Type", "text/plain");
  1956. auto ret = detail::encoding_type(req, res);
  1957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1963. #else
  1964. EXPECT_TRUE(ret == detail::EncodingType::None);
  1965. #endif
  1966. }
  1967. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1968. // q value should determine priority, not hardcoded order
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1971. Response res;
  1972. res.set_header("Content-Type", "text/plain");
  1973. auto ret = detail::encoding_type(req, res);
  1974. // gzip has highest q=1.0, so it should be selected even though
  1975. // br and zstd are also supported
  1976. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1980. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1981. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1982. #else
  1983. EXPECT_TRUE(ret == detail::EncodingType::None);
  1984. #endif
  1985. }
  1986. TEST(BufferStreamTest, read) {
  1987. detail::BufferStream strm1;
  1988. Stream &strm = strm1;
  1989. EXPECT_EQ(5, strm.write("hello"));
  1990. char buf[512];
  1991. EXPECT_EQ(2, strm.read(buf, 2));
  1992. EXPECT_EQ('h', buf[0]);
  1993. EXPECT_EQ('e', buf[1]);
  1994. EXPECT_EQ(2, strm.read(buf, 2));
  1995. EXPECT_EQ('l', buf[0]);
  1996. EXPECT_EQ('l', buf[1]);
  1997. EXPECT_EQ(1, strm.read(buf, 1));
  1998. EXPECT_EQ('o', buf[0]);
  1999. EXPECT_EQ(0, strm.read(buf, 1));
  2000. }
  2001. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2002. auto host = "www.httpwatch.com";
  2003. auto ip = hosted_at(host);
  2004. EXPECT_EQ("23.96.13.243", ip);
  2005. std::vector<std::string> addrs;
  2006. hosted_at(host, addrs);
  2007. EXPECT_EQ(1u, addrs.size());
  2008. }
  2009. #if 0 // It depends on each test environment...
  2010. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2011. auto host = "www.youtube.com";
  2012. std::vector<std::string> addrs;
  2013. hosted_at(host, addrs);
  2014. EXPECT_EQ(20u, addrs.size());
  2015. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2016. EXPECT_TRUE(it != addrs.end());
  2017. }
  2018. #endif
  2019. class ChunkedEncodingTest : public ::testing::Test {
  2020. protected:
  2021. ChunkedEncodingTest()
  2022. : cli_(HOST, PORT)
  2023. #ifdef CPPHTTPLIB_SSL_ENABLED
  2024. ,
  2025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2026. #endif
  2027. {
  2028. cli_.set_connection_timeout(2);
  2029. #ifdef CPPHTTPLIB_SSL_ENABLED
  2030. cli_.enable_server_certificate_verification(false);
  2031. #endif
  2032. }
  2033. virtual void SetUp() {
  2034. read_file("./image.jpg", image_data_);
  2035. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2036. res.set_content("Hello World!", "text/plain");
  2037. });
  2038. svr_.Get(
  2039. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2040. res.set_chunked_content_provider(
  2041. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2042. size_t remaining = image_data_.size() - offset;
  2043. if (remaining == 0) {
  2044. sink.done();
  2045. } else {
  2046. constexpr size_t CHUNK_SIZE = 1024;
  2047. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2048. sink.write(&image_data_[offset], send_size);
  2049. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2050. }
  2051. return true;
  2052. });
  2053. });
  2054. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2055. svr_.wait_until_ready();
  2056. }
  2057. virtual void TearDown() {
  2058. svr_.stop();
  2059. if (!request_threads_.empty()) {
  2060. std::this_thread::sleep_for(std::chrono::seconds(1));
  2061. for (auto &t : request_threads_) {
  2062. t.join();
  2063. }
  2064. }
  2065. t_.join();
  2066. }
  2067. #ifdef CPPHTTPLIB_SSL_ENABLED
  2068. SSLClient cli_;
  2069. SSLServer svr_;
  2070. #else
  2071. Client cli_;
  2072. Server svr_;
  2073. #endif
  2074. thread t_;
  2075. std::vector<thread> request_threads_;
  2076. std::string image_data_;
  2077. };
  2078. TEST_F(ChunkedEncodingTest, NormalGet) {
  2079. auto res = cli_.Get("/chunked");
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. std::string out;
  2082. read_file("./image.jpg", out);
  2083. EXPECT_EQ(StatusCode::OK_200, res->status);
  2084. EXPECT_EQ(out, res->body);
  2085. }
  2086. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2087. std::string body;
  2088. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2089. body.append(data, data_length);
  2090. return true;
  2091. });
  2092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2093. std::string out;
  2094. read_file("./image.jpg", out);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. EXPECT_EQ(out, body);
  2097. }
  2098. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2099. std::string body;
  2100. auto res = cli_.Get(
  2101. "/chunked",
  2102. [&](const Response &response) {
  2103. EXPECT_EQ(StatusCode::OK_200, response.status);
  2104. return true;
  2105. },
  2106. [&](const char *data, size_t data_length) {
  2107. body.append(data, data_length);
  2108. return true;
  2109. });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. std::string out;
  2112. read_file("./image.jpg", out);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. EXPECT_EQ(out, body);
  2115. }
  2116. TEST(RangeTest, FromHTTPBin_Online) {
  2117. auto host = "httpbingo.org";
  2118. auto path = std::string{"/range/32"};
  2119. #ifdef CPPHTTPLIB_SSL_ENABLED
  2120. auto port = 443;
  2121. SSLClient cli(host, port);
  2122. #else
  2123. auto port = 80;
  2124. Client cli(host, port);
  2125. #endif
  2126. cli.set_connection_timeout(5);
  2127. {
  2128. auto res = cli.Get(path);
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2131. EXPECT_EQ(StatusCode::OK_200, res->status);
  2132. }
  2133. {
  2134. Headers headers = {make_range_header({{1, -1}})};
  2135. auto res = cli.Get(path, headers);
  2136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2137. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2139. }
  2140. {
  2141. Headers headers = {make_range_header({{1, 10}})};
  2142. auto res = cli.Get(path, headers);
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("bcdefghijk", res->body);
  2145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2146. }
  2147. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2148. // entire resource, while the original httpbin returned 200. Both are
  2149. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2150. {
  2151. Headers headers = {make_range_header({{0, 31}})};
  2152. auto res = cli.Get(path, headers);
  2153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2155. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2156. res->status == StatusCode::PartialContent_206);
  2157. }
  2158. {
  2159. Headers headers = {make_range_header({{0, -1}})};
  2160. auto res = cli.Get(path, headers);
  2161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2162. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2163. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2164. res->status == StatusCode::PartialContent_206);
  2165. }
  2166. // go-httpbin returns 206 with clamped range for over-range requests,
  2167. // while the original httpbin returned 416. Both behaviors are observed
  2168. // in real servers, so we only verify the request succeeds.
  2169. {
  2170. Headers headers = {make_range_header({{0, 32}})};
  2171. auto res = cli.Get(path, headers);
  2172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2173. }
  2174. }
  2175. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2176. auto host = "unresolvableaddress.local";
  2177. auto path = std::string{"/"};
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. auto port = 443;
  2180. SSLClient cli(host, port);
  2181. #else
  2182. auto port = 80;
  2183. Client cli(host, port);
  2184. #endif
  2185. cli.set_connection_timeout(1);
  2186. {
  2187. auto res = cli.Get(path);
  2188. ASSERT_FALSE(res);
  2189. }
  2190. std::this_thread::sleep_for(std::chrono::seconds(8));
  2191. }
  2192. #if defined(__linux__) && defined(__GLIBC__) && \
  2193. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2194. // Forward declaration: in split builds split.py strips `inline` and moves the
  2195. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2196. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2197. // against the symbol in both header-only and split builds.
  2198. namespace httplib {
  2199. namespace detail {
  2200. int getaddrinfo_with_timeout(const char *node, const char *service,
  2201. const struct addrinfo *hints,
  2202. struct addrinfo **res, time_t timeout_sec);
  2203. } // namespace detail
  2204. } // namespace httplib
  2205. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2206. //
  2207. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2208. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2209. // gai_suspend() call hits the connection timeout the function calls
  2210. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2211. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2212. // still alive and still references the now-destroyed stack frame.
  2213. //
  2214. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2215. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2216. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2217. // and runs them in a container.
  2218. namespace {
  2219. bool should_run_issue_2431_tests() {
  2220. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2221. return v && *v && std::string(v) != "0";
  2222. }
  2223. std::string unique_unresolvable_host(int n) {
  2224. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2225. // glibc still asks the configured nameserver — which is exactly the path
  2226. // we want to exercise. A unique label per call avoids the resolver cache.
  2227. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2228. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2229. std::to_string(n) + ".invalid";
  2230. }
  2231. } // namespace
  2232. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2233. if (!should_run_issue_2431_tests()) {
  2234. GTEST_SKIP()
  2235. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2236. }
  2237. for (int i = 0; i < 8; ++i) {
  2238. struct addrinfo hints;
  2239. memset(&hints, 0, sizeof(hints));
  2240. hints.ai_family = AF_UNSPEC;
  2241. hints.ai_socktype = SOCK_STREAM;
  2242. auto host = unique_unresolvable_host(i);
  2243. struct addrinfo *result = nullptr;
  2244. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2245. &result, /*timeout_sec=*/1);
  2246. if (rc == 0 && result) { freeaddrinfo(result); }
  2247. }
  2248. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2249. // stack region they still believe holds their gaicb.
  2250. std::this_thread::sleep_for(std::chrono::seconds(3));
  2251. }
  2252. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2253. if (!should_run_issue_2431_tests()) {
  2254. GTEST_SKIP()
  2255. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2256. }
  2257. std::atomic<bool> stop{false};
  2258. std::vector<std::thread> threads;
  2259. for (int t = 0; t < 8; ++t) {
  2260. threads.emplace_back([t, &stop] {
  2261. int i = 0;
  2262. while (!stop.load(std::memory_order_relaxed)) {
  2263. struct addrinfo hints;
  2264. memset(&hints, 0, sizeof(hints));
  2265. hints.ai_family = AF_UNSPEC;
  2266. hints.ai_socktype = SOCK_STREAM;
  2267. auto host = unique_unresolvable_host(t * 100000 + i++);
  2268. struct addrinfo *result = nullptr;
  2269. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2270. &result, /*timeout_sec=*/1);
  2271. if (rc == 0 && result) { freeaddrinfo(result); }
  2272. }
  2273. });
  2274. }
  2275. std::this_thread::sleep_for(std::chrono::seconds(8));
  2276. stop.store(true, std::memory_order_relaxed);
  2277. for (auto &th : threads) {
  2278. th.join();
  2279. }
  2280. std::this_thread::sleep_for(std::chrono::seconds(3));
  2281. }
  2282. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2283. if (!should_run_issue_2431_tests()) {
  2284. GTEST_SKIP()
  2285. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2286. }
  2287. std::atomic<bool> stop{false};
  2288. std::vector<std::thread> threads;
  2289. for (int t = 0; t < 8; ++t) {
  2290. threads.emplace_back([t, &stop] {
  2291. int i = 0;
  2292. while (!stop.load(std::memory_order_relaxed)) {
  2293. auto host = unique_unresolvable_host(t * 100000 + i++);
  2294. Client cli(host, 80);
  2295. cli.set_connection_timeout(1, 0);
  2296. cli.set_read_timeout(1, 0);
  2297. cli.set_write_timeout(1, 0);
  2298. (void)cli.Get("/");
  2299. }
  2300. });
  2301. }
  2302. std::this_thread::sleep_for(std::chrono::seconds(8));
  2303. stop.store(true, std::memory_order_relaxed);
  2304. for (auto &th : threads) {
  2305. th.join();
  2306. }
  2307. std::this_thread::sleep_for(std::chrono::seconds(3));
  2308. }
  2309. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2310. TEST(ConnectionErrorTest, InvalidHost) {
  2311. auto host = "-abcde.com";
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. auto port = 443;
  2314. SSLClient cli(host, port);
  2315. #else
  2316. auto port = 80;
  2317. Client cli(host, port);
  2318. #endif
  2319. cli.set_connection_timeout(std::chrono::seconds(2));
  2320. auto res = cli.Get("/");
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Connection, res.error());
  2323. }
  2324. TEST(ConnectionErrorTest, InvalidHost2) {
  2325. auto host = "httpcan.org/";
  2326. #ifdef CPPHTTPLIB_SSL_ENABLED
  2327. SSLClient cli(host);
  2328. #else
  2329. Client cli(host);
  2330. #endif
  2331. cli.set_connection_timeout(std::chrono::seconds(2));
  2332. auto res = cli.Get("/");
  2333. ASSERT_TRUE(!res);
  2334. EXPECT_EQ(Error::Connection, res.error());
  2335. }
  2336. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2337. auto host = "httpcan.org/";
  2338. #ifdef CPPHTTPLIB_SSL_ENABLED
  2339. SSLClient cli(host);
  2340. #else
  2341. Client cli(host);
  2342. #endif
  2343. cli.set_connection_timeout(std::chrono::seconds(2));
  2344. auto res = cli.Get("/");
  2345. ASSERT_TRUE(!res);
  2346. stringstream s;
  2347. s << "error code: " << res.error();
  2348. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2349. }
  2350. TEST(ConnectionErrorTest, InvalidPort) {
  2351. auto host = "localhost";
  2352. auto port = 44380;
  2353. #ifdef CPPHTTPLIB_SSL_ENABLED
  2354. SSLClient cli(host, port);
  2355. #else
  2356. Client cli(host, port);
  2357. #endif
  2358. cli.set_connection_timeout(std::chrono::seconds(2));
  2359. auto res = cli.Get("/");
  2360. ASSERT_TRUE(!res);
  2361. EXPECT_TRUE(Error::Connection == res.error() ||
  2362. Error::ConnectionTimeout == res.error());
  2363. }
  2364. TEST(ConnectionErrorTest, Timeout_Online) {
  2365. auto host = "google.com";
  2366. #ifdef CPPHTTPLIB_SSL_ENABLED
  2367. auto port = 44380;
  2368. SSLClient cli(host, port);
  2369. #else
  2370. auto port = 8080;
  2371. Client cli(host, port);
  2372. #endif
  2373. cli.set_connection_timeout(std::chrono::seconds(2));
  2374. // only probe one address type so that the error reason
  2375. // correlates to the timed-out IPv4, not the unsupported
  2376. // IPv6 connection attempt
  2377. cli.set_address_family(AF_INET);
  2378. auto res = cli.Get("/");
  2379. ASSERT_TRUE(!res);
  2380. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2381. }
  2382. TEST(CancelTest, NoCancel_Online) {
  2383. auto host = "httpbingo.org";
  2384. auto path = std::string{"/range/32"};
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. auto port = 443;
  2387. SSLClient cli(host, port);
  2388. #else
  2389. auto port = 80;
  2390. Client cli(host, port);
  2391. #endif
  2392. cli.set_connection_timeout(std::chrono::seconds(5));
  2393. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2396. EXPECT_EQ(StatusCode::OK_200, res->status);
  2397. }
  2398. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2399. // Use /bytes with a large payload so that the DownloadProgress callback
  2400. // (which only fires for Content-Length responses) is invoked before the
  2401. // entire body is received, giving cancellation a chance to fire.
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/bytes/524288"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2412. cli.set_connection_timeout(std::chrono::seconds(5));
  2413. ASSERT_TRUE(!res);
  2414. EXPECT_EQ(Error::Canceled, res.error());
  2415. }
  2416. TEST(CancelTest, WithCancelLargePayload_Online) {
  2417. auto host = "httpbingo.org";
  2418. auto path = std::string{"/bytes/524288"};
  2419. #ifdef CPPHTTPLIB_SSL_ENABLED
  2420. auto port = 443;
  2421. SSLClient cli(host, port);
  2422. #else
  2423. auto port = 80;
  2424. Client cli(host, port);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(5));
  2427. uint32_t count = 0;
  2428. auto res =
  2429. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2430. ASSERT_TRUE(!res);
  2431. EXPECT_EQ(Error::Canceled, res.error());
  2432. }
  2433. TEST(CancelTest, NoCancelPost) {
  2434. Server svr;
  2435. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2436. res.set_content("Hello World!", "text/plain");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, PORT);
  2446. cli.set_connection_timeout(std::chrono::seconds(5));
  2447. auto res =
  2448. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2449. "application/json", [](uint64_t, uint64_t) { return true; });
  2450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2451. EXPECT_EQ("Hello World!", res->body);
  2452. EXPECT_EQ(StatusCode::OK_200, res->status);
  2453. }
  2454. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2455. Server svr;
  2456. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2457. res.set_content("Hello World!", "text/plain");
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli(HOST, PORT);
  2467. cli.set_connection_timeout(std::chrono::seconds(5));
  2468. auto res =
  2469. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2470. "application/json", [](uint64_t, uint64_t) { return false; });
  2471. ASSERT_TRUE(!res);
  2472. EXPECT_EQ(Error::Canceled, res.error());
  2473. }
  2474. TEST(CancelTest, WithCancelLargePayloadPost) {
  2475. Server svr;
  2476. svr.set_payload_max_length(200 * 1024 * 1024);
  2477. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2478. res.set_content(LARGE_DATA, "text/plain");
  2479. });
  2480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2481. auto se = detail::scope_exit([&] {
  2482. svr.stop();
  2483. thread.join();
  2484. ASSERT_FALSE(svr.is_running());
  2485. });
  2486. svr.wait_until_ready();
  2487. Client cli(HOST, PORT);
  2488. cli.set_payload_max_length(200 * 1024 * 1024);
  2489. cli.set_connection_timeout(std::chrono::seconds(5));
  2490. auto res =
  2491. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2492. "application/json", [](uint64_t, uint64_t) { return false; });
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::Canceled, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancelPut) {
  2497. Server svr;
  2498. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. });
  2501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2502. auto se = detail::scope_exit([&] {
  2503. svr.stop();
  2504. thread.join();
  2505. ASSERT_FALSE(svr.is_running());
  2506. });
  2507. svr.wait_until_ready();
  2508. Client cli(HOST, PORT);
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. auto res =
  2511. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2512. "application/json", [](uint64_t, uint64_t) { return true; });
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ("Hello World!", res->body);
  2515. EXPECT_EQ(StatusCode::OK_200, res->status);
  2516. }
  2517. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2518. Server svr;
  2519. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2520. res.set_content("Hello World!", "text/plain");
  2521. });
  2522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2523. auto se = detail::scope_exit([&] {
  2524. svr.stop();
  2525. thread.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. });
  2528. svr.wait_until_ready();
  2529. Client cli(HOST, PORT);
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. auto res =
  2532. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2533. "application/json", [](uint64_t, uint64_t) { return false; });
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::Canceled, res.error());
  2536. }
  2537. TEST(CancelTest, WithCancelLargePayloadPut) {
  2538. Server svr;
  2539. svr.set_payload_max_length(200 * 1024 * 1024);
  2540. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2541. res.set_content(LARGE_DATA, "text/plain");
  2542. });
  2543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2544. auto se = detail::scope_exit([&] {
  2545. svr.stop();
  2546. thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. });
  2549. svr.wait_until_ready();
  2550. Client cli(HOST, PORT);
  2551. cli.set_payload_max_length(200 * 1024 * 1024);
  2552. cli.set_connection_timeout(std::chrono::seconds(5));
  2553. auto res =
  2554. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2555. "application/json", [](uint64_t, uint64_t) { return false; });
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::Canceled, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancelPatch) {
  2560. Server svr;
  2561. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("Hello World!", "text/plain");
  2563. });
  2564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2565. auto se = detail::scope_exit([&] {
  2566. svr.stop();
  2567. thread.join();
  2568. ASSERT_FALSE(svr.is_running());
  2569. });
  2570. svr.wait_until_ready();
  2571. Client cli(HOST, PORT);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return true; });
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ("Hello World!", res->body);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. }
  2580. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2581. Server svr;
  2582. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2583. res.set_content("Hello World!", "text/plain");
  2584. });
  2585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2586. auto se = detail::scope_exit([&] {
  2587. svr.stop();
  2588. thread.join();
  2589. ASSERT_FALSE(svr.is_running());
  2590. });
  2591. svr.wait_until_ready();
  2592. Client cli(HOST, PORT);
  2593. cli.set_connection_timeout(std::chrono::seconds(5));
  2594. auto res =
  2595. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2596. "application/json", [](uint64_t, uint64_t) { return false; });
  2597. ASSERT_TRUE(!res);
  2598. EXPECT_EQ(Error::Canceled, res.error());
  2599. }
  2600. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2601. Server svr;
  2602. svr.set_payload_max_length(200 * 1024 * 1024);
  2603. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2604. res.set_content(LARGE_DATA, "text/plain");
  2605. });
  2606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2607. auto se = detail::scope_exit([&] {
  2608. svr.stop();
  2609. thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. });
  2612. svr.wait_until_ready();
  2613. Client cli(HOST, PORT);
  2614. cli.set_payload_max_length(200 * 1024 * 1024);
  2615. cli.set_connection_timeout(std::chrono::seconds(5));
  2616. auto res =
  2617. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2618. "application/json", [](uint64_t, uint64_t) { return false; });
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Canceled, res.error());
  2621. }
  2622. TEST(CancelTest, NoCancelDelete) {
  2623. Server svr;
  2624. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2628. auto se = detail::scope_exit([&] {
  2629. svr.stop();
  2630. thread.join();
  2631. ASSERT_FALSE(svr.is_running());
  2632. });
  2633. svr.wait_until_ready();
  2634. Client cli(HOST, PORT);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return true; });
  2639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. EXPECT_EQ(StatusCode::OK_200, res->status);
  2642. }
  2643. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2644. Server svr;
  2645. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2646. res.set_content("Hello World!", "text/plain");
  2647. });
  2648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. thread.join();
  2652. ASSERT_FALSE(svr.is_running());
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, PORT);
  2656. cli.set_connection_timeout(std::chrono::seconds(5));
  2657. auto res =
  2658. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2659. "application/json", [](uint64_t, uint64_t) { return false; });
  2660. ASSERT_TRUE(!res);
  2661. EXPECT_EQ(Error::Canceled, res.error());
  2662. }
  2663. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2664. Server svr;
  2665. svr.set_payload_max_length(200 * 1024 * 1024);
  2666. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2667. res.set_content(LARGE_DATA, "text/plain");
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. Client cli(HOST, PORT);
  2677. cli.set_payload_max_length(200 * 1024 * 1024);
  2678. cli.set_connection_timeout(std::chrono::seconds(5));
  2679. auto res =
  2680. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2681. "application/json", [](uint64_t, uint64_t) { return false; });
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::Canceled, res.error());
  2684. }
  2685. static std::string remove_whitespace(const std::string &input) {
  2686. std::string output;
  2687. output.reserve(input.size());
  2688. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2689. [](unsigned char c) { return !std::isspace(c); });
  2690. return output;
  2691. }
  2692. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2693. auto host = "httpbingo.org";
  2694. auto path = std::string{"/basic-auth/hello/world"};
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. auto port = 443;
  2697. SSLClient cli(host, port);
  2698. #else
  2699. auto port = 80;
  2700. Client cli(host, port);
  2701. #endif
  2702. {
  2703. auto res = cli.Get(path);
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2706. }
  2707. {
  2708. auto res = cli.Get(
  2709. path, Headers{make_basic_authentication_header("hello", "world")});
  2710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2711. auto body = remove_whitespace(res->body);
  2712. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2713. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2714. EXPECT_EQ(StatusCode::OK_200, res->status);
  2715. }
  2716. {
  2717. cli.set_basic_auth("hello", "world");
  2718. auto res = cli.Get(path);
  2719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2720. auto body = remove_whitespace(res->body);
  2721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2723. EXPECT_EQ(StatusCode::OK_200, res->status);
  2724. }
  2725. {
  2726. cli.set_basic_auth("hello", "bad");
  2727. auto res = cli.Get(path);
  2728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2730. }
  2731. {
  2732. cli.set_basic_auth("bad", "world");
  2733. auto res = cli.Get(path);
  2734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2736. }
  2737. }
  2738. #ifdef CPPHTTPLIB_SSL_ENABLED
  2739. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2740. auto host = "httpbingo.org";
  2741. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2742. auto paths = std::vector<std::string>{
  2743. "/digest-auth/auth/hello/world/MD5",
  2744. "/digest-auth/auth/hello/world/SHA-256",
  2745. };
  2746. auto port = 443;
  2747. SSLClient cli(host, port);
  2748. {
  2749. auto res = cli.Get(unauth_path);
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2752. }
  2753. {
  2754. cli.set_digest_auth("hello", "world");
  2755. for (const auto &path : paths) {
  2756. auto res = cli.Get(path.c_str());
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. auto body = remove_whitespace(res->body);
  2759. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2760. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. }
  2763. cli.set_digest_auth("hello", "bad");
  2764. for (const auto &path : paths) {
  2765. auto res = cli.Get(path.c_str());
  2766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2767. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2768. }
  2769. }
  2770. }
  2771. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2772. // comma-separated list of challenges, and each challenge may itself carry a
  2773. // comma-separated auth-param list, so a server can legally offer Basic
  2774. // before Digest, either as two field lines or packed into one. Runs one 401
  2775. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2776. // value() joins them in receipt order) and checks that the retry carries a
  2777. // well-formed Digest Authorization header naming expected_realm.
  2778. static void
  2779. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2780. const std::string &expected_realm) {
  2781. std::atomic<int> hits{0};
  2782. Server svr;
  2783. svr.Get("/x", [&](const Request &req, Response &res) {
  2784. if (++hits == 1) {
  2785. res.status = StatusCode::Unauthorized_401;
  2786. for (const auto &challenge : challenges) {
  2787. res.set_header("WWW-Authenticate", challenge);
  2788. }
  2789. } else {
  2790. auto authorization = req.get_header_value("Authorization");
  2791. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2792. EXPECT_NE(std::string::npos,
  2793. authorization.find("realm=\"" + expected_realm + "\""));
  2794. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2795. res.set_content("ok", "text/plain");
  2796. }
  2797. });
  2798. auto port = svr.bind_to_any_port(HOST);
  2799. std::thread t([&]() { svr.listen_after_bind(); });
  2800. auto se = detail::scope_exit([&] {
  2801. svr.stop();
  2802. t.join();
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(HOST, port);
  2806. cli.set_digest_auth("hello", "world");
  2807. auto res = cli.Get("/x");
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(2, hits.load());
  2810. }
  2811. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2812. static const char *kDigestChallenge =
  2813. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2814. "algorithm=MD5";
  2815. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2816. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2817. "testrealm");
  2818. }
  2819. // Same challenge list with the schemes in the opposite order, to make sure
  2820. // the fix above didn't just special-case "Basic first".
  2821. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2822. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2823. "testrealm");
  2824. }
  2825. // A comma inside a quoted auth-param value must not be mistaken for the
  2826. // separator between two challenges (or two auth-params).
  2827. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2828. run_digest_challenge_list_test(
  2829. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2830. "algorithm=MD5"},
  2831. "test,realm");
  2832. }
  2833. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2834. // make_digest_authentication_header() dereferences both unconditionally, so
  2835. // a server sending a challenge missing either one must not be treated as
  2836. // usable -- doing so used to crash the client with std::out_of_range.
  2837. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2838. Server svr;
  2839. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2840. res.status = StatusCode::Unauthorized_401;
  2841. res.set_header("WWW-Authenticate", challenge);
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. std::thread t([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. t.join();
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, port);
  2851. cli.set_digest_auth("hello", "world");
  2852. auto res = cli.Get("/x");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2855. }
  2856. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2857. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2858. }
  2859. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2860. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2861. }
  2862. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2863. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2864. }
  2865. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2866. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2867. // when storing the values, so the header builder has to re-escape them (and
  2868. // keep algorithm a bare token); otherwise the value breaks out of its
  2869. // quoted-string and injects extra auth-params into the client's Authorization.
  2870. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2871. std::atomic<int> hits{0};
  2872. std::string authorization;
  2873. Server svr;
  2874. svr.Get("/x", [&](const Request &req, Response &res) {
  2875. if (++hits == 1) {
  2876. res.status = StatusCode::Unauthorized_401;
  2877. // On the wire the quotes embedded in the values are backslash-escaped.
  2878. res.set_header("WWW-Authenticate",
  2879. "Digest realm=\"testrealm\", "
  2880. "nonce=\"n\\\"; injected=\\\"x\", "
  2881. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2882. } else {
  2883. authorization = req.get_header_value("Authorization");
  2884. res.set_content("ok", "text/plain");
  2885. }
  2886. });
  2887. auto port = svr.bind_to_any_port(HOST);
  2888. std::thread t([&]() { svr.listen_after_bind(); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. t.join();
  2892. });
  2893. svr.wait_until_ready();
  2894. Client cli(HOST, port);
  2895. cli.set_digest_auth("hello", "world");
  2896. auto res = cli.Get("/x");
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(2, hits.load());
  2899. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2900. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2901. // inside its quoted-string rather than starting an "injected" auth-param.
  2902. EXPECT_NE(std::string::npos,
  2903. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2904. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2905. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2906. }
  2907. #endif
  2908. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2909. auto host = "google.com";
  2910. auto another_host = "example.com";
  2911. auto wrong_ip = "0.0.0.0";
  2912. #ifdef CPPHTTPLIB_SSL_ENABLED
  2913. SSLClient cli(host);
  2914. #else
  2915. Client cli(host);
  2916. #endif
  2917. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2918. auto res = cli.Get("/");
  2919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2920. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2921. }
  2922. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2923. auto host = "google.com";
  2924. auto wrong_ip = "0.0.0.0";
  2925. #ifdef CPPHTTPLIB_SSL_ENABLED
  2926. SSLClient cli(host);
  2927. #else
  2928. Client cli(host);
  2929. #endif
  2930. cli.set_hostname_addr_map({{host, wrong_ip}});
  2931. auto res = cli.Get("/");
  2932. ASSERT_TRUE(!res);
  2933. EXPECT_EQ(Error::Connection, res.error());
  2934. }
  2935. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2936. // A mapped value that is not an IP literal must be resolved. "localhost"
  2937. // resolves from the hosts file, so this test needs no external DNS.
  2938. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2939. auto host = "target.invalid";
  2940. Server svr;
  2941. std::string received_host;
  2942. svr.Get("/hi", [&](const Request &req, Response &res) {
  2943. received_host = req.get_header_value("Host");
  2944. res.set_content("Hello World!", "text/plain");
  2945. });
  2946. auto port = svr.bind_to_any_port(HOST);
  2947. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2948. auto se = detail::scope_exit([&] {
  2949. svr.stop();
  2950. thread.join();
  2951. ASSERT_FALSE(svr.is_running());
  2952. });
  2953. svr.wait_until_ready();
  2954. Client cli(host, port);
  2955. cli.set_hostname_addr_map({{host, HOST}});
  2956. auto res = cli.Get("/hi");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. // The mapping only redirects the connection; the identity stays host_.
  2960. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2961. }
  2962. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2963. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2964. auto host = "target.invalid";
  2965. Server svr;
  2966. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2967. res.set_content("Hello World!", "text/plain");
  2968. });
  2969. auto port = svr.bind_to_any_port("127.0.0.1");
  2970. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. thread.join();
  2974. ASSERT_FALSE(svr.is_running());
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(host, port);
  2978. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2979. auto res = cli.Get("/hi");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(StatusCode::OK_200, res->status);
  2982. }
  2983. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2984. // An empty mapped value must leave host_ as the connection target. Without
  2985. // that guard the empty value would become the host argument, getaddrinfo
  2986. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2987. // loopback - silently connecting somewhere the caller never asked for.
  2988. // The server listens on loopback, so such a fallback would succeed and is
  2989. // therefore observable as a failure of this test.
  2990. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2991. Server svr;
  2992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2993. res.set_content("Hello World!", "text/plain");
  2994. });
  2995. auto port = svr.bind_to_any_port(HOST);
  2996. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. Client cli(blackhole, port);
  3004. cli.set_hostname_addr_map({{blackhole, ""}});
  3005. cli.set_connection_timeout(1);
  3006. auto res = cli.Get("/hi");
  3007. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3008. }
  3009. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3010. auto host = "httpbingo.org";
  3011. auto path = std::string{"/absolute-redirect/3"};
  3012. #ifdef CPPHTTPLIB_SSL_ENABLED
  3013. SSLClient cli(host);
  3014. #else
  3015. Client cli(host);
  3016. #endif
  3017. cli.set_follow_location(true);
  3018. auto res = cli.Get(path);
  3019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3020. EXPECT_EQ(StatusCode::OK_200, res->status);
  3021. }
  3022. TEST(RedirectTest, Redirect_Online) {
  3023. auto host = "httpbingo.org";
  3024. auto path = std::string{"/redirect/3"};
  3025. #ifdef CPPHTTPLIB_SSL_ENABLED
  3026. SSLClient cli(host);
  3027. #else
  3028. Client cli(host);
  3029. #endif
  3030. cli.set_follow_location(true);
  3031. auto res = cli.Get(path);
  3032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. }
  3035. TEST(RelativeRedirectTest, Redirect_Online) {
  3036. auto host = "httpbingo.org";
  3037. auto path = std::string{"/relative-redirect/3"};
  3038. #ifdef CPPHTTPLIB_SSL_ENABLED
  3039. SSLClient cli(host);
  3040. #else
  3041. Client cli(host);
  3042. #endif
  3043. cli.set_follow_location(true);
  3044. auto res = cli.Get(path);
  3045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3046. EXPECT_EQ(StatusCode::OK_200, res->status);
  3047. }
  3048. TEST(TooManyRedirectTest, Redirect_Online) {
  3049. auto host = "httpbingo.org";
  3050. auto path = std::string{"/redirect/21"};
  3051. #ifdef CPPHTTPLIB_SSL_ENABLED
  3052. SSLClient cli(host);
  3053. #else
  3054. Client cli(host);
  3055. #endif
  3056. cli.set_follow_location(true);
  3057. auto res = cli.Get(path);
  3058. ASSERT_TRUE(!res);
  3059. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3060. }
  3061. #ifdef CPPHTTPLIB_SSL_ENABLED
  3062. TEST(YahooRedirectTest, Redirect_Online) {
  3063. Client cli("yahoo.com");
  3064. auto res = cli.Get("/");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3067. cli.set_follow_location(true);
  3068. res = cli.Get("/");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3072. }
  3073. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3074. #define REDIR_HOST "httpbingo.org"
  3075. #define REDIR_PATH "/redirect-to"
  3076. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3077. SSLClient cli(REDIR_HOST);
  3078. cli.set_follow_location(true);
  3079. auto res =
  3080. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3082. EXPECT_EQ(StatusCode::OK_200, res->status);
  3083. }
  3084. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3085. SSLClient cli(REDIR_HOST);
  3086. cli.set_follow_location(true);
  3087. Params params;
  3088. params.emplace("url", "http://example.com");
  3089. params.emplace("status_code", "302");
  3090. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. EXPECT_EQ(StatusCode::OK_200, res->status);
  3093. }
  3094. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3095. SSLClient cli(REDIR_HOST);
  3096. cli.set_follow_location(true);
  3097. Params params;
  3098. params.emplace("url", "http://example.com");
  3099. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3101. EXPECT_EQ(StatusCode::OK_200, res->status);
  3102. }
  3103. TEST(UrlWithSpace, Redirect_Online) {
  3104. SSLClient cli("edge.forgecdn.net");
  3105. cli.set_follow_location(true);
  3106. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3110. }
  3111. #endif
  3112. #if !defined(_WIN32) && !defined(_WIN64)
  3113. TEST(ReceiveSignals, Signal) {
  3114. auto setupSignalHandlers = []() {
  3115. struct sigaction act;
  3116. sigemptyset(&act.sa_mask);
  3117. act.sa_flags = SA_SIGINFO;
  3118. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3119. switch (sig) {
  3120. case SIGINT:
  3121. default: break;
  3122. }
  3123. };
  3124. ::sigaction(SIGINT, &act, nullptr);
  3125. };
  3126. Server svr;
  3127. int port = 0;
  3128. auto thread = std::thread([&]() {
  3129. setupSignalHandlers();
  3130. port = svr.bind_to_any_port(HOST);
  3131. svr.listen_after_bind();
  3132. });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. ASSERT_TRUE(svr.is_running());
  3140. pthread_kill(thread.native_handle(), SIGINT);
  3141. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3142. ASSERT_TRUE(svr.is_running());
  3143. }
  3144. #endif
  3145. TEST(RedirectToDifferentPort, Redirect) {
  3146. Server svr1;
  3147. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3148. res.set_content("Hello World!", "text/plain");
  3149. });
  3150. int svr1_port = 0;
  3151. auto thread1 = std::thread([&]() {
  3152. svr1_port = svr1.bind_to_any_port(HOST);
  3153. svr1.listen_after_bind();
  3154. });
  3155. Server svr2;
  3156. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3157. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3158. });
  3159. int svr2_port = 0;
  3160. auto thread2 = std::thread([&]() {
  3161. svr2_port = svr2.bind_to_any_port(HOST);
  3162. svr2.listen_after_bind();
  3163. });
  3164. auto se = detail::scope_exit([&] {
  3165. svr2.stop();
  3166. thread2.join();
  3167. svr1.stop();
  3168. thread1.join();
  3169. ASSERT_FALSE(svr2.is_running());
  3170. ASSERT_FALSE(svr1.is_running());
  3171. });
  3172. svr1.wait_until_ready();
  3173. svr2.wait_until_ready();
  3174. Client cli("localhost", svr2_port);
  3175. cli.set_follow_location(true);
  3176. auto res = cli.Get("/2");
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("Hello World!", res->body);
  3180. }
  3181. // GET /redir on one server redirects to /target on another port, so the
  3182. // client follows it with a new client.
  3183. static Result
  3184. GetThroughRedirectToDifferentPort(Server::Handler target,
  3185. const std::function<void(Client &)> &setup,
  3186. const Headers &headers = Headers()) {
  3187. Server target_svr;
  3188. target_svr.Get("/target", target);
  3189. int target_port = 0;
  3190. auto target_thread = std::thread([&]() {
  3191. target_port = target_svr.bind_to_any_port(HOST);
  3192. target_svr.listen_after_bind();
  3193. });
  3194. Server origin_svr;
  3195. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3196. res.set_redirect(
  3197. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3198. });
  3199. int origin_port = 0;
  3200. auto origin_thread = std::thread([&]() {
  3201. origin_port = origin_svr.bind_to_any_port(HOST);
  3202. origin_svr.listen_after_bind();
  3203. });
  3204. auto se = detail::scope_exit([&] {
  3205. origin_svr.stop();
  3206. origin_thread.join();
  3207. target_svr.stop();
  3208. target_thread.join();
  3209. });
  3210. target_svr.wait_until_ready();
  3211. origin_svr.wait_until_ready();
  3212. Client cli("localhost", origin_port);
  3213. cli.set_follow_location(true);
  3214. setup(cli);
  3215. return cli.Get("/redir", headers);
  3216. }
  3217. static void
  3218. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3219. std::string captured_authorization;
  3220. auto result = GetThroughRedirectToDifferentPort(
  3221. [&](const Request &req, Response &res) {
  3222. captured_authorization = req.get_header_value("Authorization");
  3223. res.set_content("OK", "text/plain");
  3224. },
  3225. set_auth);
  3226. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3227. EXPECT_EQ(StatusCode::OK_200, result->status);
  3228. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3229. EXPECT_TRUE(captured_authorization.empty());
  3230. }
  3231. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3232. TestDoNotForwardCredentialsOnRedirect(
  3233. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3234. }
  3235. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3236. TestDoNotForwardCredentialsOnRedirect(
  3237. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3238. }
  3239. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3240. std::string captured_cookie;
  3241. auto result = GetThroughRedirectToDifferentPort(
  3242. [&](const Request &req, Response &res) {
  3243. captured_cookie = req.get_header_value("Cookie");
  3244. res.set_content("OK", "text/plain");
  3245. },
  3246. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3247. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3248. EXPECT_EQ(StatusCode::OK_200, result->status);
  3249. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3250. EXPECT_TRUE(captured_cookie.empty());
  3251. }
  3252. TEST(RedirectToSamePort, ForwardCookie) {
  3253. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3254. // header so that ordinary session flows keep working.
  3255. Server svr;
  3256. std::string captured_cookie;
  3257. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3258. res.set_redirect("/target", 302);
  3259. });
  3260. svr.Get("/target", [&](const Request &req, Response &res) {
  3261. captured_cookie = req.get_header_value("Cookie");
  3262. res.set_content("OK", "text/plain");
  3263. });
  3264. auto port = svr.bind_to_any_port(HOST);
  3265. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3266. auto se = detail::scope_exit([&] {
  3267. svr.stop();
  3268. thread.join();
  3269. ASSERT_FALSE(svr.is_running());
  3270. });
  3271. svr.wait_until_ready();
  3272. Client cli(HOST, port);
  3273. cli.set_follow_location(true);
  3274. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3275. auto res = cli.Get("/redir", headers);
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3279. }
  3280. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3281. std::string authorization;
  3282. std::string trace_id;
  3283. auto result = GetThroughRedirectToDifferentPort(
  3284. [&](const Request &req, Response &res) {
  3285. authorization = req.get_header_value("Authorization");
  3286. trace_id = req.get_header_value("X-Trace-Id");
  3287. res.set_content("OK", "text/plain");
  3288. },
  3289. [](Client &cli) {
  3290. cli.set_default_headers(
  3291. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3292. });
  3293. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3294. EXPECT_EQ(StatusCode::OK_200, result->status);
  3295. // Like a header given with the request, a default one goes along unless it
  3296. // carries credentials (RFC 9110 15.4).
  3297. EXPECT_TRUE(authorization.empty());
  3298. EXPECT_EQ("42", trace_id);
  3299. }
  3300. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3301. auto result = GetThroughRedirectToDifferentPort(
  3302. [](const Request &, Response &res) {
  3303. res.set_content(std::string(2048, 'x'), "text/plain");
  3304. },
  3305. [](Client &cli) { cli.set_payload_max_length(1024); });
  3306. EXPECT_FALSE(result);
  3307. }
  3308. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3309. auto result = GetThroughRedirectToDifferentPort(
  3310. [](const Request &req, Response &res) {
  3311. // Answer after a second, or once the client gives up.
  3312. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3314. }
  3315. res.set_content("late", "text/plain");
  3316. },
  3317. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3318. ASSERT_FALSE(result);
  3319. EXPECT_EQ(Error::Read, result.error());
  3320. }
  3321. #ifdef CPPHTTPLIB_SSL_ENABLED
  3322. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3323. auto result = GetThroughRedirectToDifferentPort(
  3324. [](const Request &, Response &res) {
  3325. res.status = StatusCode::Unauthorized_401;
  3326. res.set_header("WWW-Authenticate",
  3327. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3328. },
  3329. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3332. }
  3333. #endif
  3334. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3335. Server svr;
  3336. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3337. // Port number that overflows int — should not crash
  3338. res.set_redirect("http://localhost:99999999999999999999/target");
  3339. });
  3340. auto port = svr.bind_to_any_port(HOST);
  3341. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3342. auto se = detail::scope_exit([&] {
  3343. svr.stop();
  3344. thread.join();
  3345. ASSERT_FALSE(svr.is_running());
  3346. });
  3347. svr.wait_until_ready();
  3348. Client cli(HOST, port);
  3349. cli.set_follow_location(true);
  3350. auto res = cli.Get("/redir");
  3351. // Should fail gracefully, not crash (no valid response due to bad port)
  3352. EXPECT_FALSE(res);
  3353. }
  3354. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3355. Server svr;
  3356. auto port = svr.bind_to_any_port(HOST);
  3357. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3358. // The server's own port followed by junk must not be followed
  3359. res.set_redirect("http://" + std::string(HOST) + ":" +
  3360. std::to_string(port) + "junk/target");
  3361. });
  3362. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3363. res.set_content("target", "text/plain");
  3364. });
  3365. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3366. auto se = detail::scope_exit([&] {
  3367. svr.stop();
  3368. thread.join();
  3369. ASSERT_FALSE(svr.is_running());
  3370. });
  3371. svr.wait_until_ready();
  3372. Client cli(HOST, port);
  3373. cli.set_follow_location(true);
  3374. auto res = cli.Get("/redir");
  3375. EXPECT_FALSE(res);
  3376. }
  3377. TEST(RedirectFromPageWithContent, Redirect) {
  3378. Server svr;
  3379. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3380. res.set_content("___", "text/plain");
  3381. res.set_redirect("/2");
  3382. });
  3383. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3384. res.set_content("Hello World!", "text/plain");
  3385. });
  3386. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3387. auto se = detail::scope_exit([&] {
  3388. svr.stop();
  3389. th.join();
  3390. ASSERT_FALSE(svr.is_running());
  3391. });
  3392. svr.wait_until_ready();
  3393. {
  3394. Client cli("localhost", PORT);
  3395. cli.set_follow_location(true);
  3396. std::string body;
  3397. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3398. body.append(data, data_length);
  3399. return true;
  3400. });
  3401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3402. EXPECT_EQ(StatusCode::OK_200, res->status);
  3403. EXPECT_EQ("Hello World!", body);
  3404. }
  3405. {
  3406. Client cli("localhost", PORT);
  3407. std::string body;
  3408. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::Found_302, res->status);
  3414. EXPECT_EQ("___", body);
  3415. }
  3416. }
  3417. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3418. Server svr;
  3419. auto port_str = std::to_string(PORT);
  3420. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3421. auto expected_host = "[::1]:" + port_str;
  3422. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3423. res.set_content("___", "text/plain");
  3424. // res.set_redirect("/2");
  3425. res.set_redirect(redirect_url);
  3426. });
  3427. svr.Get("/2", [&](const Request &req, Response &res) {
  3428. auto host_header = req.headers.find("Host");
  3429. ASSERT_TRUE(host_header != req.headers.end());
  3430. EXPECT_EQ(expected_host, host_header->second);
  3431. res.set_content("Hello World!", "text/plain");
  3432. });
  3433. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3434. auto se = detail::scope_exit([&] {
  3435. svr.stop();
  3436. th.join();
  3437. ASSERT_FALSE(svr.is_running());
  3438. });
  3439. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3440. // actually starts anything, so the condition !svr.is_running() will
  3441. // always remain true, and the loop never stops.
  3442. // This basically counts how many milliseconds have passed since the
  3443. // call to svr.listen(), and if after 5 seconds nothing started yet
  3444. // aborts the test.
  3445. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3446. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3447. ASSERT_LT(milliseconds, 5000U);
  3448. }
  3449. {
  3450. Client cli("::1", PORT);
  3451. cli.set_follow_location(true);
  3452. std::string body;
  3453. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3454. body.append(data, data_length);
  3455. return true;
  3456. });
  3457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("Hello World!", body);
  3460. }
  3461. {
  3462. Client cli("::1", PORT);
  3463. std::string body;
  3464. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3465. body.append(data, data_length);
  3466. return true;
  3467. });
  3468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3469. EXPECT_EQ(StatusCode::Found_302, res->status);
  3470. EXPECT_EQ("___", body);
  3471. }
  3472. }
  3473. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3474. Server svr;
  3475. svr.Get("/foo", [](const Request &req, Response &res) {
  3476. auto a = req.params.find("a");
  3477. if (a != req.params.end()) {
  3478. res.set_content((*a).second, "text/plain");
  3479. res.status = StatusCode::OK_200;
  3480. } else {
  3481. res.status = StatusCode::BadRequest_400;
  3482. }
  3483. });
  3484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. thread.join();
  3488. ASSERT_FALSE(svr.is_running());
  3489. });
  3490. svr.wait_until_ready();
  3491. {
  3492. Client cli(HOST, PORT);
  3493. cli.set_path_encode(false);
  3494. auto res = cli.Get("/foo?a=explicitly+encoded");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. // This expects it back with a space, as the `+` won't have been
  3498. // url-encoded, and server-side the params get decoded turning `+`
  3499. // into spaces.
  3500. EXPECT_EQ("explicitly encoded", res->body);
  3501. }
  3502. }
  3503. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3504. // When path encoding is disabled the client must transmit the supplied
  3505. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3506. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3507. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3508. // than a space (0x20). Assert on the raw wire target to catch this.
  3509. Server svr;
  3510. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3511. svr.Get("/foo", [&](const Request &req, Response &res) {
  3512. EXPECT_EQ(expected_target, req.target);
  3513. res.status = StatusCode::OK_200;
  3514. });
  3515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3516. auto se = detail::scope_exit([&] {
  3517. svr.stop();
  3518. thread.join();
  3519. ASSERT_FALSE(svr.is_running());
  3520. });
  3521. svr.wait_until_ready();
  3522. {
  3523. Client cli(HOST, PORT);
  3524. cli.set_path_encode(false);
  3525. auto res = cli.Get(expected_target.c_str());
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ(StatusCode::OK_200, res->status);
  3528. }
  3529. }
  3530. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3531. // `open_stream()` used to skip the path encoding that the buffered send
  3532. // path applies, so the same `path` produced different bytes in the request
  3533. // line depending on which API was used. Assert the two agree.
  3534. Server svr;
  3535. std::string target;
  3536. svr.Get(".*", [&](const Request &req, Response &res) {
  3537. target = req.target;
  3538. res.status = StatusCode::OK_200;
  3539. });
  3540. auto port = svr.bind_to_any_port(HOST);
  3541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3542. auto se = detail::scope_exit([&] {
  3543. svr.stop();
  3544. thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. });
  3547. svr.wait_until_ready();
  3548. struct {
  3549. const char *path;
  3550. const char *expected;
  3551. } cases[] = {
  3552. {"/a b?x=1", "/a%20b?x=1"},
  3553. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3554. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3555. };
  3556. for (const auto &c : cases) {
  3557. Client cli(HOST, port);
  3558. target.clear();
  3559. auto res = cli.Get(c.path);
  3560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3561. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3562. auto buffered_target = target;
  3563. target.clear();
  3564. auto handle = cli.open_stream("GET", c.path);
  3565. EXPECT_TRUE(handle.is_valid())
  3566. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3567. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3568. }
  3569. }
  3570. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3571. // The `set_path_encode(false)` contract — transmit the supplied target
  3572. // verbatim — must hold for the streaming API too.
  3573. Server svr;
  3574. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3575. std::string target;
  3576. svr.Get("/foo", [&](const Request &req, Response &res) {
  3577. target = req.target;
  3578. res.status = StatusCode::OK_200;
  3579. });
  3580. auto port = svr.bind_to_any_port(HOST);
  3581. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. thread.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli(HOST, port);
  3590. cli.set_path_encode(false);
  3591. auto handle = cli.open_stream("GET", expected_target);
  3592. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3593. EXPECT_EQ(expected_target, target);
  3594. }
  3595. }
  3596. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3597. // With path encoding enabled a CR/LF in the target is percent-encoded
  3598. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3599. // write_request_line still backstops `set_path_encode(false)`, which is
  3600. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3601. Server svr;
  3602. // Captured before routing: the decoded path contains a newline, which a
  3603. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3604. std::string target;
  3605. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3606. target = req.target;
  3607. res.status = StatusCode::OK_200;
  3608. return Server::HandlerResponse::Handled;
  3609. });
  3610. auto port = svr.bind_to_any_port(HOST);
  3611. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3612. auto se = detail::scope_exit([&] {
  3613. svr.stop();
  3614. thread.join();
  3615. ASSERT_FALSE(svr.is_running());
  3616. });
  3617. svr.wait_until_ready();
  3618. {
  3619. Client cli(HOST, port);
  3620. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3621. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3622. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3623. }
  3624. }
  3625. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3626. // Every control character is percent-encoded, not just CR/LF, so the target
  3627. // passes the request-target check in write_request_line.
  3628. Server svr;
  3629. std::string target;
  3630. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3631. target = req.target;
  3632. res.status = StatusCode::OK_200;
  3633. return Server::HandlerResponse::Handled;
  3634. });
  3635. auto port = svr.bind_to_any_port(HOST);
  3636. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3637. auto se = detail::scope_exit([&] {
  3638. svr.stop();
  3639. thread.join();
  3640. ASSERT_FALSE(svr.is_running());
  3641. });
  3642. svr.wait_until_ready();
  3643. {
  3644. Client cli(HOST, port);
  3645. auto res = cli.Get("/a\tb\x1b\x7f");
  3646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3647. EXPECT_EQ("/a%09b%1B%7F", target);
  3648. }
  3649. }
  3650. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3651. // Nothing may reach the wire: a raw CR/LF target would split the request
  3652. // line and inject headers.
  3653. Server svr;
  3654. // Pre-routing so that "not called" means nothing reached the server at all,
  3655. // rather than merely failing to match a handler pattern.
  3656. auto handler_called = false;
  3657. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3658. handler_called = true;
  3659. res.status = StatusCode::OK_200;
  3660. return Server::HandlerResponse::Handled;
  3661. });
  3662. auto port = svr.bind_to_any_port(HOST);
  3663. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3664. auto se = detail::scope_exit([&] {
  3665. svr.stop();
  3666. thread.join();
  3667. ASSERT_FALSE(svr.is_running());
  3668. });
  3669. svr.wait_until_ready();
  3670. {
  3671. Client cli(HOST, port);
  3672. cli.set_path_encode(false);
  3673. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3674. EXPECT_FALSE(handle.is_valid());
  3675. EXPECT_EQ(Error::Write, handle.error);
  3676. EXPECT_FALSE(handler_called);
  3677. }
  3678. }
  3679. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3680. // Which of the two branches runs is decided by whether the query component
  3681. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3682. // an empty query and must still fall back to building one from
  3683. // `req.params`, while a non-empty query must win over `req.params`.
  3684. Server svr;
  3685. std::string target;
  3686. svr.Get("/foo", [&](const Request &req, Response &res) {
  3687. target = req.target;
  3688. res.status = StatusCode::OK_200;
  3689. });
  3690. auto port = svr.bind_to_any_port(HOST);
  3691. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3692. auto se = detail::scope_exit([&] {
  3693. svr.stop();
  3694. thread.join();
  3695. ASSERT_FALSE(svr.is_running());
  3696. });
  3697. svr.wait_until_ready();
  3698. {
  3699. // Trailing `?` -> empty query component -> `req.params` is used.
  3700. Client cli(HOST, port);
  3701. Request req;
  3702. req.method = "GET";
  3703. req.path = "/foo?";
  3704. req.params.emplace("a", "1");
  3705. target.clear();
  3706. auto res = cli.send(req);
  3707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3708. EXPECT_EQ("/foo?a=1", target);
  3709. }
  3710. {
  3711. // Non-empty query in `req.path` -> `req.params` is not appended.
  3712. Client cli(HOST, port);
  3713. Request req;
  3714. req.method = "GET";
  3715. req.path = "/foo?b=2";
  3716. req.params.emplace("a", "1");
  3717. target.clear();
  3718. auto res = cli.send(req);
  3719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3720. EXPECT_EQ("/foo?b=2", target);
  3721. }
  3722. }
  3723. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3724. Server svr;
  3725. svr.Get("/", [](const Request &req, Response &) {
  3726. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3727. });
  3728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3729. auto se = detail::scope_exit([&] {
  3730. svr.stop();
  3731. thread.join();
  3732. ASSERT_FALSE(svr.is_running());
  3733. });
  3734. svr.wait_until_ready();
  3735. {
  3736. Client cli(HOST, PORT);
  3737. cli.set_path_encode(false);
  3738. auto res = cli.Get("/?something=%0A");
  3739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. }
  3743. TEST(BindServerTest, BindDualStack) {
  3744. Server svr;
  3745. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3746. res.set_content("Hello World!", "text/plain");
  3747. });
  3748. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli("127.0.0.1", PORT);
  3757. auto res = cli.Get("/1");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("Hello World!", res->body);
  3761. }
  3762. {
  3763. Client cli("::1", PORT);
  3764. auto res = cli.Get("/1");
  3765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("Hello World!", res->body);
  3768. }
  3769. }
  3770. TEST(BindServerTest, BindAndListenSeparately) {
  3771. Server svr;
  3772. int port = svr.bind_to_any_port("0.0.0.0");
  3773. ASSERT_TRUE(svr.is_valid());
  3774. ASSERT_TRUE(port > 0);
  3775. svr.stop();
  3776. }
  3777. // Reports whether anything is still listening on a loopback port. A plain
  3778. // connect() is used instead of a Client request because a socket left bound by
  3779. // mistake accepts the connection into its backlog and never answers, which
  3780. // would hang the test instead of failing it.
  3781. static bool is_loopback_port_accepting(int port) {
  3782. sockaddr_in addr{};
  3783. addr.sin_family = AF_INET;
  3784. addr.sin_port = htons(static_cast<uint16_t>(port));
  3785. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3786. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3787. EXPECT_NE(sock, INVALID_SOCKET);
  3788. if (sock == INVALID_SOCKET) { return false; }
  3789. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3790. static_cast<socklen_t>(sizeof(addr)));
  3791. detail::close_socket(sock);
  3792. return ret == 0;
  3793. }
  3794. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3795. Server svr;
  3796. auto port = svr.bind_to_any_port("127.0.0.1");
  3797. ASSERT_TRUE(port > 0);
  3798. svr.stop();
  3799. // bind_to_any_port() already called listen(2), so until stop() closed the
  3800. // descriptor the port kept accepting connections into the backlog. ASSERT
  3801. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3802. // below blocks forever in the accept loop.
  3803. ASSERT_FALSE(is_loopback_port_accepting(port));
  3804. // Nothing is left to accept on, so listen_after_bind() must report failure
  3805. // instead of returning success without ever serving.
  3806. EXPECT_FALSE(svr.listen_after_bind());
  3807. // The failed listen marks the server decommissioned, so a waiter returns
  3808. // instead of spinning forever.
  3809. svr.wait_until_ready();
  3810. }
  3811. #ifdef CPPHTTPLIB_SSL_ENABLED
  3812. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3814. CLIENT_CA_CERT_DIR);
  3815. int port = svr.bind_to_any_port("0.0.0.0");
  3816. ASSERT_TRUE(svr.is_valid());
  3817. ASSERT_TRUE(port > 0);
  3818. svr.stop();
  3819. }
  3820. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3821. // or a rejected CustomRoute() registration would not stop the server binding.
  3822. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3824. CLIENT_CA_CERT_DIR);
  3825. ASSERT_TRUE(svr.is_valid());
  3826. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3827. EXPECT_FALSE(svr.is_valid());
  3828. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3829. }
  3830. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3831. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3832. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3833. int port = svr.bind_to_any_port("0.0.0.0");
  3834. ASSERT_TRUE(svr.is_valid());
  3835. ASSERT_TRUE(port > 0);
  3836. svr.stop();
  3837. }
  3838. TEST(BindServerTest, UpdateCertsPem) {
  3839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3840. int port = svr.bind_to_any_port("0.0.0.0");
  3841. ASSERT_TRUE(svr.is_valid());
  3842. ASSERT_TRUE(port > 0);
  3843. // Read PEM files
  3844. std::string cert_pem, key_pem, ca_pem;
  3845. read_file(SERVER_CERT_FILE, cert_pem);
  3846. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3847. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3848. // Update server certificates using PEM API
  3849. ASSERT_TRUE(
  3850. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3851. ASSERT_TRUE(svr.is_valid());
  3852. svr.stop();
  3853. }
  3854. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3855. // Start server with client CA (enables client auth)
  3856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3857. ASSERT_TRUE(svr.is_valid());
  3858. bool handler_called = false;
  3859. svr.Get("/test", [&](const Request &req, Response &res) {
  3860. handler_called = true;
  3861. // Verify client certificate is present
  3862. auto cert = req.peer_cert();
  3863. EXPECT_TRUE(static_cast<bool>(cert));
  3864. res.set_content("ok", "text/plain");
  3865. });
  3866. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. t.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. // Read PEM files
  3874. std::string cert_pem, key_pem, ca_pem;
  3875. read_file(SERVER_CERT_FILE, cert_pem);
  3876. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3877. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3878. // Update server certificates and client CA using PEM API while server running
  3879. ASSERT_TRUE(
  3880. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3881. // Connect with client certificate
  3882. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3883. cli.enable_server_certificate_verification(false);
  3884. cli.set_connection_timeout(30);
  3885. auto res = cli.Get("/test");
  3886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3887. ASSERT_EQ(StatusCode::OK_200, res->status);
  3888. ASSERT_TRUE(handler_called);
  3889. EXPECT_EQ("ok", res->body);
  3890. }
  3891. #endif
  3892. TEST(ErrorHandlerTest, ContentLength) {
  3893. Server svr;
  3894. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3895. res.status = StatusCode::OK_200;
  3896. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3897. "text/html"); // <= Content-Length still 13
  3898. });
  3899. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3900. res.set_content("Hello World!\n", "text/plain");
  3901. res.status = 524;
  3902. });
  3903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3904. auto se = detail::scope_exit([&] {
  3905. svr.stop();
  3906. thread.join();
  3907. ASSERT_FALSE(svr.is_running());
  3908. });
  3909. svr.wait_until_ready();
  3910. {
  3911. Client cli(HOST, PORT);
  3912. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3914. EXPECT_EQ(StatusCode::OK_200, res->status);
  3915. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3916. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3917. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3918. }
  3919. }
  3920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3921. TEST(ExceptionTest, WithoutExceptionHandler) {
  3922. Server svr;
  3923. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3924. throw std::runtime_error("exception...");
  3925. });
  3926. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3927. throw std::runtime_error("exception\r\n...");
  3928. });
  3929. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. listen_thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. Client cli("localhost", PORT);
  3937. {
  3938. auto res = cli.Get("/exception");
  3939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3940. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3941. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3942. }
  3943. {
  3944. auto res = cli.Get("/unknown");
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3947. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3948. }
  3949. }
  3950. TEST(ExceptionTest, WithExceptionHandler) {
  3951. Server svr;
  3952. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3953. std::exception_ptr ep) {
  3954. EXPECT_FALSE(ep == nullptr);
  3955. try {
  3956. std::rethrow_exception(ep);
  3957. } catch (std::exception &e) {
  3958. EXPECT_EQ("abc", std::string(e.what()));
  3959. } catch (...) {}
  3960. res.status = StatusCode::InternalServerError_500;
  3961. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3962. "text/html"); // <= Content-Length still 13 at this point
  3963. });
  3964. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3965. res.set_content("Hello World!\n", "text/plain");
  3966. throw std::runtime_error("abc");
  3967. });
  3968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3969. auto se = detail::scope_exit([&] {
  3970. svr.stop();
  3971. thread.join();
  3972. ASSERT_FALSE(svr.is_running());
  3973. });
  3974. svr.wait_until_ready();
  3975. for (size_t i = 0; i < 10; i++) {
  3976. Client cli(HOST, PORT);
  3977. for (size_t j = 0; j < 100; j++) {
  3978. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3980. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3981. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3982. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3983. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3984. }
  3985. cli.set_keep_alive(true);
  3986. for (size_t j = 0; j < 100; j++) {
  3987. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3989. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3990. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3991. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3992. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3993. }
  3994. }
  3995. }
  3996. TEST(ExceptionTest, AndErrorHandler) {
  3997. Server svr;
  3998. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3999. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4000. });
  4001. svr.set_exception_handler(
  4002. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4003. EXPECT_FALSE(ep == nullptr);
  4004. try {
  4005. std::rethrow_exception(ep);
  4006. } catch (std::exception &e) {
  4007. res.set_content(e.what(), "text/html");
  4008. } catch (...) {}
  4009. res.status = StatusCode::InternalServerError_500;
  4010. });
  4011. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4012. throw std::runtime_error("EXCEPTION");
  4013. });
  4014. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4015. res.set_content("ERROR", "text/html");
  4016. res.status = StatusCode::InternalServerError_500;
  4017. });
  4018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4019. auto se = detail::scope_exit([&] {
  4020. svr.stop();
  4021. thread.join();
  4022. ASSERT_FALSE(svr.is_running());
  4023. });
  4024. svr.wait_until_ready();
  4025. Client cli(HOST, PORT);
  4026. {
  4027. auto res = cli.Get("/exception");
  4028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4029. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4030. EXPECT_EQ("EXCEPTION", res->body);
  4031. }
  4032. {
  4033. auto res = cli.Get("/error");
  4034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4035. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4036. EXPECT_EQ("ERROR", res->body);
  4037. }
  4038. {
  4039. auto res = cli.Get("/invalid");
  4040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4042. EXPECT_EQ("NOT_FOUND", res->body);
  4043. }
  4044. }
  4045. #endif
  4046. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4047. // process_request() wraps only routing() in a try/catch, so an exception from
  4048. // any other user callback used to unwind into the task queue - which does not
  4049. // catch - and terminate the process. Each test below runs the server on a
  4050. // single worker thread: a guard that catches the exception but still loses the
  4051. // thread would otherwise be hidden by a spare worker serving the follow-up
  4052. // request. Note that a regression here aborts the whole test binary rather
  4053. // than failing one test.
  4054. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4055. Server svr;
  4056. svr.new_task_queue = [] { return new ThreadPool(1); };
  4057. std::atomic<int> reported{0};
  4058. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4059. if (err == Error::UserCallbackException) { reported++; }
  4060. });
  4061. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4062. res.set_content_provider(
  4063. 1024, "text/plain",
  4064. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4065. sink.write("hello", 5);
  4066. throw std::runtime_error("from the content provider");
  4067. });
  4068. });
  4069. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4070. res.set_content("ok", "text/plain");
  4071. });
  4072. auto port = svr.bind_to_any_port(HOST);
  4073. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4074. auto se = detail::scope_exit([&] {
  4075. svr.stop();
  4076. listen_thread.join();
  4077. ASSERT_FALSE(svr.is_running());
  4078. });
  4079. svr.wait_until_ready();
  4080. {
  4081. Client cli(HOST, port);
  4082. cli.set_read_timeout(5, 0);
  4083. EXPECT_FALSE(cli.Get("/throw"));
  4084. }
  4085. EXPECT_TRUE(svr.is_running());
  4086. EXPECT_EQ(1, reported.load());
  4087. // A request on a fresh connection is still served.
  4088. {
  4089. Client cli(HOST, port);
  4090. auto res = cli.Get("/ok");
  4091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("ok", res->body);
  4094. }
  4095. }
  4096. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4097. Server svr;
  4098. svr.new_task_queue = [] { return new ThreadPool(1); };
  4099. std::atomic<bool> should_throw{true};
  4100. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4101. res.set_content("hi", "text/plain");
  4102. });
  4103. svr.set_post_routing_handler(
  4104. [&](const Request & /*req*/, Response & /*res*/) {
  4105. if (should_throw) {
  4106. throw std::runtime_error("from the post-routing handler");
  4107. }
  4108. });
  4109. auto port = svr.bind_to_any_port(HOST);
  4110. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. listen_thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. {
  4118. Client cli(HOST, port);
  4119. cli.set_read_timeout(5, 0);
  4120. EXPECT_FALSE(cli.Get("/hi"));
  4121. }
  4122. EXPECT_TRUE(svr.is_running());
  4123. should_throw = false;
  4124. {
  4125. Client cli(HOST, port);
  4126. auto res = cli.Get("/hi");
  4127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4128. EXPECT_EQ(StatusCode::OK_200, res->status);
  4129. EXPECT_EQ("hi", res->body);
  4130. }
  4131. }
  4132. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4133. // The guard reports the caught exception through the error logger, which is
  4134. // a user callback too. A logger that throws has to be contained as well, or
  4135. // the process would terminate from inside the catch.
  4136. Server svr;
  4137. svr.new_task_queue = [] { return new ThreadPool(1); };
  4138. std::atomic<int> reported{0};
  4139. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4140. if (err == Error::UserCallbackException) {
  4141. reported++;
  4142. throw std::runtime_error("from the error logger");
  4143. }
  4144. });
  4145. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4146. res.set_content_provider(
  4147. 1024, "text/plain",
  4148. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4149. sink.write("hello", 5);
  4150. throw std::runtime_error("from the content provider");
  4151. });
  4152. });
  4153. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4154. res.set_content("ok", "text/plain");
  4155. });
  4156. auto port = svr.bind_to_any_port(HOST);
  4157. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4158. auto se = detail::scope_exit([&] {
  4159. svr.stop();
  4160. listen_thread.join();
  4161. ASSERT_FALSE(svr.is_running());
  4162. });
  4163. svr.wait_until_ready();
  4164. {
  4165. Client cli(HOST, port);
  4166. cli.set_read_timeout(5, 0);
  4167. EXPECT_FALSE(cli.Get("/throw"));
  4168. }
  4169. EXPECT_TRUE(svr.is_running());
  4170. EXPECT_EQ(1, reported.load());
  4171. {
  4172. Client cli(HOST, port);
  4173. auto res = cli.Get("/ok");
  4174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4175. EXPECT_EQ(StatusCode::OK_200, res->status);
  4176. EXPECT_EQ("ok", res->body);
  4177. }
  4178. }
  4179. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4180. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4181. // so the exception unwinds through the ws::WebSocket object on its way to
  4182. // the guard. None of the HTTP cases above cross that.
  4183. Server svr;
  4184. svr.new_task_queue = [] { return new ThreadPool(1); };
  4185. std::atomic<int> reported{0};
  4186. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4187. if (err == Error::UserCallbackException) { reported++; }
  4188. });
  4189. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4190. throw std::runtime_error("from the WebSocket handler");
  4191. });
  4192. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4193. res.set_content("ok", "text/plain");
  4194. });
  4195. auto port = svr.bind_to_any_port(HOST);
  4196. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. listen_thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4205. "/ws");
  4206. auto res = client.connect();
  4207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4208. // The server dropped the connection instead of dying.
  4209. std::string msg;
  4210. EXPECT_FALSE(client.read(msg));
  4211. client.close();
  4212. }
  4213. EXPECT_TRUE(svr.is_running());
  4214. EXPECT_EQ(1, reported.load());
  4215. {
  4216. Client cli(HOST, port);
  4217. auto res = cli.Get("/ok");
  4218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. EXPECT_EQ("ok", res->body);
  4221. }
  4222. }
  4223. #ifdef CPPHTTPLIB_SSL_ENABLED
  4224. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4225. // SSLServer::process_and_close_socket() is a separate overload with its own
  4226. // guard, so it is exercised on its own.
  4227. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4228. ASSERT_TRUE(svr.is_valid());
  4229. svr.new_task_queue = [] { return new ThreadPool(1); };
  4230. std::atomic<int> reported{0};
  4231. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4232. if (err == Error::UserCallbackException) { reported++; }
  4233. });
  4234. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4235. res.set_content_provider(
  4236. 1024, "text/plain",
  4237. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4238. sink.write("hello", 5);
  4239. throw std::runtime_error("from the content provider");
  4240. });
  4241. });
  4242. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4243. res.set_content("ok", "text/plain");
  4244. });
  4245. auto port = svr.bind_to_any_port(HOST);
  4246. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4247. auto se = detail::scope_exit([&] {
  4248. svr.stop();
  4249. listen_thread.join();
  4250. ASSERT_FALSE(svr.is_running());
  4251. });
  4252. svr.wait_until_ready();
  4253. {
  4254. SSLClient cli(HOST, port);
  4255. cli.enable_server_certificate_verification(false);
  4256. cli.set_read_timeout(5, 0);
  4257. EXPECT_FALSE(cli.Get("/throw"));
  4258. }
  4259. EXPECT_TRUE(svr.is_running());
  4260. EXPECT_EQ(1, reported.load());
  4261. {
  4262. SSLClient cli(HOST, port);
  4263. cli.enable_server_certificate_verification(false);
  4264. auto res = cli.Get("/ok");
  4265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4266. EXPECT_EQ(StatusCode::OK_200, res->status);
  4267. EXPECT_EQ("ok", res->body);
  4268. }
  4269. }
  4270. #endif
  4271. #endif
  4272. TEST(NoContentTest, ContentLength) {
  4273. Server svr;
  4274. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4275. res.status = StatusCode::NoContent_204;
  4276. });
  4277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4278. auto se = detail::scope_exit([&] {
  4279. svr.stop();
  4280. thread.join();
  4281. ASSERT_FALSE(svr.is_running());
  4282. });
  4283. svr.wait_until_ready();
  4284. {
  4285. Client cli(HOST, PORT);
  4286. auto res = cli.Get("/hi");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4289. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4290. }
  4291. }
  4292. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4293. #ifdef CPPHTTPLIB_SSL_ENABLED
  4294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4295. ASSERT_TRUE(svr.is_valid());
  4296. #else
  4297. Server svr;
  4298. #endif
  4299. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4300. if (req.path == "/routing_handler") {
  4301. res.set_header("PRE_ROUTING", "on");
  4302. res.set_content("Routing Handler", "text/plain");
  4303. return httplib::Server::HandlerResponse::Handled;
  4304. }
  4305. return httplib::Server::HandlerResponse::Unhandled;
  4306. });
  4307. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4308. res.set_content("Error", "text/html");
  4309. });
  4310. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4311. if (req.path == "/routing_handler") {
  4312. res.set_header("POST_ROUTING", "on");
  4313. }
  4314. });
  4315. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4316. res.set_content("Hello World!\n", "text/plain");
  4317. });
  4318. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. {
  4326. #ifdef CPPHTTPLIB_SSL_ENABLED
  4327. SSLClient cli(HOST, PORT);
  4328. cli.enable_server_certificate_verification(false);
  4329. #else
  4330. Client cli(HOST, PORT);
  4331. #endif
  4332. auto res = cli.Get("/routing_handler");
  4333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4334. EXPECT_EQ(StatusCode::OK_200, res->status);
  4335. EXPECT_EQ("Routing Handler", res->body);
  4336. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4337. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4338. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4339. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4340. }
  4341. {
  4342. #ifdef CPPHTTPLIB_SSL_ENABLED
  4343. SSLClient cli(HOST, PORT);
  4344. cli.enable_server_certificate_verification(false);
  4345. #else
  4346. Client cli(HOST, PORT);
  4347. #endif
  4348. auto res = cli.Get("/hi");
  4349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. EXPECT_EQ("Hello World!\n", res->body);
  4352. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4353. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4354. }
  4355. {
  4356. #ifdef CPPHTTPLIB_SSL_ENABLED
  4357. SSLClient cli(HOST, PORT);
  4358. cli.enable_server_certificate_verification(false);
  4359. #else
  4360. Client cli(HOST, PORT);
  4361. #endif
  4362. auto res = cli.Get("/aaa");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4365. EXPECT_EQ("Error", res->body);
  4366. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4367. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4368. }
  4369. }
  4370. TEST(RequestHandlerTest, PreRequestHandler) {
  4371. auto route_path = "/user/:user";
  4372. Server svr;
  4373. svr.Get("/hi", [](const Request &, Response &res) {
  4374. res.set_content("hi", "text/plain");
  4375. });
  4376. svr.Get(route_path, [](const Request &req, Response &res) {
  4377. res.set_content(req.path_params.at("user"), "text/plain");
  4378. });
  4379. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4380. if (req.matched_route == route_path) {
  4381. auto user = req.path_params.at("user");
  4382. if (user != "john") {
  4383. res.status = StatusCode::Forbidden_403;
  4384. res.set_content("error", "text/html");
  4385. return Server::HandlerResponse::Handled;
  4386. }
  4387. }
  4388. return Server::HandlerResponse::Unhandled;
  4389. });
  4390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. thread.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. Client cli(HOST, PORT);
  4398. {
  4399. auto res = cli.Get("/hi");
  4400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. EXPECT_EQ("hi", res->body);
  4403. }
  4404. {
  4405. auto res = cli.Get("/user/john");
  4406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4407. EXPECT_EQ(StatusCode::OK_200, res->status);
  4408. EXPECT_EQ("john", res->body);
  4409. }
  4410. {
  4411. auto res = cli.Get("/user/invalid-user");
  4412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4413. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4414. EXPECT_EQ("error", res->body);
  4415. }
  4416. }
  4417. // The pre-request handler must run before the request body is read, so a
  4418. // rejected request never forces the server to buffer a (potentially large)
  4419. // body. Here the posted body is larger than the payload limit: if the body
  4420. // were read first the server would answer 413, but because the pre-request
  4421. // handler runs first it answers 403 and the body is never read.
  4422. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4423. Server svr;
  4424. svr.set_payload_max_length(8);
  4425. auto handler_ran = false;
  4426. svr.Post("/reject", [&](const Request &req, Response &res) {
  4427. handler_ran = true;
  4428. res.set_content(req.body, "text/plain");
  4429. });
  4430. svr.Post("/accept", [](const Request &req, Response &res) {
  4431. res.set_content(req.body, "text/plain");
  4432. });
  4433. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4434. if (req.matched_route == "/reject") {
  4435. res.status = StatusCode::Forbidden_403;
  4436. res.set_content("denied", "text/plain");
  4437. return Server::HandlerResponse::Handled;
  4438. }
  4439. return Server::HandlerResponse::Unhandled;
  4440. });
  4441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4442. auto se = detail::scope_exit([&] {
  4443. svr.stop();
  4444. thread.join();
  4445. ASSERT_FALSE(svr.is_running());
  4446. });
  4447. svr.wait_until_ready();
  4448. Client cli(HOST, PORT);
  4449. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4450. // rejects with 403 before the body is read, so 413 is never reached.
  4451. {
  4452. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4454. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4455. EXPECT_EQ("denied", res->body);
  4456. EXPECT_FALSE(handler_ran);
  4457. }
  4458. // An approved route still reads the body and enforces the payload limit.
  4459. {
  4460. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4462. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4463. }
  4464. }
  4465. TEST(UserDataTest, BasicOperations) {
  4466. httplib::UserData ud;
  4467. // Initially empty
  4468. EXPECT_FALSE(ud.has("key"));
  4469. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4470. // set and get
  4471. ud.set("key", 42);
  4472. EXPECT_TRUE(ud.has("key"));
  4473. auto *p = ud.get<int>("key");
  4474. ASSERT_NE(nullptr, p);
  4475. EXPECT_EQ(42, *p);
  4476. // Type mismatch → nullptr
  4477. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4478. // Overwrite with different type
  4479. ud.set("key", std::string("hello"));
  4480. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4481. auto *s = ud.get<std::string>("key");
  4482. ASSERT_NE(nullptr, s);
  4483. EXPECT_EQ("hello", *s);
  4484. // erase
  4485. ud.erase("key");
  4486. EXPECT_FALSE(ud.has("key"));
  4487. // clear
  4488. ud.set("a", 1);
  4489. ud.set("b", 2);
  4490. ud.clear();
  4491. EXPECT_FALSE(ud.has("a"));
  4492. EXPECT_FALSE(ud.has("b"));
  4493. }
  4494. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4495. struct AuthCtx {
  4496. std::string user_id;
  4497. };
  4498. Server svr;
  4499. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4500. res.user_data.set("auth", AuthCtx{"alice"});
  4501. return Server::HandlerResponse::Unhandled;
  4502. });
  4503. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4504. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4505. ASSERT_NE(nullptr, ctx);
  4506. res.set_content("Hello " + ctx->user_id, "text/plain");
  4507. });
  4508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4509. auto se = detail::scope_exit([&] {
  4510. svr.stop();
  4511. thread.join();
  4512. ASSERT_FALSE(svr.is_running());
  4513. });
  4514. svr.wait_until_ready();
  4515. Client cli(HOST, PORT);
  4516. auto res = cli.Get("/me");
  4517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("Hello alice", res->body);
  4520. }
  4521. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4522. struct RoleCtx {
  4523. std::string role;
  4524. };
  4525. Server svr;
  4526. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4527. res.user_data.set("role", RoleCtx{"admin"});
  4528. return Server::HandlerResponse::Unhandled;
  4529. });
  4530. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4531. auto *ctx = res.user_data.get<RoleCtx>("role");
  4532. ASSERT_NE(nullptr, ctx);
  4533. res.set_content(ctx->role, "text/plain");
  4534. });
  4535. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. Client cli(HOST, PORT);
  4543. auto res = cli.Get("/role");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::OK_200, res->status);
  4546. EXPECT_EQ("admin", res->body);
  4547. }
  4548. TEST(InvalidFormatTest, StatusCode) {
  4549. Server svr;
  4550. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4551. res.set_content("Hello World!\n", "text/plain");
  4552. res.status = 9999; // Status should be a three-digit code...
  4553. });
  4554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4555. auto se = detail::scope_exit([&] {
  4556. svr.stop();
  4557. thread.join();
  4558. ASSERT_FALSE(svr.is_running());
  4559. });
  4560. svr.wait_until_ready();
  4561. {
  4562. Client cli(HOST, PORT);
  4563. auto res = cli.Get("/hi");
  4564. ASSERT_FALSE(res);
  4565. }
  4566. }
  4567. TEST(URLFragmentTest, WithFragment) {
  4568. Server svr;
  4569. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4570. EXPECT_TRUE(req.target == "/hi");
  4571. });
  4572. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, PORT);
  4581. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4582. EXPECT_TRUE(res);
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. res = cli.Get("/hi%23key1=val1=key2=val2");
  4585. EXPECT_TRUE(res);
  4586. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4587. }
  4588. }
  4589. TEST(HeaderWriter, SetHeaderWriter) {
  4590. Server svr;
  4591. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4592. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4593. return detail::write_headers(strm, hdrs);
  4594. });
  4595. svr.Get("/hi", [](const Request &req, Response &res) {
  4596. auto it = req.headers.find("CustomClientHeader");
  4597. EXPECT_TRUE(it != req.headers.end());
  4598. EXPECT_EQ(it->second, "CustomClientValue");
  4599. res.set_content("Hello World!\n", "text/plain");
  4600. });
  4601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. thread.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. {
  4609. Client cli(HOST, PORT);
  4610. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4611. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4612. return detail::write_headers(strm, hdrs);
  4613. });
  4614. auto res = cli.Get("/hi");
  4615. EXPECT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. auto it = res->headers.find("CustomServerHeader");
  4618. EXPECT_TRUE(it != res->headers.end());
  4619. EXPECT_EQ(it->second, "CustomServerValue");
  4620. }
  4621. }
  4622. class ServerTest : public ::testing::Test {
  4623. protected:
  4624. ServerTest()
  4625. : cli_(HOST, PORT)
  4626. #ifdef CPPHTTPLIB_SSL_ENABLED
  4627. ,
  4628. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4629. #endif
  4630. {
  4631. #ifdef CPPHTTPLIB_SSL_ENABLED
  4632. cli_.enable_server_certificate_verification(false);
  4633. #endif
  4634. // Allow LARGE_DATA (100MB) responses
  4635. cli_.set_payload_max_length(200 * 1024 * 1024);
  4636. }
  4637. virtual void SetUp() {
  4638. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4639. svr_.set_payload_max_length(200 * 1024 * 1024);
  4640. svr_.set_mount_point("/", "./www");
  4641. svr_.set_mount_point("/mount", "./www2");
  4642. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4643. svr_.Get("/hi",
  4644. [&](const Request & /*req*/, Response &res) {
  4645. res.set_content("Hello World!", "text/plain");
  4646. })
  4647. .Get("/file_content",
  4648. [&](const Request & /*req*/, Response &res) {
  4649. res.set_file_content("./www/dir/test.html");
  4650. })
  4651. .Get("/file_content_with_content_type",
  4652. [&](const Request & /*req*/, Response &res) {
  4653. res.set_file_content("./www/file", "text/plain");
  4654. })
  4655. .Get("/invalid_file_content",
  4656. [&](const Request & /*req*/, Response &res) {
  4657. res.set_file_content("./www/dir/invalid_file_path");
  4658. })
  4659. .Get("/http_response_splitting",
  4660. [&](const Request & /*req*/, Response &res) {
  4661. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4662. EXPECT_EQ(0U, res.headers.size());
  4663. EXPECT_FALSE(res.has_header("a"));
  4664. res.set_header("a", "1\nSet-Cookie: a=1");
  4665. EXPECT_EQ(0U, res.headers.size());
  4666. EXPECT_FALSE(res.has_header("a"));
  4667. res.set_header("a", "1\rSet-Cookie: a=1");
  4668. EXPECT_EQ(0U, res.headers.size());
  4669. EXPECT_FALSE(res.has_header("a"));
  4670. res.set_header("a\r\nb", "0");
  4671. EXPECT_EQ(0U, res.headers.size());
  4672. EXPECT_FALSE(res.has_header("a"));
  4673. res.set_header("a\rb", "0");
  4674. EXPECT_EQ(0U, res.headers.size());
  4675. EXPECT_FALSE(res.has_header("a"));
  4676. res.set_header("a\nb", "0");
  4677. EXPECT_EQ(0U, res.headers.size());
  4678. EXPECT_FALSE(res.has_header("a"));
  4679. res.set_redirect("1\r\nSet-Cookie: a=1");
  4680. EXPECT_EQ(0U, res.headers.size());
  4681. EXPECT_FALSE(res.has_header("Location"));
  4682. })
  4683. .Get("/slow",
  4684. [&](const Request & /*req*/, Response &res) {
  4685. std::this_thread::sleep_for(std::chrono::seconds(4));
  4686. res.set_content("slow", "text/plain");
  4687. })
  4688. #if 0
  4689. .Post("/slowpost",
  4690. [&](const Request & /*req*/, Response &res) {
  4691. std::this_thread::sleep_for(std::chrono::seconds(2));
  4692. res.set_content("slow", "text/plain");
  4693. })
  4694. #endif
  4695. .Get("/remote_addr",
  4696. [&](const Request &req, Response &res) {
  4697. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4698. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4699. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4700. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4701. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4702. #endif
  4703. res.set_content(req.remote_addr, "text/plain");
  4704. })
  4705. .Get("/local_addr",
  4706. [&](const Request &req, Response &res) {
  4707. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4708. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4709. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4710. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4711. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4712. #endif
  4713. auto local_addr = req.local_addr;
  4714. auto local_port = std::to_string(req.local_port);
  4715. res.set_content(local_addr.append(":").append(local_port),
  4716. "text/plain");
  4717. })
  4718. .Get("/endwith%",
  4719. [&](const Request & /*req*/, Response &res) {
  4720. res.set_content("Hello World!", "text/plain");
  4721. })
  4722. .Get("/a\\+\\+b",
  4723. [&](const Request &req, Response &res) {
  4724. ASSERT_TRUE(req.has_param("a +b"));
  4725. auto val = req.get_param_value("a +b");
  4726. res.set_content(val, "text/plain");
  4727. })
  4728. .Get("/", [&](const Request & /*req*/,
  4729. Response &res) { res.set_redirect("/hi"); })
  4730. .Post("/1",
  4731. [](const Request & /*req*/, Response &res) {
  4732. res.set_redirect("/2", StatusCode::SeeOther_303);
  4733. })
  4734. .Get("/2",
  4735. [](const Request & /*req*/, Response &res) {
  4736. res.set_content("redirected.", "text/plain");
  4737. res.status = StatusCode::OK_200;
  4738. })
  4739. .Post("/person",
  4740. [&](const Request &req, Response &res) {
  4741. if (req.has_param("name") && req.has_param("note")) {
  4742. persons_[req.get_param_value("name")] =
  4743. req.get_param_value("note");
  4744. } else {
  4745. res.status = StatusCode::BadRequest_400;
  4746. }
  4747. })
  4748. .Put("/person",
  4749. [&](const Request &req, Response &res) {
  4750. if (req.has_param("name") && req.has_param("note")) {
  4751. persons_[req.get_param_value("name")] =
  4752. req.get_param_value("note");
  4753. } else {
  4754. res.status = StatusCode::BadRequest_400;
  4755. }
  4756. })
  4757. .Get("/person/(.*)",
  4758. [&](const Request &req, Response &res) {
  4759. string name = req.matches[1];
  4760. if (persons_.find(name) != persons_.end()) {
  4761. auto note = persons_[name];
  4762. res.set_content(note, "text/plain");
  4763. } else {
  4764. res.status = StatusCode::NotFound_404;
  4765. }
  4766. })
  4767. .Delete("/person",
  4768. [&](const Request &req, Response &res) {
  4769. if (req.has_param("name")) {
  4770. string name = req.get_param_value("name");
  4771. if (persons_.find(name) != persons_.end()) {
  4772. persons_.erase(name);
  4773. res.set_content("DELETED", "text/plain");
  4774. } else {
  4775. res.status = StatusCode::NotFound_404;
  4776. }
  4777. } else {
  4778. res.status = StatusCode::BadRequest_400;
  4779. }
  4780. })
  4781. .Post("/x-www-form-urlencoded-json",
  4782. [&](const Request &req, Response &res) {
  4783. auto json = req.get_param_value("json");
  4784. ASSERT_EQ(JSON_DATA, json);
  4785. res.set_content(json, "appliation/json");
  4786. res.status = StatusCode::OK_200;
  4787. })
  4788. .Get("/streamed-chunked",
  4789. [&](const Request & /*req*/, Response &res) {
  4790. res.set_chunked_content_provider(
  4791. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4792. sink.os << "123";
  4793. sink.os << "456";
  4794. sink.os << "789";
  4795. sink.done();
  4796. return true;
  4797. });
  4798. })
  4799. .Get("/streamed-chunked-with-prohibited-trailer",
  4800. [&](const Request & /*req*/, Response &res) {
  4801. auto i = new int(0);
  4802. // Declare both a prohibited trailer (Content-Length) and an
  4803. // allowed one
  4804. res.set_header("Trailer", "Content-Length, X-Allowed");
  4805. res.set_chunked_content_provider(
  4806. "text/plain",
  4807. [i](size_t /*offset*/, DataSink &sink) {
  4808. switch (*i) {
  4809. case 0: sink.os << "123"; break;
  4810. case 1: sink.os << "456"; break;
  4811. case 2: sink.os << "789"; break;
  4812. case 3: {
  4813. sink.done_with_trailer(
  4814. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4815. } break;
  4816. }
  4817. (*i)++;
  4818. return true;
  4819. },
  4820. [i](bool success) {
  4821. EXPECT_TRUE(success);
  4822. delete i;
  4823. });
  4824. })
  4825. .Get("/streamed-chunked2",
  4826. [&](const Request & /*req*/, Response &res) {
  4827. auto i = new int(0);
  4828. res.set_chunked_content_provider(
  4829. "text/plain",
  4830. [i](size_t /*offset*/, DataSink &sink) {
  4831. switch (*i) {
  4832. case 0: sink.os << "123"; break;
  4833. case 1: sink.os << "456"; break;
  4834. case 2: sink.os << "789"; break;
  4835. case 3: sink.done(); break;
  4836. }
  4837. (*i)++;
  4838. return true;
  4839. },
  4840. [i](bool success) {
  4841. EXPECT_TRUE(success);
  4842. delete i;
  4843. });
  4844. })
  4845. .Get("/streamed-chunked-with-trailer",
  4846. [&](const Request & /*req*/, Response &res) {
  4847. auto i = new int(0);
  4848. res.set_header("Trailer", "Dummy1, Dummy2");
  4849. res.set_chunked_content_provider(
  4850. "text/plain",
  4851. [i](size_t /*offset*/, DataSink &sink) {
  4852. switch (*i) {
  4853. case 0: sink.os << "123"; break;
  4854. case 1: sink.os << "456"; break;
  4855. case 2: sink.os << "789"; break;
  4856. case 3: {
  4857. sink.done_with_trailer(
  4858. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4859. } break;
  4860. }
  4861. (*i)++;
  4862. return true;
  4863. },
  4864. [i](bool success) {
  4865. EXPECT_TRUE(success);
  4866. delete i;
  4867. });
  4868. })
  4869. .Get("/streamed",
  4870. [&](const Request & /*req*/, Response &res) {
  4871. res.set_content_provider(
  4872. 6, "text/plain",
  4873. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4874. sink.os << (offset < 3 ? "a" : "b");
  4875. return true;
  4876. });
  4877. })
  4878. .Get("/streamed-without-length",
  4879. [&](const Request & /*req*/, Response &res) {
  4880. auto data = new std::string("abcdefg");
  4881. res.set_content_provider(
  4882. "text/plain",
  4883. [data](size_t offset, DataSink &sink) {
  4884. if (offset < data->size()) {
  4885. sink.os << data->substr(offset);
  4886. }
  4887. sink.done();
  4888. return true;
  4889. },
  4890. [data](bool success) {
  4891. EXPECT_TRUE(success);
  4892. delete data;
  4893. });
  4894. })
  4895. .Get("/streamed-with-range",
  4896. [&](const Request &req, Response &res) {
  4897. auto data = new std::string("abcdefg");
  4898. // An explicit status keeps the server from picking the 206 it
  4899. // would otherwise choose for a ranged request, so the response
  4900. // is not a partial representation.
  4901. auto status = req.get_param_value("status");
  4902. if (status == "200") {
  4903. res.status = StatusCode::OK_200;
  4904. } else if (status == "403") {
  4905. res.status = StatusCode::Forbidden_403;
  4906. }
  4907. res.set_content_provider(
  4908. data->size(), "text/plain",
  4909. [data](size_t offset, size_t length, DataSink &sink) {
  4910. size_t DATA_CHUNK_SIZE = 4;
  4911. const auto &d = *data;
  4912. auto out_len =
  4913. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4914. auto ret =
  4915. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4916. EXPECT_TRUE(ret);
  4917. return true;
  4918. },
  4919. [data, &req](bool success) {
  4920. EXPECT_EQ(success, !req.has_param("error"));
  4921. delete data;
  4922. });
  4923. })
  4924. .Get("/streamed-cancel",
  4925. [&](const Request & /*req*/, Response &res) {
  4926. res.set_content_provider(
  4927. size_t(-1), "text/plain",
  4928. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4929. sink.os << "data_chunk";
  4930. return true;
  4931. });
  4932. })
  4933. .Get("/regex-with-delimiter",
  4934. [&](const Request &req, Response & /*res*/) {
  4935. ASSERT_TRUE(req.has_param("key"));
  4936. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4937. })
  4938. .Get("/with-range",
  4939. [&](const Request & /*req*/, Response &res) {
  4940. res.set_content("abcdefg", "text/plain");
  4941. })
  4942. .Get("/test-start-time",
  4943. [&](const Request &req, Response & /*res*/) {
  4944. EXPECT_NE(req.start_time_,
  4945. std::chrono::steady_clock::time_point::min());
  4946. })
  4947. .Get("/with-range-customized-response",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. res.status = StatusCode::BadRequest_400;
  4950. res.set_content(JSON_DATA, "application/json");
  4951. })
  4952. .Post("/chunked",
  4953. [&](const Request &req, Response & /*res*/) {
  4954. EXPECT_EQ(req.body, "dechunked post body");
  4955. })
  4956. .Post("/large-chunked",
  4957. [&](const Request &req, Response & /*res*/) {
  4958. std::string expected(6 * 30 * 1024u, 'a');
  4959. EXPECT_EQ(req.body, expected);
  4960. })
  4961. .Post("/multipart",
  4962. [&](const Request &req, Response & /*res*/) {
  4963. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4964. req.form.get_field_count("text2") +
  4965. req.form.get_field_count("file3") +
  4966. req.form.get_field_count("file4"));
  4967. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4968. req.form.get_file_count("file2"));
  4969. ASSERT_TRUE(!req.form.has_file("???"));
  4970. ASSERT_TRUE(!req.form.has_field("???"));
  4971. ASSERT_TRUE(req.body.empty());
  4972. {
  4973. const auto &text = req.form.get_field("text1");
  4974. EXPECT_EQ("text default", text);
  4975. }
  4976. {
  4977. const auto &text = req.form.get_field("text2");
  4978. EXPECT_EQ("aωb", text);
  4979. }
  4980. {
  4981. const auto &file = req.form.get_file("file1");
  4982. EXPECT_EQ("hello.txt", file.filename);
  4983. EXPECT_EQ("text/plain", file.content_type);
  4984. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4985. }
  4986. {
  4987. const auto &file = req.form.get_file("file2");
  4988. EXPECT_EQ("world.json", file.filename);
  4989. EXPECT_EQ("application/json", file.content_type);
  4990. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4991. }
  4992. {
  4993. const auto &text = req.form.get_field("file3");
  4994. EXPECT_EQ(0u, text.size());
  4995. }
  4996. {
  4997. const auto &text = req.form.get_field("file4");
  4998. EXPECT_EQ(0u, text.size());
  4999. }
  5000. })
  5001. .Post("/multipart/multi_file_values",
  5002. [&](const Request &req, Response & /*res*/) {
  5003. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5004. req.form.get_field_count("multi_text1"));
  5005. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5006. ASSERT_TRUE(!req.form.has_file("???"));
  5007. ASSERT_TRUE(!req.form.has_field("???"));
  5008. ASSERT_TRUE(req.body.empty());
  5009. {
  5010. const auto &text = req.form.get_field("text");
  5011. EXPECT_EQ("default text", text);
  5012. }
  5013. {
  5014. const auto &text1_values = req.form.get_fields("multi_text1");
  5015. EXPECT_EQ(2u, text1_values.size());
  5016. EXPECT_EQ("aaaaa", text1_values[0]);
  5017. EXPECT_EQ("bbbbb", text1_values[1]);
  5018. }
  5019. {
  5020. const auto &file1_values = req.form.get_files("multi_file1");
  5021. EXPECT_EQ(2u, file1_values.size());
  5022. auto file1 = file1_values[0];
  5023. EXPECT_EQ(file1.filename, "hello.txt");
  5024. EXPECT_EQ(file1.content_type, "text/plain");
  5025. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5026. auto file2 = file1_values[1];
  5027. EXPECT_EQ(file2.filename, "world.json");
  5028. EXPECT_EQ(file2.content_type, "application/json");
  5029. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5030. }
  5031. })
  5032. .Post("/empty",
  5033. [&](const Request &req, Response &res) {
  5034. EXPECT_EQ(req.body, "");
  5035. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5036. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5037. res.set_content("empty", "text/plain");
  5038. })
  5039. .Post("/empty-no-content-type",
  5040. [&](const Request &req, Response &res) {
  5041. EXPECT_EQ(req.body, "");
  5042. EXPECT_FALSE(req.has_header("Content-Type"));
  5043. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5044. res.set_content("empty-no-content-type", "text/plain");
  5045. })
  5046. .Post("/path-only",
  5047. [&](const Request &req, Response &res) {
  5048. EXPECT_EQ(req.body, "");
  5049. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5050. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5051. res.set_content("path-only", "text/plain");
  5052. })
  5053. .Post("/path-headers-only",
  5054. [&](const Request &req, Response &res) {
  5055. EXPECT_EQ(req.body, "");
  5056. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5057. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5058. EXPECT_EQ("world", req.get_header_value("hello"));
  5059. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5060. res.set_content("path-headers-only", "text/plain");
  5061. })
  5062. .Post("/post-large",
  5063. [&](const Request &req, Response &res) {
  5064. EXPECT_EQ(req.body, LARGE_DATA);
  5065. res.set_content(req.body, "text/plain");
  5066. })
  5067. .Post("/post-loopback",
  5068. [&](const Request &, Response &res,
  5069. ContentReader const &content_reader) {
  5070. std::string body;
  5071. content_reader([&](const char *data, size_t data_length) {
  5072. body.append(data, data_length);
  5073. return true;
  5074. });
  5075. res.set_content(body, "text/plain");
  5076. })
  5077. .Put("/put-loopback",
  5078. [&](const Request &, Response &res,
  5079. ContentReader const &content_reader) {
  5080. std::string body;
  5081. content_reader([&](const char *data, size_t data_length) {
  5082. body.append(data, data_length);
  5083. return true;
  5084. });
  5085. res.set_content(body, "text/plain");
  5086. })
  5087. .Patch("/patch-loopback",
  5088. [&](const Request &, Response &res,
  5089. ContentReader const &content_reader) {
  5090. std::string body;
  5091. content_reader([&](const char *data, size_t data_length) {
  5092. body.append(data, data_length);
  5093. return true;
  5094. });
  5095. res.set_content(body, "text/plain");
  5096. })
  5097. .Put("/empty-no-content-type",
  5098. [&](const Request &req, Response &res) {
  5099. EXPECT_EQ(req.body, "");
  5100. EXPECT_FALSE(req.has_header("Content-Type"));
  5101. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5102. res.set_content("empty-no-content-type", "text/plain");
  5103. })
  5104. .Put("/put",
  5105. [&](const Request &req, Response &res) {
  5106. EXPECT_EQ(req.body, "PUT");
  5107. res.set_content(req.body, "text/plain");
  5108. })
  5109. .Put("/put-large",
  5110. [&](const Request &req, Response &res) {
  5111. EXPECT_EQ(req.body, LARGE_DATA);
  5112. res.set_content(req.body, "text/plain");
  5113. })
  5114. .Patch("/patch",
  5115. [&](const Request &req, Response &res) {
  5116. EXPECT_EQ(req.body, "PATCH");
  5117. res.set_content(req.body, "text/plain");
  5118. })
  5119. .Delete("/delete",
  5120. [&](const Request & /*req*/, Response &res) {
  5121. res.set_content("DELETE", "text/plain");
  5122. })
  5123. .Delete("/delete-body",
  5124. [&](const Request &req, Response &res) {
  5125. EXPECT_EQ(req.body, "content");
  5126. res.set_content(req.body, "text/plain");
  5127. })
  5128. .Options(R"(\*)",
  5129. [&](const Request & /*req*/, Response &res) {
  5130. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5131. })
  5132. .CustomRoute("PROPFIND", "/dav/:id",
  5133. [&](const Request &req, Response &res) {
  5134. res.set_header("x-body-size",
  5135. std::to_string(req.body.size()));
  5136. res.set_header("x-matched-route", req.matched_route);
  5137. res.set_header("x-dav-id", req.path_params.at("id"));
  5138. res.status = StatusCode::MultiStatus_207;
  5139. res.set_content(req.body, "application/xml");
  5140. })
  5141. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5142. [&](const Request &req, Response &res) {
  5143. res.set_header("x-dav-match", req.matches[1]);
  5144. res.status = StatusCode::MultiStatus_207;
  5145. })
  5146. .CustomRoute("MKCOL", "/dav-mkcol",
  5147. [&](const Request &req, Response &res) {
  5148. EXPECT_TRUE(req.body.empty());
  5149. res.status = StatusCode::Created_201;
  5150. })
  5151. .CustomRoute(
  5152. "REPORT", "/dav-report",
  5153. [&](const Request & /*req*/, Response &res,
  5154. const ContentReader &content_reader) {
  5155. std::string body;
  5156. content_reader([&](const char *data, size_t data_length) {
  5157. body.append(data, data_length);
  5158. return true;
  5159. });
  5160. res.set_header("x-body-size", std::to_string(body.size()));
  5161. res.status = StatusCode::MultiStatus_207;
  5162. res.set_content(body, "application/xml");
  5163. })
  5164. .Get("/request-target",
  5165. [&](const Request &req, Response & /*res*/) {
  5166. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5167. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5168. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5169. })
  5170. .Get("/long-query-value",
  5171. [&](const Request &req, Response & /*res*/) {
  5172. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5173. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5174. })
  5175. .Get("/too-long-query-value",
  5176. [&](const Request &req, Response & /*res*/) {
  5177. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5178. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5179. })
  5180. .Get("/array-param",
  5181. [&](const Request &req, Response & /*res*/) {
  5182. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5183. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5184. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5185. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5186. })
  5187. .Get("/array-param-values",
  5188. [&](const Request &req, Response & /*res*/) {
  5189. auto values = req.get_param_values("array");
  5190. EXPECT_EQ(3u, values.size());
  5191. EXPECT_EQ("value1", values[0]);
  5192. EXPECT_EQ("value2", values[1]);
  5193. EXPECT_EQ("value3", values[2]);
  5194. auto empty = req.get_param_values("nonexistent");
  5195. EXPECT_TRUE(empty.empty());
  5196. })
  5197. .Post("/validate-no-multiple-headers",
  5198. [&](const Request &req, Response & /*res*/) {
  5199. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5200. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5201. })
  5202. .Post("/content_receiver",
  5203. [&](const Request &req, Response &res,
  5204. const ContentReader &content_reader) {
  5205. if (req.is_multipart_form_data()) {
  5206. std::vector<FormData> items;
  5207. content_reader(
  5208. [&](const FormData &file) {
  5209. items.push_back(file);
  5210. return true;
  5211. },
  5212. [&](const char *data, size_t data_length) {
  5213. items.back().content.append(data, data_length);
  5214. return true;
  5215. });
  5216. EXPECT_EQ(5u, items.size());
  5217. {
  5218. const auto &file = get_file_value(items, "text1");
  5219. EXPECT_TRUE(file.filename.empty());
  5220. EXPECT_EQ("text default", file.content);
  5221. }
  5222. {
  5223. const auto &file = get_file_value(items, "text2");
  5224. EXPECT_TRUE(file.filename.empty());
  5225. EXPECT_EQ("aωb", file.content);
  5226. }
  5227. {
  5228. const auto &file = get_file_value(items, "file1");
  5229. EXPECT_EQ("hello.txt", file.filename);
  5230. EXPECT_EQ("text/plain", file.content_type);
  5231. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5232. }
  5233. {
  5234. const auto &file = get_file_value(items, "file2");
  5235. EXPECT_EQ("world.json", file.filename);
  5236. EXPECT_EQ("application/json", file.content_type);
  5237. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5238. }
  5239. {
  5240. const auto &file = get_file_value(items, "file3");
  5241. EXPECT_TRUE(file.filename.empty());
  5242. EXPECT_EQ("application/octet-stream", file.content_type);
  5243. EXPECT_EQ(0u, file.content.size());
  5244. }
  5245. } else {
  5246. std::string body;
  5247. content_reader([&](const char *data, size_t data_length) {
  5248. EXPECT_EQ(7U, data_length);
  5249. body.append(data, data_length);
  5250. return true;
  5251. });
  5252. EXPECT_EQ(body, "content");
  5253. res.set_content(body, "text/plain");
  5254. }
  5255. })
  5256. .Put("/content_receiver",
  5257. [&](const Request & /*req*/, Response &res,
  5258. const ContentReader &content_reader) {
  5259. std::string body;
  5260. content_reader([&](const char *data, size_t data_length) {
  5261. body.append(data, data_length);
  5262. return true;
  5263. });
  5264. EXPECT_EQ(body, "content");
  5265. res.set_content(body, "text/plain");
  5266. })
  5267. .Patch("/content_receiver",
  5268. [&](const Request & /*req*/, Response &res,
  5269. const ContentReader &content_reader) {
  5270. std::string body;
  5271. content_reader([&](const char *data, size_t data_length) {
  5272. body.append(data, data_length);
  5273. return true;
  5274. });
  5275. EXPECT_EQ(body, "content");
  5276. res.set_content(body, "text/plain");
  5277. })
  5278. .Post("/query-string-and-body",
  5279. [&](const Request &req, Response & /*res*/) {
  5280. ASSERT_TRUE(req.has_param("key"));
  5281. EXPECT_EQ(req.get_param_value("key"), "value");
  5282. EXPECT_EQ(req.body, "content");
  5283. })
  5284. .Get("/last-request",
  5285. [&](const Request &req, Response & /*res*/) {
  5286. EXPECT_EQ("close", req.get_header_value("Connection"));
  5287. })
  5288. .Get(R"(/redirect/(\d+))",
  5289. [&](const Request &req, Response &res) {
  5290. auto num = std::stoi(req.matches[1]) + 1;
  5291. std::string url = "/redirect/" + std::to_string(num);
  5292. res.set_redirect(url);
  5293. })
  5294. .Post("/binary",
  5295. [&](const Request &req, Response &res) {
  5296. EXPECT_EQ(4U, req.body.size());
  5297. EXPECT_EQ("application/octet-stream",
  5298. req.get_header_value("Content-Type"));
  5299. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5300. res.set_content(req.body, "application/octet-stream");
  5301. })
  5302. .Put("/binary",
  5303. [&](const Request &req, Response &res) {
  5304. EXPECT_EQ(4U, req.body.size());
  5305. EXPECT_EQ("application/octet-stream",
  5306. req.get_header_value("Content-Type"));
  5307. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5308. res.set_content(req.body, "application/octet-stream");
  5309. })
  5310. .Patch("/binary",
  5311. [&](const Request &req, Response &res) {
  5312. EXPECT_EQ(4U, req.body.size());
  5313. EXPECT_EQ("application/octet-stream",
  5314. req.get_header_value("Content-Type"));
  5315. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5316. res.set_content(req.body, "application/octet-stream");
  5317. })
  5318. .Delete("/binary",
  5319. [&](const Request &req, Response &res) {
  5320. EXPECT_EQ(4U, req.body.size());
  5321. EXPECT_EQ("application/octet-stream",
  5322. req.get_header_value("Content-Type"));
  5323. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5324. res.set_content(req.body, "application/octet-stream");
  5325. })
  5326. .Get("/issue1772",
  5327. [&](const Request & /*req*/, Response &res) {
  5328. res.status = 401;
  5329. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5330. })
  5331. .Delete("/issue609",
  5332. [](const httplib::Request &, httplib::Response &res,
  5333. const httplib::ContentReader &) {
  5334. res.set_content("ok", "text/plain");
  5335. })
  5336. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5337. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5338. .Get("/compress",
  5339. [&](const Request & /*req*/, Response &res) {
  5340. res.set_content(
  5341. "12345678901234567890123456789012345678901234567890123456789"
  5342. "01234567890123456789012345678901234567890",
  5343. "text/plain");
  5344. })
  5345. .Get("/compress-with-charset",
  5346. [&](const Request & /*req*/, Response &res) {
  5347. res.set_content(
  5348. "12345678901234567890123456789012345678901234567890123456789"
  5349. "01234567890123456789012345678901234567890",
  5350. "application/json; charset=utf-8");
  5351. })
  5352. .Get("/nocompress",
  5353. [&](const Request & /*req*/, Response &res) {
  5354. res.set_content(
  5355. "12345678901234567890123456789012345678901234567890123456789"
  5356. "01234567890123456789012345678901234567890",
  5357. "application/octet-stream");
  5358. })
  5359. .Post("/compress-multipart",
  5360. [&](const Request &req, Response & /*res*/) {
  5361. EXPECT_EQ(2u, req.form.fields.size());
  5362. ASSERT_TRUE(!req.form.has_field("???"));
  5363. {
  5364. const auto &text = req.form.get_field("key1");
  5365. EXPECT_EQ("test", text);
  5366. }
  5367. {
  5368. const auto &text = req.form.get_field("key2");
  5369. EXPECT_EQ("--abcdefg123", text);
  5370. }
  5371. })
  5372. #endif
  5373. ;
  5374. persons_["john"] = "programmer";
  5375. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5376. svr_.wait_until_ready();
  5377. }
  5378. virtual void TearDown() {
  5379. svr_.stop();
  5380. if (!request_threads_.empty()) {
  5381. std::this_thread::sleep_for(std::chrono::seconds(1));
  5382. for (auto &t : request_threads_) {
  5383. t.join();
  5384. }
  5385. }
  5386. t_.join();
  5387. }
  5388. map<string, string> persons_;
  5389. #ifdef CPPHTTPLIB_SSL_ENABLED
  5390. SSLClient cli_;
  5391. SSLServer svr_;
  5392. #else
  5393. Client cli_;
  5394. Server svr_;
  5395. #endif
  5396. thread t_;
  5397. std::vector<thread> request_threads_;
  5398. };
  5399. TEST_F(ServerTest, GetMethod200) {
  5400. auto res = cli_.Get("/hi");
  5401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5402. EXPECT_EQ("HTTP/1.1", res->version);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("OK", res->reason);
  5405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5407. EXPECT_EQ("Hello World!", res->body);
  5408. }
  5409. TEST_F(ServerTest, GetEmptyFile) {
  5410. auto res = cli_.Get("/empty_file");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5414. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5415. EXPECT_EQ("", res->body);
  5416. }
  5417. TEST_F(ServerTest, GetFileContent) {
  5418. auto res = cli_.Get("/file_content");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5423. EXPECT_EQ("test.html", res->body);
  5424. }
  5425. TEST_F(ServerTest, GetFileContentWithRange) {
  5426. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5429. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5431. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5432. EXPECT_EQ("est", res->body);
  5433. }
  5434. TEST_F(ServerTest, GetFileContentWithContentType) {
  5435. auto res = cli_.Get("/file_content_with_content_type");
  5436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5437. EXPECT_EQ(StatusCode::OK_200, res->status);
  5438. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5439. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5440. EXPECT_EQ("file\n", res->body);
  5441. }
  5442. TEST_F(ServerTest, GetInvalidFileContent) {
  5443. auto res = cli_.Get("/invalid_file_content");
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5446. }
  5447. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5448. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. EXPECT_EQ("HTTP/1.1", res->version);
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5453. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5454. EXPECT_EQ("Hello World!", res->body);
  5455. }
  5456. TEST_F(ServerTest, GetMethod302) {
  5457. auto res = cli_.Get("/");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::Found_302, res->status);
  5460. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5461. }
  5462. TEST_F(ServerTest, GetMethod302Redirect) {
  5463. cli_.set_follow_location(true);
  5464. auto res = cli_.Get("/");
  5465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. EXPECT_EQ("Hello World!", res->body);
  5468. EXPECT_EQ("/hi", res->location);
  5469. }
  5470. TEST_F(ServerTest, GetMethod404) {
  5471. auto res = cli_.Get("/invalid");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, HeadMethod200) {
  5476. auto res = cli_.Head("/hi");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::OK_200, res->status);
  5479. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5480. EXPECT_TRUE(res->body.empty());
  5481. }
  5482. TEST_F(ServerTest, HeadMethod200Static) {
  5483. auto res = cli_.Head("/mount/dir/index.html");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5487. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5488. EXPECT_TRUE(res->body.empty());
  5489. }
  5490. TEST_F(ServerTest, HeadMethod404) {
  5491. auto res = cli_.Head("/invalid");
  5492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5494. EXPECT_TRUE(res->body.empty());
  5495. }
  5496. TEST_F(ServerTest, GetMethodPersonJohn) {
  5497. auto res = cli_.Get("/person/john");
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. EXPECT_EQ(StatusCode::OK_200, res->status);
  5500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5501. EXPECT_EQ("programmer", res->body);
  5502. }
  5503. TEST_F(ServerTest, PostMethod1) {
  5504. auto res = cli_.Get("/person/john1");
  5505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5506. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5507. res = cli_.Post("/person", "name=john1&note=coder",
  5508. "application/x-www-form-urlencoded");
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. ASSERT_EQ(StatusCode::OK_200, res->status);
  5511. res = cli_.Get("/person/john1");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. ASSERT_EQ(StatusCode::OK_200, res->status);
  5514. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. ASSERT_EQ("coder", res->body);
  5516. }
  5517. TEST_F(ServerTest, PostMethod2) {
  5518. auto res = cli_.Get("/person/john2");
  5519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5520. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5521. Params params;
  5522. params.emplace("name", "john2");
  5523. params.emplace("note", "coder");
  5524. res = cli_.Post("/person", params);
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. ASSERT_EQ(StatusCode::OK_200, res->status);
  5527. res = cli_.Get("/person/john2");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. ASSERT_EQ(StatusCode::OK_200, res->status);
  5530. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5531. ASSERT_EQ("coder", res->body);
  5532. }
  5533. TEST_F(ServerTest, PutMethod3) {
  5534. auto res = cli_.Get("/person/john3");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5537. Params params;
  5538. params.emplace("name", "john3");
  5539. params.emplace("note", "coder");
  5540. res = cli_.Put("/person", params);
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. ASSERT_EQ(StatusCode::OK_200, res->status);
  5543. res = cli_.Get("/person/john3");
  5544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5545. ASSERT_EQ(StatusCode::OK_200, res->status);
  5546. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5547. ASSERT_EQ("coder", res->body);
  5548. }
  5549. TEST_F(ServerTest, DeleteMethod1) {
  5550. auto res = cli_.Get("/person/john4");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5553. Params params;
  5554. params.emplace("name", "john4");
  5555. params.emplace("note", "coder");
  5556. res = cli_.Post("/person", params);
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. ASSERT_EQ(StatusCode::OK_200, res->status);
  5559. res = cli_.Get("/person/john4");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. ASSERT_EQ(StatusCode::OK_200, res->status);
  5562. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5563. ASSERT_EQ("coder", res->body);
  5564. Params delete_params;
  5565. delete_params.emplace("name", "john4");
  5566. res = cli_.Delete("/person", delete_params);
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. ASSERT_EQ(StatusCode::OK_200, res->status);
  5569. ASSERT_EQ("DELETED", res->body);
  5570. res = cli_.Get("/person/john4");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5573. }
  5574. TEST_F(ServerTest, DeleteMethod2) {
  5575. auto res = cli_.Get("/person/john5");
  5576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5577. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5578. Params params;
  5579. params.emplace("name", "john5");
  5580. params.emplace("note", "developer");
  5581. res = cli_.Post("/person", params);
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. ASSERT_EQ(StatusCode::OK_200, res->status);
  5584. res = cli_.Get("/person/john5");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5588. ASSERT_EQ("developer", res->body);
  5589. Params delete_params;
  5590. delete_params.emplace("name", "john5");
  5591. Headers headers;
  5592. headers.emplace("Custom-Header", "test-value");
  5593. res = cli_.Delete("/person", headers, delete_params);
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. ASSERT_EQ(StatusCode::OK_200, res->status);
  5596. ASSERT_EQ("DELETED", res->body);
  5597. res = cli_.Get("/person/john5");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5600. }
  5601. TEST_F(ServerTest, DeleteMethod3) {
  5602. auto res = cli_.Get("/person/john6");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5605. Params params;
  5606. params.emplace("name", "john6");
  5607. params.emplace("note", "tester");
  5608. res = cli_.Post("/person", params);
  5609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5610. ASSERT_EQ(StatusCode::OK_200, res->status);
  5611. res = cli_.Get("/person/john6");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. ASSERT_EQ(StatusCode::OK_200, res->status);
  5614. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5615. ASSERT_EQ("tester", res->body);
  5616. Params delete_params;
  5617. delete_params.emplace("name", "john6");
  5618. Headers headers;
  5619. headers.emplace("Custom-Header", "test-value");
  5620. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. ASSERT_EQ(StatusCode::OK_200, res->status);
  5623. ASSERT_EQ("DELETED", res->body);
  5624. res = cli_.Get("/person/john6");
  5625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5626. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5627. }
  5628. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5629. Params params;
  5630. params.emplace("json", JSON_DATA);
  5631. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. ASSERT_EQ(JSON_DATA, res->body);
  5635. }
  5636. TEST_F(ServerTest, PostEmptyContent) {
  5637. auto res = cli_.Post("/empty", "", "text/plain");
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. ASSERT_EQ(StatusCode::OK_200, res->status);
  5640. ASSERT_EQ("empty", res->body);
  5641. }
  5642. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5643. auto res = cli_.Post("/empty-no-content-type");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. ASSERT_EQ("empty-no-content-type", res->body);
  5647. }
  5648. TEST_F(ServerTest, PostPathOnly) {
  5649. auto res = cli_.Post("/path-only");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. ASSERT_EQ(StatusCode::OK_200, res->status);
  5652. ASSERT_EQ("path-only", res->body);
  5653. }
  5654. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5655. auto res = cli_.Post("/path-headers-only",
  5656. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. ASSERT_EQ(StatusCode::OK_200, res->status);
  5659. ASSERT_EQ("path-headers-only", res->body);
  5660. }
  5661. TEST_F(ServerTest, PostLarge) {
  5662. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. EXPECT_EQ(LARGE_DATA, res->body);
  5666. }
  5667. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5668. auto res = cli_.Put("/empty-no-content-type");
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. ASSERT_EQ(StatusCode::OK_200, res->status);
  5671. ASSERT_EQ("empty-no-content-type", res->body);
  5672. }
  5673. TEST_F(ServerTest, GetMethodDir) {
  5674. auto res = cli_.Get("/dir/");
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. EXPECT_EQ(StatusCode::OK_200, res->status);
  5677. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5678. auto body = R"(<html>
  5679. <head>
  5680. </head>
  5681. <body>
  5682. <a href="/dir/test.html">Test</a>
  5683. <a href="/hi">hi</a>
  5684. </body>
  5685. </html>
  5686. )";
  5687. EXPECT_EQ(body, res->body);
  5688. }
  5689. TEST_F(ServerTest, GetMethodDirTest) {
  5690. auto res = cli_.Get("/dir/test.html");
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. EXPECT_EQ(StatusCode::OK_200, res->status);
  5693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5694. EXPECT_EQ("test.html", res->body);
  5695. }
  5696. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5697. auto res = cli_.Get("/dir/../dir/test.html");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. EXPECT_EQ(StatusCode::OK_200, res->status);
  5700. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5701. EXPECT_EQ("test.html", res->body);
  5702. }
  5703. TEST_F(ServerTest, GetMethodInvalidPath) {
  5704. auto res = cli_.Get("/dir/../test.html");
  5705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5707. }
  5708. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5709. auto res = cli_.Get("/../www/dir/test.html");
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5712. }
  5713. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5714. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5717. }
  5718. TEST_F(ServerTest, GetMethodDirMountTest) {
  5719. auto res = cli_.Get("/mount/dir/test.html");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5723. EXPECT_EQ("test.html", res->body);
  5724. }
  5725. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5726. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5728. EXPECT_EQ(StatusCode::OK_200, res->status);
  5729. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5730. EXPECT_EQ("test.html", res->body);
  5731. }
  5732. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5733. auto res = cli_.Get("/mount/dir/../test.html");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5736. }
  5737. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5738. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5741. }
  5742. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5743. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5746. }
  5747. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5748. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5751. }
  5752. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5753. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5756. }
  5757. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5758. auto res = cli_.Get("/mount/dir");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5761. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5762. }
  5763. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5764. auto res = cli_.Get("//dir");
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5767. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5768. }
  5769. TEST_F(ServerTest, PostMethod303) {
  5770. auto res = cli_.Post("/1", "body", "text/plain");
  5771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5772. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5773. EXPECT_EQ("/2", res->get_header_value("Location"));
  5774. }
  5775. TEST_F(ServerTest, PostMethod303Redirect) {
  5776. cli_.set_follow_location(true);
  5777. auto res = cli_.Post("/1", "body", "text/plain");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::OK_200, res->status);
  5780. EXPECT_EQ("redirected.", res->body);
  5781. EXPECT_EQ("/2", res->location);
  5782. }
  5783. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5784. auto res = cli_.Get("/dir/test.abcde");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5788. EXPECT_EQ("abcde", res->body);
  5789. }
  5790. TEST_F(ServerTest, StaticFileRange) {
  5791. auto res =
  5792. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5795. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5796. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5797. EXPECT_EQ(true, res->has_header("Content-Range"));
  5798. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5799. EXPECT_EQ(std::string("cd"), res->body);
  5800. }
  5801. TEST_F(ServerTest, StaticFileRanges) {
  5802. auto res = cli_.Get("/dir/test.abcde",
  5803. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5806. EXPECT_TRUE(
  5807. res->get_header_value("Content-Type")
  5808. .find(
  5809. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5810. 0);
  5811. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5812. }
  5813. TEST_F(ServerTest, StaticFileRangeHead) {
  5814. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5817. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5818. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5819. EXPECT_EQ(true, res->has_header("Content-Range"));
  5820. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5821. }
  5822. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5823. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5826. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5827. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5828. EXPECT_EQ(true, res->has_header("Content-Range"));
  5829. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5830. res->get_header_value("Content-Range"));
  5831. EXPECT_EQ("LAST\n", res->body);
  5832. }
  5833. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5834. auto res =
  5835. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5839. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5840. EXPECT_EQ(true, res->has_header("Content-Range"));
  5841. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5842. }
  5843. TEST_F(ServerTest, StaticFileBigFile) {
  5844. auto res = cli_.Get("/dir/1MB.txt");
  5845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5846. EXPECT_EQ(StatusCode::OK_200, res->status);
  5847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5848. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5849. }
  5850. TEST_F(ServerTest, InvalidBaseDirMount) {
  5851. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5852. }
  5853. TEST_F(ServerTest, Binary) {
  5854. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5855. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5856. "application/octet-stream");
  5857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5858. ASSERT_EQ(StatusCode::OK_200, res->status);
  5859. ASSERT_EQ(4U, res->body.size());
  5860. res = cli_.Put("/binary", binary.data(), binary.size(),
  5861. "application/octet-stream");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. ASSERT_EQ(StatusCode::OK_200, res->status);
  5864. ASSERT_EQ(4U, res->body.size());
  5865. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5866. "application/octet-stream");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. ASSERT_EQ(StatusCode::OK_200, res->status);
  5869. ASSERT_EQ(4U, res->body.size());
  5870. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5871. "application/octet-stream");
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. ASSERT_EQ(StatusCode::OK_200, res->status);
  5874. ASSERT_EQ(4U, res->body.size());
  5875. }
  5876. TEST_F(ServerTest, BinaryString) {
  5877. auto binary = std::string("\x00\x01\x02\x03", 4);
  5878. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5880. ASSERT_EQ(StatusCode::OK_200, res->status);
  5881. ASSERT_EQ(4U, res->body.size());
  5882. res = cli_.Put("/binary", binary, "application/octet-stream");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. ASSERT_EQ(StatusCode::OK_200, res->status);
  5885. ASSERT_EQ(4U, res->body.size());
  5886. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. ASSERT_EQ(StatusCode::OK_200, res->status);
  5889. ASSERT_EQ(4U, res->body.size());
  5890. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. ASSERT_EQ(StatusCode::OK_200, res->status);
  5893. ASSERT_EQ(4U, res->body.size());
  5894. }
  5895. TEST_F(ServerTest, EmptyRequest) {
  5896. auto res = cli_.Get("");
  5897. ASSERT_TRUE(!res);
  5898. EXPECT_EQ(Error::Connection, res.error());
  5899. }
  5900. TEST_F(ServerTest, LongRequest) {
  5901. std::string request;
  5902. for (size_t i = 0; i < 545; i++) {
  5903. request += "/TooLongRequest";
  5904. }
  5905. request += "OK";
  5906. auto res = cli_.Get(request.c_str());
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5909. }
  5910. TEST_F(ServerTest, TooLongRequest) {
  5911. std::string request;
  5912. for (size_t i = 0; i < 546; i++) {
  5913. request += "/TooLongRequest";
  5914. }
  5915. request += "_NG";
  5916. auto start = std::chrono::high_resolution_clock::now();
  5917. cli_.set_keep_alive(true);
  5918. auto res = cli_.Get(request.c_str());
  5919. auto end = std::chrono::high_resolution_clock::now();
  5920. auto elapsed =
  5921. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5922. .count();
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5925. EXPECT_LE(elapsed, 1000);
  5926. EXPECT_EQ("close", res->get_header_value("Connection"));
  5927. EXPECT_FALSE(cli_.is_socket_open());
  5928. }
  5929. TEST_F(ServerTest, AlmostTooLongRequest) {
  5930. // test for #2046 - URI length check shouldn't include other content on req
  5931. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5932. // leading /, space, HTTP/1.1)
  5933. std::string request =
  5934. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5935. auto res = cli_.Get(request.c_str());
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5938. }
  5939. TEST_F(ServerTest, LongHeader) {
  5940. Request req;
  5941. req.method = "GET";
  5942. req.path = "/hi";
  5943. std::string host_and_port;
  5944. host_and_port += HOST;
  5945. host_and_port += ":";
  5946. host_and_port += std::to_string(PORT);
  5947. req.headers.emplace("Host", host_and_port.c_str());
  5948. req.headers.emplace("Accept", "*/*");
  5949. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5950. req.headers.emplace(
  5951. "Header-Name",
  5952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5972. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5973. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5974. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5975. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5976. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5977. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5978. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5979. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5980. "@@@@@@@@@@@@@@@@");
  5981. auto res = std::make_shared<Response>();
  5982. auto error = Error::Success;
  5983. auto ret = cli_.send(req, *res, error);
  5984. ASSERT_TRUE(ret);
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. }
  5987. TEST_F(ServerTest, LongQueryValue) {
  5988. auto start = std::chrono::high_resolution_clock::now();
  5989. cli_.set_keep_alive(true);
  5990. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5991. auto end = std::chrono::high_resolution_clock::now();
  5992. auto elapsed =
  5993. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5994. .count();
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5997. EXPECT_LE(elapsed, 1000);
  5998. EXPECT_EQ("close", res->get_header_value("Connection"));
  5999. EXPECT_FALSE(cli_.is_socket_open());
  6000. }
  6001. TEST_F(ServerTest, TooLongQueryValue) {
  6002. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6003. ASSERT_FALSE(res);
  6004. EXPECT_EQ(Error::Read, res.error());
  6005. }
  6006. TEST_F(ServerTest, TooLongHeader) {
  6007. Request req;
  6008. req.method = "GET";
  6009. req.path = "/hi";
  6010. std::string host_and_port;
  6011. host_and_port += HOST;
  6012. host_and_port += ":";
  6013. host_and_port += std::to_string(PORT);
  6014. req.headers.emplace("Host", host_and_port.c_str());
  6015. req.headers.emplace("Accept", "*/*");
  6016. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6017. req.headers.emplace(
  6018. "Header-Name",
  6019. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6020. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6021. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6022. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6023. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6024. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6025. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6026. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6027. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6047. "@@@@@@@@@@@@@@@@@");
  6048. auto res = std::make_shared<Response>();
  6049. auto error = Error::Success;
  6050. auto ret = cli_.send(req, *res, error);
  6051. ASSERT_TRUE(ret);
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. }
  6054. TEST_F(ServerTest, HeaderCountAtLimit) {
  6055. // Test with headers just under the 100 limit
  6056. httplib::Headers headers;
  6057. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6058. // This should keep us just under the 100 header limit
  6059. for (int i = 0; i < 95; i++) {
  6060. std::string name = "X-Test-Header-" + std::to_string(i);
  6061. std::string value = "value" + std::to_string(i);
  6062. headers.emplace(name, value);
  6063. }
  6064. // This should work fine as we're under the limit
  6065. auto res = cli_.Get("/hi", headers);
  6066. EXPECT_TRUE(res);
  6067. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6068. }
  6069. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6070. // Test with many headers to exceed the 100 limit
  6071. httplib::Headers headers;
  6072. // Add 150 headers to definitely exceed the 100 limit
  6073. for (int i = 0; i < 150; i++) {
  6074. std::string name = "X-Test-Header-" + std::to_string(i);
  6075. std::string value = "value" + std::to_string(i);
  6076. headers.emplace(name, value);
  6077. }
  6078. // This should fail due to exceeding header count limit
  6079. cli_.set_keep_alive(true);
  6080. auto res = cli_.Get("/hi", headers);
  6081. // The server should respond with 400 Bad Request
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6084. EXPECT_EQ("close", res->get_header_value("Connection"));
  6085. EXPECT_FALSE(cli_.is_socket_open());
  6086. }
  6087. TEST_F(ServerTest, PercentEncoding) {
  6088. auto res = cli_.Get("/e%6edwith%");
  6089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6090. EXPECT_EQ(StatusCode::OK_200, res->status);
  6091. }
  6092. TEST_F(ServerTest, PercentEncodingUnicode) {
  6093. auto res = cli_.Get("/e%u006edwith%");
  6094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6095. EXPECT_EQ(StatusCode::OK_200, res->status);
  6096. }
  6097. TEST_F(ServerTest, InvalidPercentEncoding) {
  6098. auto res = cli_.Get("/%endwith%");
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6101. }
  6102. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6103. auto res = cli_.Get("/%uendwith%");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6106. }
  6107. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6108. auto res = cli_.Get("/hello?aaa=bbb%");
  6109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6110. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6111. }
  6112. TEST_F(ServerTest, PlusSignEncoding) {
  6113. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6115. EXPECT_EQ(StatusCode::OK_200, res->status);
  6116. EXPECT_EQ("a +b", res->body);
  6117. }
  6118. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6119. // This test simulates a potential DoS attack using many headers
  6120. // to verify our security fix prevents memory exhaustion
  6121. httplib::Headers attack_headers;
  6122. // Attempt to add many headers like an attacker would (200 headers to far
  6123. // exceed limit)
  6124. for (int i = 0; i < 200; i++) {
  6125. std::string name = "X-Attack-Header-" + std::to_string(i);
  6126. std::string value = "attack_payload_" + std::to_string(i);
  6127. attack_headers.emplace(name, value);
  6128. }
  6129. // Try to POST with excessive headers
  6130. cli_.set_keep_alive(true);
  6131. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6132. // Should either fail or return 400 Bad Request due to security limit
  6133. if (res) {
  6134. // If we get a response, it should be 400 Bad Request
  6135. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6136. EXPECT_EQ("close", res->get_header_value("Connection"));
  6137. }
  6138. EXPECT_FALSE(cli_.is_socket_open());
  6139. }
  6140. TEST_F(ServerTest, MultipartFormData) {
  6141. UploadFormDataItems items = {
  6142. {"text1", "text default", "", ""},
  6143. {"text2", "aωb", "", ""},
  6144. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6145. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6146. {"file3", "", "", "application/octet-stream"},
  6147. {"file4", "", "", " application/json tmp-string "}};
  6148. auto res = cli_.Post("/multipart", items);
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. EXPECT_EQ(StatusCode::OK_200, res->status);
  6151. }
  6152. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6153. UploadFormDataItems items = {
  6154. {"text", "default text", "", ""},
  6155. {"multi_text1", "aaaaa", "", ""},
  6156. {"multi_text1", "bbbbb", "", ""},
  6157. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6158. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6159. "application/json"},
  6160. };
  6161. auto res = cli_.Post("/multipart/multi_file_values", items);
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6166. auto res = cli_.Get("/hi");
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. EXPECT_EQ(StatusCode::OK_200, res->status);
  6169. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6170. EXPECT_EQ("Hello World!", res->body);
  6171. }
  6172. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6173. Request req;
  6174. req.method = "POST";
  6175. req.path = "/chunked";
  6176. std::string host_and_port;
  6177. host_and_port += HOST;
  6178. host_and_port += ":";
  6179. host_and_port += std::to_string(PORT);
  6180. req.headers.emplace("Host", host_and_port.c_str());
  6181. req.headers.emplace("Accept", "*/*");
  6182. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6183. req.headers.emplace("Content-Type", "text/plain");
  6184. req.headers.emplace("Content-Length", "0");
  6185. req.headers.emplace(
  6186. "Transfer-Encoding",
  6187. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6188. // Client does not chunk, so make a chunked body manually.
  6189. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6190. auto res = std::make_shared<Response>();
  6191. auto error = Error::Success;
  6192. auto ret = cli_.send(req, *res, error);
  6193. ASSERT_TRUE(ret);
  6194. EXPECT_EQ(StatusCode::OK_200, res->status);
  6195. }
  6196. template <typename ClientT>
  6197. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6198. int expected_status) {
  6199. Request req;
  6200. req.method = "POST";
  6201. req.path = "/chunked";
  6202. std::string host_and_port;
  6203. host_and_port += HOST;
  6204. host_and_port += ":";
  6205. host_and_port += std::to_string(PORT);
  6206. req.headers.emplace("Host", host_and_port.c_str());
  6207. req.headers.emplace("Content-Length", "0");
  6208. req.headers.emplace("Transfer-Encoding", "chunked");
  6209. req.body = body;
  6210. auto res = std::make_shared<Response>();
  6211. auto error = Error::Success;
  6212. ASSERT_TRUE(cli.send(req, *res, error));
  6213. EXPECT_EQ(expected_status, res->status);
  6214. }
  6215. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6216. // rather than treat them as valid lengths.
  6217. template <typename ClientT>
  6218. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6219. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6220. }
  6221. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6222. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6223. }
  6224. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6225. expect_chunked_body_rejected(
  6226. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6227. }
  6228. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6229. // chunk-size line carries no CR, LF or other control character ahead of its
  6230. // terminator. Such a line must be refused rather than read as extension text.
  6231. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6232. expect_chunked_body_rejected(
  6233. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6234. }
  6235. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6236. expect_chunked_body_rejected(
  6237. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6238. }
  6239. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6240. expect_chunked_body_rejected(
  6241. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6242. }
  6243. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6244. // The literal stays split: a hex escape consumes every hex digit that
  6245. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6246. expect_chunked_body_rejected(
  6247. cli_, "4;a\x01"
  6248. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6249. }
  6250. TEST_F(ServerTest, AcceptsChunkExtension) {
  6251. expect_chunked_body_status(cli_,
  6252. "4;name=value\r\ndech\r\n"
  6253. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6254. "0;last\r\n\r\n",
  6255. StatusCode::OK_200);
  6256. }
  6257. TEST_F(ServerTest, GetStreamed2) {
  6258. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6261. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6262. EXPECT_EQ(true, res->has_header("Content-Range"));
  6263. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6264. EXPECT_EQ(std::string("ab"), res->body);
  6265. }
  6266. TEST_F(ServerTest, GetStreamed) {
  6267. auto res = cli_.Get("/streamed");
  6268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6269. EXPECT_EQ(StatusCode::OK_200, res->status);
  6270. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6271. EXPECT_EQ(std::string("aaabbb"), res->body);
  6272. }
  6273. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6274. auto res = cli_.Get("/streamed-without-length",
  6275. Headers{make_range_header({{0, -1}})});
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. EXPECT_EQ(StatusCode::OK_200, res->status);
  6278. EXPECT_EQ(false, res->has_header("Content-Length"));
  6279. EXPECT_EQ(false, res->has_header("Content-Range"));
  6280. EXPECT_EQ(std::string("abcdefg"), res->body);
  6281. }
  6282. TEST_F(ServerTest, GetStreamedWithRange1) {
  6283. auto res =
  6284. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6287. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6288. EXPECT_EQ(true, res->has_header("Content-Range"));
  6289. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6290. EXPECT_EQ(std::string("def"), res->body);
  6291. }
  6292. TEST_F(ServerTest, GetStreamedWithRange2) {
  6293. auto res =
  6294. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6297. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6298. EXPECT_EQ(true, res->has_header("Content-Range"));
  6299. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6300. EXPECT_EQ(std::string("bcdefg"), res->body);
  6301. }
  6302. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6303. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6306. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6307. EXPECT_EQ(true, res->has_header("Content-Range"));
  6308. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6309. EXPECT_EQ(std::string("efg"), res->body);
  6310. }
  6311. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6312. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6313. // the entire representation.
  6314. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6315. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6318. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6319. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6320. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6321. }
  6322. }
  6323. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6324. auto res =
  6325. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6328. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6329. EXPECT_EQ(false, res->has_header("Content-Range"));
  6330. EXPECT_EQ(0U, res->body.size());
  6331. }
  6332. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6333. // Only a 206 is served as a partial representation. Under any other status
  6334. // `apply_ranges()` reported the full content length, so the body must match
  6335. // that header, and the content provider must never be asked for an offset
  6336. // outside the representation.
  6337. auto check = [&](int status, const char *range) {
  6338. auto path =
  6339. std::string("/streamed-with-range?status=") + std::to_string(status);
  6340. auto ctx = path + " Range: " + range;
  6341. auto res = cli_.Get(path, Headers{{"Range", range}});
  6342. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6343. EXPECT_EQ(status, res->status) << ctx;
  6344. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6346. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6347. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6348. };
  6349. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6350. check(403, "bytes=3-5");
  6351. // The offset is far past the representation.
  6352. check(403, "bytes=100000-100200");
  6353. // `first_pos` is still -1 here, and the bounds asserts in
  6354. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6355. check(403, "bytes=-3");
  6356. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6357. // multipart branch would have written one that is empty.
  6358. check(403, "bytes=1-2, 4-5");
  6359. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6360. // covers the whole representation.
  6361. check(200, "bytes=3-5");
  6362. check(200, "bytes=1-2, 4-5");
  6363. }
  6364. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6365. auto res =
  6366. cli_.Get("/streamed-with-range",
  6367. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6368. "92233720368547758079223372036854775807"}});
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6371. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6372. EXPECT_EQ(false, res->has_header("Content-Range"));
  6373. EXPECT_EQ(0U, res->body.size());
  6374. }
  6375. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6376. auto res = cli_.Get(
  6377. "/with-range",
  6378. Headers{{"Range",
  6379. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6380. {"Accept-Encoding", ""}});
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6383. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6384. EXPECT_EQ(true, res->has_header("Content-Range"));
  6385. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6386. EXPECT_EQ(std::string("abcdefg"), res->body);
  6387. }
  6388. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6389. auto res = cli_.Get("/with-range", Headers{
  6390. {"Range", "bytes=0-"},
  6391. {"Accept-Encoding", ""},
  6392. });
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6395. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6396. EXPECT_EQ(true, res->has_header("Content-Range"));
  6397. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6398. EXPECT_EQ(std::string("abcdefg"), res->body);
  6399. }
  6400. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6401. auto res = cli_.Get("/streamed-with-range",
  6402. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6405. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6406. EXPECT_EQ(false, res->has_header("Content-Range"));
  6407. EXPECT_EQ(267U, res->body.size());
  6408. // Check that both range contents are present
  6409. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6410. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6411. // Check that Content-Range headers are present for both ranges
  6412. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6413. std::string::npos);
  6414. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6415. std::string::npos);
  6416. }
  6417. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6418. Ranges ranges;
  6419. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6420. ranges.emplace_back(0, -1);
  6421. }
  6422. auto res = cli_.Get("/streamed-with-range?error",
  6423. Headers{{make_range_header(ranges)}});
  6424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6425. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6426. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6427. EXPECT_EQ(false, res->has_header("Content-Range"));
  6428. EXPECT_EQ(0U, res->body.size());
  6429. }
  6430. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6431. auto res = cli_.Get("/streamed-with-range",
  6432. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6435. EXPECT_EQ(5U, res->body.size());
  6436. // Check that overlapping ranges are coalesced into a single range
  6437. EXPECT_EQ("bcdef", res->body);
  6438. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6439. // Should be single range, not multipart
  6440. EXPECT_TRUE(res->has_header("Content-Range"));
  6441. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6442. }
  6443. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6444. auto res = cli_.Get("/streamed-with-range",
  6445. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6448. EXPECT_EQ(268U, res->body.size());
  6449. // Check that both range contents are present
  6450. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6451. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6452. // Check that Content-Range headers are present for both ranges
  6453. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6454. std::string::npos);
  6455. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6456. std::string::npos);
  6457. }
  6458. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6459. auto res = cli_.Get("/streamed-with-range",
  6460. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6463. EXPECT_EQ(269U, res->body.size());
  6464. // Check that both duplicate range contents are present
  6465. size_t first_abc = res->body.find("abc\r\n");
  6466. EXPECT_TRUE(first_abc != std::string::npos);
  6467. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6468. EXPECT_TRUE(second_abc != std::string::npos);
  6469. // Check that Content-Range headers are present for both ranges
  6470. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6471. EXPECT_TRUE(first_range != std::string::npos);
  6472. size_t second_range =
  6473. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6474. EXPECT_TRUE(second_range != std::string::npos);
  6475. }
  6476. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6477. auto res =
  6478. cli_.Get("/streamed-with-range?error",
  6479. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6482. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6483. EXPECT_EQ(false, res->has_header("Content-Range"));
  6484. EXPECT_EQ(0U, res->body.size());
  6485. }
  6486. TEST_F(ServerTest, GetStreamedEndless) {
  6487. uint64_t offset = 0;
  6488. auto res = cli_.Get("/streamed-cancel",
  6489. [&](const char * /*data*/, uint64_t data_length) {
  6490. if (offset < 100) {
  6491. offset += data_length;
  6492. return true;
  6493. }
  6494. return false;
  6495. });
  6496. ASSERT_TRUE(!res);
  6497. EXPECT_EQ(Error::Canceled, res.error());
  6498. }
  6499. TEST_F(ServerTest, ClientStop) {
  6500. std::atomic_size_t count{4};
  6501. std::vector<std::thread> threads;
  6502. for (auto i = count.load(); i != 0; --i) {
  6503. threads.emplace_back([&]() {
  6504. auto res = cli_.Get("/streamed-cancel",
  6505. [&](const char *, uint64_t) { return true; });
  6506. --count;
  6507. ASSERT_TRUE(!res);
  6508. EXPECT_TRUE(res.error() == Error::Canceled ||
  6509. res.error() == Error::Read || res.error() == Error::Write);
  6510. });
  6511. }
  6512. std::this_thread::sleep_for(std::chrono::seconds(2));
  6513. while (count != 0) {
  6514. cli_.stop();
  6515. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6516. }
  6517. for (auto &t : threads) {
  6518. t.join();
  6519. }
  6520. }
  6521. TEST_F(ServerTest, GetWithRange1) {
  6522. auto res = cli_.Get("/with-range", Headers{
  6523. make_range_header({{3, 5}}),
  6524. {"Accept-Encoding", ""},
  6525. });
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6528. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6529. EXPECT_EQ(true, res->has_header("Content-Range"));
  6530. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6531. EXPECT_EQ(std::string("def"), res->body);
  6532. }
  6533. TEST_F(ServerTest, GetWithRange2) {
  6534. auto res = cli_.Get("/with-range", Headers{
  6535. make_range_header({{1, -1}}),
  6536. {"Accept-Encoding", ""},
  6537. });
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6540. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6541. EXPECT_EQ(true, res->has_header("Content-Range"));
  6542. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6543. EXPECT_EQ(std::string("bcdefg"), res->body);
  6544. }
  6545. TEST_F(ServerTest, GetWithRange3) {
  6546. auto res = cli_.Get("/with-range", Headers{
  6547. make_range_header({{0, 0}}),
  6548. {"Accept-Encoding", ""},
  6549. });
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6552. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(true, res->has_header("Content-Range"));
  6554. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6555. EXPECT_EQ(std::string("a"), res->body);
  6556. }
  6557. TEST_F(ServerTest, GetWithRange4) {
  6558. auto res = cli_.Get("/with-range", Headers{
  6559. make_range_header({{-1, 2}}),
  6560. {"Accept-Encoding", ""},
  6561. });
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6564. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6565. EXPECT_EQ(true, res->has_header("Content-Range"));
  6566. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6567. EXPECT_EQ(std::string("fg"), res->body);
  6568. }
  6569. TEST_F(ServerTest, GetWithRange5) {
  6570. auto res = cli_.Get("/with-range", Headers{
  6571. make_range_header({{0, 5}}),
  6572. {"Accept-Encoding", ""},
  6573. });
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6577. EXPECT_EQ(true, res->has_header("Content-Range"));
  6578. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6579. EXPECT_EQ(std::string("abcdef"), res->body);
  6580. }
  6581. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6582. auto res =
  6583. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6586. }
  6587. TEST_F(ServerTest, GetWithRangeMultipart) {
  6588. auto res =
  6589. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6592. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6593. EXPECT_EQ(false, res->has_header("Content-Range"));
  6594. EXPECT_EQ(267U, res->body.size());
  6595. }
  6596. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6597. auto res = cli_.Get("/with-range",
  6598. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6601. }
  6602. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6603. auto res = cli_.Get("/with-range-customized-response",
  6604. Headers{{make_range_header({{1, 2}})}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6607. EXPECT_EQ(true, res->has_header("Content-Length"));
  6608. EXPECT_EQ(false, res->has_header("Content-Range"));
  6609. EXPECT_EQ(JSON_DATA, res->body);
  6610. }
  6611. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6612. auto res = cli_.Get("/with-range-customized-response",
  6613. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6616. EXPECT_EQ(true, res->has_header("Content-Length"));
  6617. EXPECT_EQ(false, res->has_header("Content-Range"));
  6618. EXPECT_EQ(JSON_DATA, res->body);
  6619. }
  6620. TEST_F(ServerTest, Issue1772) {
  6621. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6624. }
  6625. TEST_F(ServerTest, Issue609) {
  6626. auto res = cli_.Delete("/issue609");
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::OK_200, res->status);
  6629. EXPECT_EQ(std::string("ok"), res->body);
  6630. }
  6631. TEST_F(ServerTest, GetStreamedChunked) {
  6632. auto res = cli_.Get("/streamed-chunked");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ(std::string("123456789"), res->body);
  6636. }
  6637. TEST_F(ServerTest, GetStreamedChunked2) {
  6638. auto res = cli_.Get("/streamed-chunked2");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. EXPECT_EQ(StatusCode::OK_200, res->status);
  6641. EXPECT_EQ(std::string("123456789"), res->body);
  6642. }
  6643. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6644. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ(std::string("123456789"), res->body);
  6648. EXPECT_TRUE(res->has_header("Trailer"));
  6649. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6650. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6651. // Trailers are now stored separately from headers (security fix)
  6652. EXPECT_EQ(2U, res->trailers.size());
  6653. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6654. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6655. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6656. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6657. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6658. // Verify trailers are NOT in headers (security verification)
  6659. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6660. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6661. }
  6662. TEST_F(ServerTest, LargeChunkedPost) {
  6663. Request req;
  6664. req.method = "POST";
  6665. req.path = "/large-chunked";
  6666. std::string host_and_port;
  6667. host_and_port += HOST;
  6668. host_and_port += ":";
  6669. host_and_port += std::to_string(PORT);
  6670. req.headers.emplace("Host", host_and_port.c_str());
  6671. req.headers.emplace("Accept", "*/*");
  6672. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6673. req.headers.emplace("Content-Type", "text/plain");
  6674. req.headers.emplace("Content-Length", "0");
  6675. req.headers.emplace("Transfer-Encoding", "chunked");
  6676. std::string long_string(30 * 1024u, 'a');
  6677. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6678. // Attempt to make a large enough post to exceed OS buffers, to test that
  6679. // the server handles short reads if the full chunk data isn't available.
  6680. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6681. auto res = std::make_shared<Response>();
  6682. auto error = Error::Success;
  6683. auto ret = cli_.send(req, *res, error);
  6684. ASSERT_TRUE(ret);
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. }
  6687. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6688. auto res = cli_.Get("/remote_addr");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6692. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6693. }
  6694. TEST_F(ServerTest, GetMethodLocalAddr) {
  6695. auto res = cli_.Get("/local_addr");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6699. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6700. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6701. }
  6702. TEST_F(ServerTest, HTTPResponseSplitting) {
  6703. auto res = cli_.Get("/http_response_splitting");
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::OK_200, res->status);
  6706. }
  6707. TEST_F(ServerTest, SlowRequest) {
  6708. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6709. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6710. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6711. }
  6712. #if 0
  6713. TEST_F(ServerTest, SlowPost) {
  6714. char buffer[64 * 1024];
  6715. memset(buffer, 0x42, sizeof(buffer));
  6716. auto res = cli_.Post(
  6717. "/slowpost", 64 * 1024 * 1024,
  6718. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6719. auto ret = sink.write(buffer, sizeof(buffer));
  6720. EXPECT_TRUE(ret);
  6721. return true;
  6722. },
  6723. "text/plain");
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. EXPECT_EQ(StatusCode::OK_200, res->status);
  6726. }
  6727. TEST_F(ServerTest, SlowPostFail) {
  6728. char buffer[64 * 1024];
  6729. memset(buffer, 0x42, sizeof(buffer));
  6730. cli_.set_write_timeout(std::chrono::seconds(0));
  6731. auto res = cli_.Post(
  6732. "/slowpost", 64 * 1024 * 1024,
  6733. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6734. sink.write(buffer, sizeof(buffer));
  6735. return true;
  6736. },
  6737. "text/plain");
  6738. ASSERT_TRUE(!res);
  6739. EXPECT_EQ(Error::Write, res.error());
  6740. }
  6741. #endif
  6742. TEST_F(ServerTest, Put) {
  6743. auto res = cli_.Put("/put", "PUT", "text/plain");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("PUT", res->body);
  6747. }
  6748. TEST_F(ServerTest, PutWithContentProvider) {
  6749. auto res = cli_.Put(
  6750. "/put", 3,
  6751. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6752. sink.os << "PUT";
  6753. return true;
  6754. },
  6755. "text/plain");
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::OK_200, res->status);
  6758. EXPECT_EQ("PUT", res->body);
  6759. }
  6760. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6761. auto res = cli_.Post(
  6762. "/post", 42,
  6763. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6764. return false;
  6765. },
  6766. "text/plain");
  6767. ASSERT_TRUE(!res);
  6768. EXPECT_EQ(Error::Canceled, res.error());
  6769. }
  6770. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6771. auto res = cli_.Put(
  6772. "/put",
  6773. [](size_t /*offset*/, DataSink &sink) {
  6774. sink.os << "PUT";
  6775. sink.done();
  6776. return true;
  6777. },
  6778. "text/plain");
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ("PUT", res->body);
  6782. }
  6783. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6784. auto res = cli_.Post(
  6785. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6786. "text/plain");
  6787. ASSERT_TRUE(!res);
  6788. EXPECT_EQ(Error::Canceled, res.error());
  6789. }
  6790. TEST_F(ServerTest, PostLoopBack) {
  6791. std::string body;
  6792. auto res = cli_.Post(
  6793. "/post-loopback", 9,
  6794. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6795. EXPECT_EQ(9u, length);
  6796. sink.write("123", 3);
  6797. sink.write("456", 3);
  6798. sink.write("789", 3);
  6799. return true;
  6800. },
  6801. "text/plain",
  6802. [&body](const char *data, size_t data_length) {
  6803. body.append(data, data_length);
  6804. return true;
  6805. });
  6806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. EXPECT_EQ("123456789", body);
  6809. }
  6810. TEST_F(ServerTest, PutLoopBack) {
  6811. std::string body;
  6812. auto res = cli_.Put(
  6813. "/put-loopback", 9,
  6814. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6815. EXPECT_EQ(9u, length);
  6816. sink.write("123", 3);
  6817. sink.write("456", 3);
  6818. sink.write("789", 3);
  6819. return true;
  6820. },
  6821. "text/plain",
  6822. [&body](const char *data, size_t data_length) {
  6823. body.append(data, data_length);
  6824. return true;
  6825. });
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ("123456789", body);
  6829. }
  6830. TEST_F(ServerTest, PatchLoopBack) {
  6831. std::string body;
  6832. auto res = cli_.Patch(
  6833. "/patch-loopback", 9,
  6834. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6835. EXPECT_EQ(9u, length);
  6836. sink.write("123", 3);
  6837. sink.write("456", 3);
  6838. sink.write("789", 3);
  6839. return true;
  6840. },
  6841. "text/plain",
  6842. [&body](const char *data, size_t data_length) {
  6843. body.append(data, data_length);
  6844. return true;
  6845. });
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. EXPECT_EQ("123456789", body);
  6849. }
  6850. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6851. std::string body;
  6852. auto res = cli_.Post(
  6853. "/post-loopback",
  6854. [](size_t /*offset*/, DataSink &sink) {
  6855. sink.write("123", 3);
  6856. sink.write("456", 3);
  6857. sink.write("789", 3);
  6858. sink.done();
  6859. return true;
  6860. },
  6861. "text/plain",
  6862. [&body](const char *data, size_t data_length) {
  6863. body.append(data, data_length);
  6864. return true;
  6865. });
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("123456789", body);
  6869. }
  6870. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6871. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6872. cli_.set_compress(true);
  6873. auto res = cli_.Put(
  6874. "/put", 3,
  6875. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6876. sink.os << "PUT";
  6877. return true;
  6878. },
  6879. "text/plain");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("PUT", res->body);
  6883. }
  6884. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6885. cli_.set_compress(true);
  6886. auto res = cli_.Post(
  6887. "/post", 42,
  6888. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6889. return false;
  6890. },
  6891. "text/plain");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::Canceled, res.error());
  6894. }
  6895. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6896. cli_.set_compress(true);
  6897. auto res = cli_.Put(
  6898. "/put",
  6899. [](size_t /*offset*/, DataSink &sink) {
  6900. sink.os << "PUT";
  6901. sink.done();
  6902. return true;
  6903. },
  6904. "text/plain");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. EXPECT_EQ("PUT", res->body);
  6908. }
  6909. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6910. cli_.set_compress(true);
  6911. auto res = cli_.Post(
  6912. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6913. "text/plain");
  6914. ASSERT_TRUE(!res);
  6915. EXPECT_EQ(Error::Canceled, res.error());
  6916. }
  6917. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6918. cli_.set_compress(true);
  6919. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::OK_200, res->status);
  6922. EXPECT_EQ(LARGE_DATA, res->body);
  6923. }
  6924. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6925. #ifdef CPPHTTPLIB_SSL_ENABLED
  6926. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6927. Client cli(s.c_str());
  6928. cli.enable_server_certificate_verification(false);
  6929. #else
  6930. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6931. Client cli(s.c_str());
  6932. #endif
  6933. cli.set_compress(true);
  6934. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. EXPECT_EQ(LARGE_DATA, res->body);
  6938. // The compressed size should be less than a 10th of the original. May vary
  6939. // depending on the zlib library.
  6940. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6941. static_cast<uint64_t>(10 * 1024 * 1024));
  6942. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6943. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6944. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6945. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6946. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6947. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6948. #endif
  6949. }
  6950. TEST_F(ServerTest, PutContentWithDeflate) {
  6951. cli_.set_compress(false);
  6952. Headers headers;
  6953. headers.emplace("Content-Encoding", "deflate");
  6954. // PUT in deflate format:
  6955. auto res = cli_.Put("/put", headers,
  6956. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. EXPECT_EQ("PUT", res->body);
  6960. }
  6961. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6962. Headers headers;
  6963. headers.emplace("Accept-Encoding", "gzip, deflate");
  6964. auto res = cli_.Get("/streamed-chunked", headers);
  6965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. EXPECT_EQ(std::string("123456789"), res->body);
  6968. }
  6969. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6970. Headers headers;
  6971. headers.emplace("Accept-Encoding", "gzip, deflate");
  6972. auto res = cli_.Get("/streamed-chunked2", headers);
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. EXPECT_EQ(StatusCode::OK_200, res->status);
  6975. EXPECT_EQ(std::string("123456789"), res->body);
  6976. }
  6977. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6978. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::OK_200, res->status);
  6981. }
  6982. TEST(GzipDecompressor, ChunkedDecompression) {
  6983. std::string data;
  6984. for (size_t i = 0; i < 32 * 1024; ++i) {
  6985. data.push_back(static_cast<char>('a' + i % 26));
  6986. }
  6987. std::string compressed_data;
  6988. {
  6989. httplib::detail::gzip_compressor compressor;
  6990. bool result = compressor.compress(
  6991. data.data(), data.size(),
  6992. /*last=*/true,
  6993. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6994. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6995. compressed_data_size);
  6996. return true;
  6997. });
  6998. ASSERT_TRUE(result);
  6999. }
  7000. std::string decompressed_data;
  7001. {
  7002. httplib::detail::gzip_decompressor decompressor;
  7003. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7004. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7005. size_t chunk_size = 130;
  7006. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7007. chunk_begin += chunk_size) {
  7008. size_t current_chunk_size =
  7009. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7010. bool result = decompressor.decompress(
  7011. compressed_data.data() + chunk_begin, current_chunk_size,
  7012. [&](const char *decompressed_data_chunk,
  7013. size_t decompressed_data_chunk_size) {
  7014. decompressed_data.insert(decompressed_data.size(),
  7015. decompressed_data_chunk,
  7016. decompressed_data_chunk_size);
  7017. return true;
  7018. });
  7019. ASSERT_TRUE(result);
  7020. }
  7021. }
  7022. ASSERT_EQ(data, decompressed_data);
  7023. }
  7024. TEST(GzipDecompressor, DeflateDecompression) {
  7025. std::string original_text = "Raw deflate without gzip";
  7026. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7027. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7028. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7029. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7030. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7031. std::string decompressed_data;
  7032. {
  7033. httplib::detail::gzip_decompressor decompressor;
  7034. bool result = decompressor.decompress(
  7035. compressed_data.data(), compressed_data.size(),
  7036. [&](const char *decompressed_data_chunk,
  7037. size_t decompressed_data_chunk_size) {
  7038. decompressed_data.insert(decompressed_data.size(),
  7039. decompressed_data_chunk,
  7040. decompressed_data_chunk_size);
  7041. return true;
  7042. });
  7043. ASSERT_TRUE(result);
  7044. }
  7045. ASSERT_EQ(original_text, decompressed_data);
  7046. }
  7047. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7048. std::string original_text = "Raw deflate without gzip";
  7049. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7050. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7051. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7052. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7053. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7054. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7055. std::string decompressed_data;
  7056. {
  7057. httplib::detail::gzip_decompressor decompressor;
  7058. bool result = decompressor.decompress(
  7059. compressed_data.data(), compressed_data.size(),
  7060. [&](const char *decompressed_data_chunk,
  7061. size_t decompressed_data_chunk_size) {
  7062. decompressed_data.insert(decompressed_data.size(),
  7063. decompressed_data_chunk,
  7064. decompressed_data_chunk_size);
  7065. return true;
  7066. });
  7067. ASSERT_TRUE(result);
  7068. }
  7069. ASSERT_EQ(original_text, decompressed_data);
  7070. }
  7071. #endif
  7072. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7073. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7074. Headers headers;
  7075. headers.emplace("Accept-Encoding", "br");
  7076. auto res = cli_.Get("/streamed-chunked", headers);
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::OK_200, res->status);
  7079. EXPECT_EQ(std::string("123456789"), res->body);
  7080. }
  7081. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7082. Headers headers;
  7083. headers.emplace("Accept-Encoding", "br");
  7084. auto res = cli_.Get("/streamed-chunked2", headers);
  7085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7086. EXPECT_EQ(StatusCode::OK_200, res->status);
  7087. EXPECT_EQ(std::string("123456789"), res->body);
  7088. }
  7089. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7090. cli_.set_compress(true);
  7091. auto res = cli_.Put(
  7092. "/put", 3,
  7093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7094. sink.os << "PUT";
  7095. return true;
  7096. },
  7097. "text/plain");
  7098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7099. EXPECT_EQ(StatusCode::OK_200, res->status);
  7100. EXPECT_EQ("PUT", res->body);
  7101. }
  7102. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7103. cli_.set_compress(true);
  7104. auto res = cli_.Put(
  7105. "/put",
  7106. [](size_t /*offset*/, DataSink &sink) {
  7107. sink.os << "PUT";
  7108. sink.done();
  7109. return true;
  7110. },
  7111. "text/plain");
  7112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7113. EXPECT_EQ(StatusCode::OK_200, res->status);
  7114. EXPECT_EQ("PUT", res->body);
  7115. }
  7116. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7117. cli_.set_compress(true);
  7118. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::OK_200, res->status);
  7121. EXPECT_EQ(LARGE_DATA, res->body);
  7122. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7123. }
  7124. #endif
  7125. TEST_F(ServerTest, Patch) {
  7126. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ(StatusCode::OK_200, res->status);
  7129. EXPECT_EQ("PATCH", res->body);
  7130. }
  7131. TEST_F(ServerTest, Delete) {
  7132. auto res = cli_.Delete("/delete");
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. EXPECT_EQ("DELETE", res->body);
  7136. }
  7137. TEST_F(ServerTest, DeleteContentReceiver) {
  7138. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. EXPECT_EQ("content", res->body);
  7142. }
  7143. TEST_F(ServerTest, Options) {
  7144. auto res = cli_.Options("*");
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::OK_200, res->status);
  7147. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7148. EXPECT_TRUE(res->body.empty());
  7149. }
  7150. TEST_F(ServerTest, URL) {
  7151. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::OK_200, res->status);
  7154. }
  7155. TEST_F(ServerTest, ArrayParam) {
  7156. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST_F(ServerTest, ArrayParamValues) {
  7161. auto res =
  7162. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::OK_200, res->status);
  7165. }
  7166. TEST_F(ServerTest, NoMultipleHeaders) {
  7167. Headers headers = {{"Content-Length", "5"}};
  7168. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7169. "text/plain");
  7170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7171. EXPECT_EQ(StatusCode::OK_200, res->status);
  7172. }
  7173. TEST_F(ServerTest, PostContentReceiver) {
  7174. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. ASSERT_EQ(StatusCode::OK_200, res->status);
  7177. ASSERT_EQ("content", res->body);
  7178. }
  7179. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7180. UploadFormDataItems items = {
  7181. {"text1", "text default", "", ""},
  7182. {"text2", "aωb", "", ""},
  7183. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7184. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7185. {"file3", "", "", "application/octet-stream"},
  7186. };
  7187. auto res = cli_.Post("/content_receiver", items);
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. }
  7191. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7192. UploadFormDataItems items = {
  7193. {"text1", "text default", "", ""},
  7194. {"text2", "aωb", "", ""},
  7195. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7196. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7197. {"file3", "", "", "application/octet-stream"},
  7198. };
  7199. auto boundary = std::string("+++++");
  7200. std::string body;
  7201. for (const auto &item : items) {
  7202. body += "--" + boundary + "\r\n";
  7203. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7204. if (!item.filename.empty()) {
  7205. body += "; filename=\"" + item.filename + "\"";
  7206. }
  7207. body += "\r\n";
  7208. if (!item.content_type.empty()) {
  7209. body += "Content-Type: " + item.content_type + "\r\n";
  7210. }
  7211. body += "\r\n";
  7212. body += item.content + "\r\n";
  7213. }
  7214. body += "--" + boundary + "--\r\n";
  7215. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7216. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. }
  7220. TEST(MultipartFormDataTest, FieldEscaping) {
  7221. Server svr;
  7222. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7223. const ContentReader &content_reader) {
  7224. ASSERT_TRUE(req.is_multipart_form_data());
  7225. std::vector<FormData> received;
  7226. content_reader(
  7227. [&](const FormData &file) {
  7228. received.push_back(file);
  7229. return true;
  7230. },
  7231. [&](const char *data, size_t data_length) {
  7232. received.back().content.append(data, data_length);
  7233. return true;
  7234. });
  7235. // '"', CR and LF in names and filenames are escaped following the
  7236. // WHATWG HTML standard, so each part still parses as a single part
  7237. // with no injected headers. Content types get CR/LF escaped too,
  7238. // while '"' (legal there, e.g. quoted charset) is preserved.
  7239. ASSERT_EQ(4U, received.size());
  7240. EXPECT_EQ("na%22me", received[0].name);
  7241. EXPECT_EQ("quoted name", received[0].content);
  7242. EXPECT_EQ("file", received[1].name);
  7243. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7244. received[1].filename);
  7245. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7246. EXPECT_EQ("injected", received[1].content);
  7247. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7248. EXPECT_EQ("my%22file.txt", received[2].filename);
  7249. EXPECT_EQ("cr lf name", received[2].content);
  7250. EXPECT_EQ("typed", received[3].name);
  7251. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7252. received[3].content_type);
  7253. EXPECT_EQ("typed content", received[3].content);
  7254. });
  7255. auto port = svr.bind_to_any_port("localhost");
  7256. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7257. auto se = detail::scope_exit([&] {
  7258. svr.stop();
  7259. t.join();
  7260. ASSERT_FALSE(svr.is_running());
  7261. });
  7262. svr.wait_until_ready();
  7263. Client cli("localhost", port);
  7264. UploadFormDataItems items = {
  7265. {"na\"me", "quoted name", "", ""},
  7266. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7267. "application/octet-stream"},
  7268. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7269. {"typed", "typed content", "",
  7270. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7271. };
  7272. auto res = cli.Post("/post", items);
  7273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7274. EXPECT_EQ(StatusCode::OK_200, res->status);
  7275. }
  7276. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7277. const UploadFormDataItems items = {
  7278. {"name1", "Content 1", "", ""},
  7279. {"name2", "Content 2", "file2.txt", "text/plain"},
  7280. };
  7281. Server svr;
  7282. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7283. const ContentReader &content_reader) {
  7284. ASSERT_TRUE(req.is_multipart_form_data());
  7285. std::vector<FormData> received;
  7286. content_reader(
  7287. [&](const FormData &file) {
  7288. received.push_back(file);
  7289. return true;
  7290. },
  7291. [&](const char *data, size_t data_length) {
  7292. received.back().content.append(data, data_length);
  7293. return true;
  7294. });
  7295. ASSERT_EQ(2U, received.size());
  7296. EXPECT_EQ("name1", received[0].name);
  7297. EXPECT_EQ("Content 1", received[0].content);
  7298. EXPECT_EQ("name2", received[1].name);
  7299. EXPECT_EQ("Content 2", received[1].content);
  7300. EXPECT_EQ("file2.txt", received[1].filename);
  7301. EXPECT_EQ("text/plain", received[1].content_type);
  7302. });
  7303. auto port = svr.bind_to_any_port("localhost");
  7304. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7305. auto se = detail::scope_exit([&] {
  7306. svr.stop();
  7307. t.join();
  7308. ASSERT_FALSE(svr.is_running());
  7309. });
  7310. svr.wait_until_ready();
  7311. Client cli("localhost", port);
  7312. // Whole-body serialization with a generated boundary
  7313. {
  7314. MultipartFormDataWriter writer;
  7315. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7316. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7317. writer.content_type());
  7318. auto body = writer.serialize(items);
  7319. EXPECT_EQ(body.size(), writer.content_length(items));
  7320. auto res = cli.Post("/post", body, writer.content_type());
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::OK_200, res->status);
  7323. }
  7324. // Per-part framing with a custom boundary via a content provider
  7325. {
  7326. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7327. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7328. MultipartFormDataWriter writer("custom-boundary_123");
  7329. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7330. std::string body;
  7331. for (const auto &item : items) {
  7332. body += writer.item_begin(item);
  7333. body += item.content;
  7334. body += MultipartFormDataWriter::item_end();
  7335. }
  7336. body += writer.finish();
  7337. EXPECT_EQ(body.size(), writer.content_length(items));
  7338. auto res = cli.Post(
  7339. "/post", body.size(),
  7340. [&](size_t offset, size_t length, DataSink &sink) {
  7341. sink.write(body.data() + offset, length);
  7342. return true;
  7343. },
  7344. writer.content_type());
  7345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7346. EXPECT_EQ(StatusCode::OK_200, res->status);
  7347. }
  7348. }
  7349. TEST_F(ServerTest, PostContentReceiverGzip) {
  7350. cli_.set_compress(true);
  7351. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. ASSERT_EQ(StatusCode::OK_200, res->status);
  7354. ASSERT_EQ("content", res->body);
  7355. }
  7356. TEST_F(ServerTest, PutContentReceiver) {
  7357. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. ASSERT_EQ(StatusCode::OK_200, res->status);
  7360. ASSERT_EQ("content", res->body);
  7361. }
  7362. TEST_F(ServerTest, PatchContentReceiver) {
  7363. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7365. ASSERT_EQ(StatusCode::OK_200, res->status);
  7366. ASSERT_EQ("content", res->body);
  7367. }
  7368. template <typename ClientType>
  7369. void TestWithHeadersAndContentReceiver(
  7370. ClientType &cli,
  7371. std::function<Result(ClientType &, const std::string &, const Headers &,
  7372. const std::string &, const std::string &,
  7373. ContentReceiver, DownloadProgress)>
  7374. request_func) {
  7375. Headers headers;
  7376. headers.emplace("X-Custom-Header", "test-value");
  7377. std::string received_body;
  7378. auto res = request_func(
  7379. cli, "/content_receiver", headers, "content", "application/json",
  7380. [&](const char *data, size_t data_length) {
  7381. received_body.append(data, data_length);
  7382. return true;
  7383. },
  7384. nullptr);
  7385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7386. EXPECT_EQ(StatusCode::OK_200, res->status);
  7387. EXPECT_EQ("content", received_body);
  7388. }
  7389. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7390. #ifdef CPPHTTPLIB_SSL_ENABLED
  7391. using ClientT = SSLClient;
  7392. #else
  7393. using ClientT = Client;
  7394. #endif
  7395. TestWithHeadersAndContentReceiver<ClientT>(
  7396. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7397. const std::string &body, const std::string &content_type,
  7398. ContentReceiver receiver, DownloadProgress progress) {
  7399. return cli.Post(path, headers, body, content_type, receiver, progress);
  7400. });
  7401. }
  7402. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7403. #ifdef CPPHTTPLIB_SSL_ENABLED
  7404. using ClientT = SSLClient;
  7405. #else
  7406. using ClientT = Client;
  7407. #endif
  7408. TestWithHeadersAndContentReceiver<ClientT>(
  7409. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7410. const std::string &body, const std::string &content_type,
  7411. ContentReceiver receiver, DownloadProgress progress) {
  7412. return cli.Put(path, headers, body, content_type, receiver, progress);
  7413. });
  7414. }
  7415. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7416. #ifdef CPPHTTPLIB_SSL_ENABLED
  7417. using ClientT = SSLClient;
  7418. #else
  7419. using ClientT = Client;
  7420. #endif
  7421. TestWithHeadersAndContentReceiver<ClientT>(
  7422. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7423. const std::string &body, const std::string &content_type,
  7424. ContentReceiver receiver, DownloadProgress progress) {
  7425. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7426. });
  7427. }
  7428. template <typename ClientType>
  7429. void TestWithHeadersAndContentReceiverWithProgress(
  7430. ClientType &cli,
  7431. std::function<Result(ClientType &, const std::string &, const Headers &,
  7432. const std::string &, const std::string &,
  7433. ContentReceiver, DownloadProgress)>
  7434. request_func) {
  7435. Headers headers;
  7436. headers.emplace("X-Test-Header", "progress-test");
  7437. std::string received_body;
  7438. auto progress_called = false;
  7439. auto res = request_func(
  7440. cli, "/content_receiver", headers, "content", "text/plain",
  7441. [&](const char *data, size_t data_length) {
  7442. received_body.append(data, data_length);
  7443. return true;
  7444. },
  7445. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7446. progress_called = true;
  7447. return true;
  7448. });
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. EXPECT_EQ("content", received_body);
  7452. EXPECT_TRUE(progress_called);
  7453. }
  7454. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. using ClientT = SSLClient;
  7457. #else
  7458. using ClientT = Client;
  7459. #endif
  7460. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7461. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7462. const std::string &body, const std::string &content_type,
  7463. ContentReceiver receiver, DownloadProgress progress) {
  7464. return cli.Post(path, headers, body, content_type, receiver, progress);
  7465. });
  7466. }
  7467. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7468. #ifdef CPPHTTPLIB_SSL_ENABLED
  7469. using ClientT = SSLClient;
  7470. #else
  7471. using ClientT = Client;
  7472. #endif
  7473. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7474. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7475. const std::string &body, const std::string &content_type,
  7476. ContentReceiver receiver, DownloadProgress progress) {
  7477. return cli.Put(path, headers, body, content_type, receiver, progress);
  7478. });
  7479. }
  7480. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7481. #ifdef CPPHTTPLIB_SSL_ENABLED
  7482. using ClientT = SSLClient;
  7483. #else
  7484. using ClientT = Client;
  7485. #endif
  7486. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7487. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7488. const std::string &body, const std::string &content_type,
  7489. ContentReceiver receiver, DownloadProgress progress) {
  7490. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7491. });
  7492. }
  7493. template <typename ClientType>
  7494. void TestWithHeadersAndContentReceiverError(
  7495. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7496. const Headers &, const std::string &,
  7497. const std::string &, ContentReceiver)>
  7498. request_func) {
  7499. Headers headers;
  7500. headers.emplace("X-Error-Test", "true");
  7501. std::string received_body;
  7502. auto receiver_failed = false;
  7503. auto res =
  7504. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7505. [&](const char *data, size_t data_length) {
  7506. received_body.append(data, data_length);
  7507. receiver_failed = true;
  7508. return false;
  7509. });
  7510. ASSERT_FALSE(res);
  7511. EXPECT_TRUE(receiver_failed);
  7512. }
  7513. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7514. #ifdef CPPHTTPLIB_SSL_ENABLED
  7515. using ClientT = SSLClient;
  7516. #else
  7517. using ClientT = Client;
  7518. #endif
  7519. TestWithHeadersAndContentReceiverError<ClientT>(
  7520. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7521. const std::string &body, const std::string &content_type,
  7522. ContentReceiver receiver) {
  7523. return cli.Post(path, headers, body, content_type, receiver);
  7524. });
  7525. }
  7526. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7527. #ifdef CPPHTTPLIB_SSL_ENABLED
  7528. using ClientT = SSLClient;
  7529. #else
  7530. using ClientT = Client;
  7531. #endif
  7532. TestWithHeadersAndContentReceiverError<ClientT>(
  7533. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7534. const std::string &body, const std::string &content_type,
  7535. ContentReceiver receiver) {
  7536. return cli.Put(path, headers, body, content_type, receiver);
  7537. });
  7538. }
  7539. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7540. #ifdef CPPHTTPLIB_SSL_ENABLED
  7541. using ClientT = SSLClient;
  7542. #else
  7543. using ClientT = Client;
  7544. #endif
  7545. TestWithHeadersAndContentReceiverError<ClientT>(
  7546. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7547. const std::string &body, const std::string &content_type,
  7548. ContentReceiver receiver) {
  7549. return cli.Patch(path, headers, body, content_type, receiver);
  7550. });
  7551. }
  7552. TEST_F(ServerTest, PostQueryStringAndBody) {
  7553. auto res =
  7554. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. ASSERT_EQ(StatusCode::OK_200, res->status);
  7557. }
  7558. TEST_F(ServerTest, HTTP2Magic) {
  7559. Request req;
  7560. req.method = "PRI";
  7561. req.path = "*";
  7562. req.body = "SM";
  7563. auto res = std::make_shared<Response>();
  7564. auto error = Error::Success;
  7565. auto ret = cli_.send(req, *res, error);
  7566. ASSERT_TRUE(ret);
  7567. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7568. }
  7569. TEST_F(ServerTest, KeepAlive) {
  7570. auto res = cli_.Get("/hi");
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7574. EXPECT_EQ("Hello World!", res->body);
  7575. res = cli_.Get("/hi");
  7576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7577. EXPECT_EQ(StatusCode::OK_200, res->status);
  7578. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7579. EXPECT_EQ("Hello World!", res->body);
  7580. res = cli_.Get("/hi");
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::OK_200, res->status);
  7583. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7584. EXPECT_EQ("Hello World!", res->body);
  7585. res = cli_.Get("/not-exist");
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7588. res = cli_.Post("/empty", "", "text/plain");
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7592. EXPECT_EQ("empty", res->body);
  7593. EXPECT_EQ("close", res->get_header_value("Connection"));
  7594. res = cli_.Post(
  7595. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7596. "text/plain");
  7597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7598. EXPECT_EQ(StatusCode::OK_200, res->status);
  7599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7600. EXPECT_EQ("empty", res->body);
  7601. cli_.set_keep_alive(false);
  7602. res = cli_.Get("/last-request");
  7603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7604. EXPECT_EQ(StatusCode::OK_200, res->status);
  7605. EXPECT_EQ("close", res->get_header_value("Connection"));
  7606. }
  7607. TEST_F(ServerTest, TooManyRedirect) {
  7608. cli_.set_follow_location(true);
  7609. auto res = cli_.Get("/redirect/0");
  7610. ASSERT_TRUE(!res);
  7611. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7612. }
  7613. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7614. Request req;
  7615. req.method = "FOOBAR";
  7616. req.path = "/hi";
  7617. cli_.set_keep_alive(true);
  7618. auto res = cli_.send(req);
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7621. EXPECT_EQ("close", res->get_header_value("Connection"));
  7622. EXPECT_FALSE(cli_.is_socket_open());
  7623. }
  7624. TEST_F(ServerTest, CustomRouteReadsBody) {
  7625. const std::string xml =
  7626. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7627. Request req;
  7628. req.method = "PROPFIND";
  7629. req.path = "/dav/dir";
  7630. req.set_header("Depth", "1");
  7631. req.body = xml;
  7632. auto res = cli_.send(req);
  7633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7634. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7635. EXPECT_EQ(xml, res->body);
  7636. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7637. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7638. }
  7639. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7640. Request req;
  7641. req.method = "PROPFIND";
  7642. req.path = "/dav/42";
  7643. auto res = cli_.send(req);
  7644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7645. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7646. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7647. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7648. }
  7649. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7650. Request req;
  7651. req.method = "PROPFIND";
  7652. req.path = "/dav-re/123";
  7653. auto res = cli_.send(req);
  7654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7655. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7656. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7657. }
  7658. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7659. Request req;
  7660. req.method = "MKCOL";
  7661. req.path = "/dav-mkcol";
  7662. auto res = cli_.send(req);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::Created_201, res->status);
  7665. }
  7666. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7667. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7668. Request req;
  7669. req.method = "REPORT";
  7670. req.path = "/dav-report";
  7671. req.body = xml;
  7672. auto res = cli_.send(req);
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7675. EXPECT_EQ(xml, res->body);
  7676. }
  7677. // A content reader route must fire even when the request carries no body,
  7678. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7679. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7680. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7681. Request req;
  7682. req.method = "REPORT";
  7683. req.path = "/dav-report";
  7684. auto res = cli_.send(req);
  7685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7686. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7687. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7688. }
  7689. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7690. Request req;
  7691. req.method = "PROPFIND";
  7692. req.path = "/not-dav";
  7693. auto res = cli_.send(req);
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7696. }
  7697. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7698. Request req;
  7699. req.method = "UNLOCK";
  7700. req.path = "/dav/dir";
  7701. cli_.set_keep_alive(true);
  7702. auto res = cli_.send(req);
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7705. EXPECT_EQ("close", res->get_header_value("Connection"));
  7706. EXPECT_FALSE(cli_.is_socket_open());
  7707. }
  7708. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7709. // The mount point serves this path, but only for GET and HEAD.
  7710. auto get_res = cli_.Get("/dir/index.html");
  7711. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7712. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7713. Request req;
  7714. req.method = "PROPFIND";
  7715. req.path = "/dir/index.html";
  7716. auto res = cli_.send(req);
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7719. }
  7720. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7721. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7722. cli_.set_keep_alive(true);
  7723. for (auto i = 0; i < 2; i++) {
  7724. Request req;
  7725. req.method = "PROPFIND";
  7726. req.path = "/dav/dir";
  7727. req.body = xml;
  7728. auto res = cli_.send(req);
  7729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7730. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7731. EXPECT_EQ(xml, res->body);
  7732. EXPECT_TRUE(cli_.is_socket_open());
  7733. }
  7734. // A built-in method must still be served on the same connection.
  7735. cli_.set_keep_alive(false);
  7736. auto res = cli_.Get("/hi");
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("close", res->get_header_value("Connection"));
  7740. }
  7741. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7742. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7743. Request req;
  7744. req.method = "PROPFIND";
  7745. req.path = "/dav/dir";
  7746. req.set_header("Expect", "100-continue");
  7747. req.body = xml;
  7748. auto res = cli_.send(req);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7751. EXPECT_EQ(xml, res->body);
  7752. }
  7753. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7754. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7755. TEST_F(ServerTest, Gzip) {
  7756. Headers headers;
  7757. headers.emplace("Accept-Encoding", "gzip, deflate");
  7758. auto res = cli_.Get("/compress", headers);
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7762. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7763. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7764. "7890123456789012345678901234567890",
  7765. res->body);
  7766. EXPECT_EQ(StatusCode::OK_200, res->status);
  7767. }
  7768. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7769. Headers headers;
  7770. headers.emplace("Accept-Encoding", "gzip, deflate");
  7771. auto res = cli_.Get("/compress-with-charset", headers);
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7774. EXPECT_EQ("application/json; charset=utf-8",
  7775. res->get_header_value("Content-Type"));
  7776. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7777. "7890123456789012345678901234567890",
  7778. res->body);
  7779. EXPECT_EQ(StatusCode::OK_200, res->status);
  7780. }
  7781. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7782. Headers headers;
  7783. headers.emplace("Accept-Encoding", "");
  7784. auto res = cli_.Get("/compress", headers);
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7788. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7789. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7790. "7890123456789012345678901234567890",
  7791. res->body);
  7792. EXPECT_EQ(StatusCode::OK_200, res->status);
  7793. }
  7794. TEST_F(ServerTest, GzipWithContentReceiver) {
  7795. Headers headers;
  7796. headers.emplace("Accept-Encoding", "gzip, deflate");
  7797. std::string body;
  7798. auto res = cli_.Get("/compress", headers,
  7799. [&](const char *data, uint64_t data_length) {
  7800. EXPECT_EQ(100U, data_length);
  7801. body.append(data, data_length);
  7802. return true;
  7803. });
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7807. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7808. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7809. "7890123456789012345678901234567890",
  7810. body);
  7811. EXPECT_EQ(StatusCode::OK_200, res->status);
  7812. }
  7813. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7814. Headers headers;
  7815. headers.emplace("Accept-Encoding", "gzip, deflate");
  7816. cli_.set_decompress(false);
  7817. auto res = cli_.Get("/compress", headers);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7821. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(33U, res->body.size());
  7823. EXPECT_EQ(StatusCode::OK_200, res->status);
  7824. }
  7825. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7826. Headers headers;
  7827. headers.emplace("Accept-Encoding", "");
  7828. std::string body;
  7829. auto res = cli_.Get("/compress", headers,
  7830. [&](const char *data, uint64_t data_length) {
  7831. EXPECT_EQ(100U, data_length);
  7832. body.append(data, data_length);
  7833. return true;
  7834. });
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7838. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7840. "7890123456789012345678901234567890",
  7841. body);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. }
  7844. TEST_F(ServerTest, NoGzip) {
  7845. Headers headers;
  7846. headers.emplace("Accept-Encoding", "gzip, deflate");
  7847. auto res = cli_.Get("/nocompress", headers);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7850. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7851. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7852. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7853. "7890123456789012345678901234567890",
  7854. res->body);
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. }
  7857. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7858. Headers headers;
  7859. headers.emplace("Accept-Encoding", "gzip, deflate");
  7860. std::string body;
  7861. auto res = cli_.Get("/nocompress", headers,
  7862. [&](const char *data, uint64_t data_length) {
  7863. EXPECT_EQ(100U, data_length);
  7864. body.append(data, data_length);
  7865. return true;
  7866. });
  7867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7868. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7869. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7870. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7871. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7872. "7890123456789012345678901234567890",
  7873. body);
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. }
  7876. TEST_F(ServerTest, MultipartFormDataGzip) {
  7877. UploadFormDataItems items = {
  7878. {"key1", "test", "", ""},
  7879. {"key2", "--abcdefg123", "", ""},
  7880. };
  7881. cli_.set_compress(true);
  7882. auto res = cli_.Post("/compress-multipart", items);
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. }
  7886. #endif
  7887. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7888. // Static file compression is opt-in, so these run their own server rather than
  7889. // flipping it on for the shared ServerTest fixture, which would silently
  7890. // rewrite what every other static file test is asserting.
  7891. class StaticFileCompressionTest : public ::testing::Test {
  7892. protected:
  7893. void TearDown() override {
  7894. if (t_.joinable()) {
  7895. svr_.stop();
  7896. t_.join();
  7897. }
  7898. }
  7899. int start(const std::function<void(Server &)> &configure = nullptr) {
  7900. // Serves the same tree as a directory of build-time compressed assets
  7901. // would be served: the mount point names the coding the files are already
  7902. // stored in. Registered before "/" so it is the one that matches.
  7903. svr_.set_mount_point("/pre-encoded", "./www",
  7904. {{"Content-Encoding", "gzip"}});
  7905. svr_.set_mount_point("/", "./www");
  7906. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7907. res.set_file_content("./www/dir/index.html", "text/html");
  7908. });
  7909. svr_.Get("/pre-encoded-file-content",
  7910. [](const Request & /*req*/, Response &res) {
  7911. res.set_header("Content-Encoding", "gzip");
  7912. res.set_file_content("./www/dir/index.html", "text/html");
  7913. });
  7914. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7915. res.set_content_provider(
  7916. 6, "text/plain",
  7917. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7918. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7919. return true;
  7920. });
  7921. });
  7922. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7923. res.set_content_provider(
  7924. 1000, "text/plain",
  7925. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7926. if (offset < 100) {
  7927. std::string data(100, 'A');
  7928. sink.write(data.data(), data.size());
  7929. return true;
  7930. }
  7931. std::this_thread::sleep_for(std::chrono::seconds(2));
  7932. std::string data(900, 'B');
  7933. sink.write(data.data(), data.size());
  7934. return true;
  7935. });
  7936. });
  7937. if (configure) { configure(svr_); }
  7938. auto port = svr_.bind_to_any_port(HOST);
  7939. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7940. svr_.wait_until_ready();
  7941. return port;
  7942. }
  7943. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7944. // Every file under ./www except 1MB.txt is smaller than the default
  7945. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7946. // it out of the way.
  7947. static void enable_without_floor(Server &svr) {
  7948. svr.set_static_file_compression(true);
  7949. svr.set_static_file_compression_min_length(0);
  7950. }
  7951. Server svr_;
  7952. std::thread t_;
  7953. };
  7954. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7955. auto port = start();
  7956. Client cli(HOST, port);
  7957. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7961. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7962. EXPECT_EQ(1048576U, res->body.size());
  7963. }
  7964. TEST_F(StaticFileCompressionTest, MountPoint) {
  7965. auto port = start(enable);
  7966. Client cli(HOST, port);
  7967. cli.set_decompress(false);
  7968. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. EXPECT_EQ(StatusCode::OK_200, res->status);
  7971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7972. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7973. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7974. // The response stays self-delimiting: a length, not a chunked body.
  7975. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7976. EXPECT_EQ(std::to_string(res->body.size()),
  7977. res->get_header_value("Content-Length"));
  7978. EXPECT_LT(res->body.size(), 1048576U);
  7979. EXPECT_FALSE(res->body.empty());
  7980. }
  7981. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7982. auto port = start(enable);
  7983. Client cli(HOST, port);
  7984. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7988. EXPECT_EQ(1048576U, res->body.size());
  7989. }
  7990. TEST_F(StaticFileCompressionTest, FileContent) {
  7991. auto port = start(enable_without_floor);
  7992. Client cli(HOST, port);
  7993. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7997. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7998. EXPECT_EQ(104U, res->body.size());
  7999. }
  8000. // A handler that serves an already-encoded file names the coding itself. The
  8001. // file-backed path decided its coding from Accept-Encoding and the content
  8002. // type alone, so it compressed the stored bytes a second time and appended a
  8003. // second Content-Encoding field line.
  8004. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8005. auto port = start(enable_without_floor);
  8006. Client cli(HOST, port);
  8007. cli.set_decompress(false);
  8008. auto res = cli.Get("/pre-encoded-file-content",
  8009. Headers{{"Accept-Encoding", "gzip"}});
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_EQ(StatusCode::OK_200, res->status);
  8012. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8014. // Vary belongs to a coding the server chose, and it chose none here.
  8015. EXPECT_FALSE(res->has_header("Vary"));
  8016. // The file travels exactly as it is stored on disk.
  8017. EXPECT_EQ(104U, res->body.size());
  8018. }
  8019. // The 1MB file clears the default floor, so this one runs the configuration a
  8020. // deployment would actually have.
  8021. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8022. auto port = start(enable);
  8023. Client cli(HOST, port);
  8024. cli.set_decompress(false);
  8025. auto res =
  8026. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. EXPECT_EQ(StatusCode::OK_200, res->status);
  8029. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8030. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8031. EXPECT_FALSE(res->has_header("Vary"));
  8032. EXPECT_EQ(1048576U, res->body.size());
  8033. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8034. }
  8035. TEST_F(StaticFileCompressionTest, Head) {
  8036. auto port = start(enable);
  8037. Client cli(HOST, port);
  8038. cli.set_decompress(false);
  8039. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8040. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8041. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8045. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8046. // HEAD still reports the size a GET would return.
  8047. EXPECT_EQ(get->get_header_value("Content-Length"),
  8048. res->get_header_value("Content-Length"));
  8049. EXPECT_TRUE(res->body.empty());
  8050. }
  8051. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8052. auto port = start(enable);
  8053. Client cli(HOST, port);
  8054. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8055. {"Accept-Encoding", "gzip"}});
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8058. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8059. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8060. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8061. EXPECT_EQ("cd", res->body);
  8062. }
  8063. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8064. auto port = start(enable);
  8065. Client cli(HOST, port);
  8066. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8068. EXPECT_EQ(StatusCode::OK_200, res->status);
  8069. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8070. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8071. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8072. }
  8073. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8074. auto port = start(enable);
  8075. Client cli(HOST, port);
  8076. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8078. EXPECT_EQ(StatusCode::OK_200, res->status);
  8079. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8081. EXPECT_TRUE(res->body.empty());
  8082. }
  8083. TEST_F(StaticFileCompressionTest, MinLength) {
  8084. auto port = start(enable);
  8085. Client cli(HOST, port);
  8086. // 104 bytes, well under the default floor. Compressing it would add the
  8087. // gzip header and trailer to a body that already fits in one packet.
  8088. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8092. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8093. }
  8094. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8095. auto port = start([](Server &svr) {
  8096. svr.set_static_file_compression(true);
  8097. svr.set_static_file_compression_min_length(1);
  8098. });
  8099. Client cli(HOST, port);
  8100. cli.set_decompress(false);
  8101. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8104. // A 9-byte file comes back larger than it went in, because gzip's header and
  8105. // trailer outweigh anything deflate can save. That is the end of the range
  8106. // the floor exists to keep out.
  8107. EXPECT_GT(res->body.size(), 9U);
  8108. }
  8109. TEST_F(StaticFileCompressionTest, MaxLength) {
  8110. auto port = start([](Server &svr) {
  8111. svr.set_static_file_compression(true);
  8112. svr.set_static_file_compression_min_length(0);
  8113. svr.set_static_file_compression_max_length(1024);
  8114. });
  8115. Client cli(HOST, port);
  8116. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8117. // defines `small` as a macro on Windows.
  8118. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8119. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8120. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8121. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8122. // Under it: compressed.
  8123. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8124. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8125. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8126. }
  8127. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8128. auto port = start(enable_without_floor);
  8129. Client cli(HOST, port);
  8130. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8131. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8132. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8133. auto identity_etag = identity->get_header_value("ETag");
  8134. ASSERT_FALSE(identity_etag.empty());
  8135. auto gzipped =
  8136. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8137. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8138. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8139. auto gzip_etag = gzipped->get_header_value("ETag");
  8140. ASSERT_FALSE(gzip_etag.empty());
  8141. // Two representations, two validators.
  8142. EXPECT_NE(identity_etag, gzip_etag);
  8143. // Each one revalidates against the request that would produce it...
  8144. auto fresh =
  8145. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8146. {"If-None-Match", gzip_etag}});
  8147. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8148. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8149. auto fresh_identity =
  8150. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8151. {"If-None-Match", identity_etag}});
  8152. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8153. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8154. // ...and not against the other representation.
  8155. auto crossed =
  8156. cli.Get("/dir/index.html",
  8157. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8158. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8159. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8160. }
  8161. // The opt-in covers responses the server reads off disk itself. A caller's own
  8162. // known-length provider keeps its Content-Length and, more importantly, keeps
  8163. // delivering incrementally: routing it through a compressor would hold every
  8164. // write back until zlib's window filled.
  8165. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8166. auto port = start(enable);
  8167. Client cli(HOST, port);
  8168. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8172. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8173. EXPECT_EQ("aaabbb", res->body);
  8174. }
  8175. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8176. auto port = start(enable);
  8177. Client cli(HOST, port);
  8178. cli.set_read_timeout(1, 0);
  8179. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8180. Headers{{"Accept-Encoding", "gzip"}});
  8181. ASSERT_TRUE(handle.is_valid());
  8182. // The provider writes 100 bytes and then stalls for longer than the read
  8183. // timeout. Those first bytes have to arrive anyway: run the response through
  8184. // a compressor and zlib holds them until its window fills, so the read would
  8185. // come back empty instead.
  8186. char buf[256];
  8187. auto n = handle.read(buf, sizeof(buf));
  8188. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8189. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8190. }
  8191. #endif
  8192. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8193. TEST_F(ServerTest, Brotli) {
  8194. Headers headers;
  8195. headers.emplace("Accept-Encoding", "br");
  8196. auto res = cli_.Get("/compress", headers);
  8197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8198. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8200. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8201. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8202. "7890123456789012345678901234567890",
  8203. res->body);
  8204. EXPECT_EQ(StatusCode::OK_200, res->status);
  8205. }
  8206. #endif
  8207. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8208. TEST_F(ServerTest, Zstd) {
  8209. Headers headers;
  8210. headers.emplace("Accept-Encoding", "zstd");
  8211. auto res = cli_.Get("/compress", headers);
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8214. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8215. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8216. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8217. "7890123456789012345678901234567890",
  8218. res->body);
  8219. EXPECT_EQ(StatusCode::OK_200, res->status);
  8220. }
  8221. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8222. Headers headers;
  8223. headers.emplace("Accept-Encoding", "");
  8224. auto res = cli_.Get("/compress", headers);
  8225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8226. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8228. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8230. "7890123456789012345678901234567890",
  8231. res->body);
  8232. EXPECT_EQ(StatusCode::OK_200, res->status);
  8233. }
  8234. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8235. Headers headers;
  8236. headers.emplace("Accept-Encoding", "zstd");
  8237. std::string body;
  8238. auto res = cli_.Get("/compress", headers,
  8239. [&](const char *data, uint64_t data_length) {
  8240. EXPECT_EQ(100U, data_length);
  8241. body.append(data, data_length);
  8242. return true;
  8243. });
  8244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8245. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8246. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8247. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8248. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8249. "7890123456789012345678901234567890",
  8250. body);
  8251. EXPECT_EQ(StatusCode::OK_200, res->status);
  8252. }
  8253. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8254. Headers headers;
  8255. headers.emplace("Accept-Encoding", "zstd");
  8256. cli_.set_decompress(false);
  8257. auto res = cli_.Get("/compress", headers);
  8258. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8259. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8260. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8261. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8263. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8264. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8265. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8266. EXPECT_EQ(StatusCode::OK_200, res->status);
  8267. ASSERT_EQ(26U, res->body.size());
  8268. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8269. 0);
  8270. }
  8271. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8272. Headers headers;
  8273. headers.emplace("Accept-Encoding", "");
  8274. std::string body;
  8275. auto res = cli_.Get("/compress", headers,
  8276. [&](const char *data, uint64_t data_length) {
  8277. EXPECT_EQ(100U, data_length);
  8278. body.append(data, data_length);
  8279. return true;
  8280. });
  8281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8282. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8284. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8285. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8286. "7890123456789012345678901234567890",
  8287. body);
  8288. EXPECT_EQ(StatusCode::OK_200, res->status);
  8289. }
  8290. TEST_F(ServerTest, NoZstd) {
  8291. Headers headers;
  8292. headers.emplace("Accept-Encoding", "zstd");
  8293. auto res = cli_.Get("/nocompress", headers);
  8294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8295. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8296. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8297. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8299. "7890123456789012345678901234567890",
  8300. res->body);
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. }
  8303. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8304. Headers headers;
  8305. headers.emplace("Accept-Encoding", "zstd");
  8306. std::string body;
  8307. auto res = cli_.Get("/nocompress", headers,
  8308. [&](const char *data, uint64_t data_length) {
  8309. EXPECT_EQ(100U, data_length);
  8310. body.append(data, data_length);
  8311. return true;
  8312. });
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8315. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8316. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8317. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8318. "7890123456789012345678901234567890",
  8319. body);
  8320. EXPECT_EQ(StatusCode::OK_200, res->status);
  8321. }
  8322. // TODO: How to enable zstd ??
  8323. TEST_F(ServerTest, MultipartFormDataZstd) {
  8324. UploadFormDataItems items = {
  8325. {"key1", "test", "", ""},
  8326. {"key2", "--abcdefg123", "", ""},
  8327. };
  8328. Headers headers;
  8329. headers.emplace("Accept-Encoding", "zstd");
  8330. cli_.set_compress(true);
  8331. auto res = cli_.Post("/compress-multipart", headers, items);
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. }
  8335. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8336. Headers headers;
  8337. headers.emplace("Accept-Encoding", "zstd");
  8338. cli_.set_compress(true);
  8339. auto res = cli_.Put(
  8340. "/put", headers, 3,
  8341. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8342. sink.os << "PUT";
  8343. return true;
  8344. },
  8345. "text/plain");
  8346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8347. EXPECT_EQ(StatusCode::OK_200, res->status);
  8348. EXPECT_EQ("PUT", res->body);
  8349. }
  8350. // Pre-compression logging tests
  8351. TEST_F(ServerTest, PreCompressionLogging) {
  8352. // Test data for compression (matches the actual /compress endpoint content)
  8353. const std::string test_content =
  8354. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8355. "3456789012345678901234567890";
  8356. // Variables to capture logging data
  8357. std::string pre_compression_body;
  8358. std::string pre_compression_content_type;
  8359. std::string pre_compression_content_encoding;
  8360. std::string post_compression_body;
  8361. std::string post_compression_content_type;
  8362. std::string post_compression_content_encoding;
  8363. // Set up pre-compression logger
  8364. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8365. const Response &res) {
  8366. pre_compression_body = res.body;
  8367. pre_compression_content_type = res.get_header_value("Content-Type");
  8368. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8369. });
  8370. // Set up post-compression logger
  8371. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8372. post_compression_body = res.body;
  8373. post_compression_content_type = res.get_header_value("Content-Type");
  8374. post_compression_content_encoding =
  8375. res.get_header_value("Content-Encoding");
  8376. });
  8377. // Test with gzip compression
  8378. Headers headers;
  8379. headers.emplace("Accept-Encoding", "gzip");
  8380. auto res = cli_.Get("/compress", headers);
  8381. // Verify response was compressed
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8385. // Verify pre-compression logger captured uncompressed content
  8386. EXPECT_EQ(test_content, pre_compression_body);
  8387. EXPECT_EQ("text/plain", pre_compression_content_type);
  8388. EXPECT_TRUE(pre_compression_content_encoding
  8389. .empty()); // No encoding header before compression
  8390. // Verify post-compression logger captured compressed content
  8391. EXPECT_NE(test_content,
  8392. post_compression_body); // Should be different after compression
  8393. EXPECT_EQ("text/plain", post_compression_content_type);
  8394. EXPECT_EQ("gzip", post_compression_content_encoding);
  8395. // Verify compressed content is smaller
  8396. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8397. }
  8398. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8399. const std::string test_content =
  8400. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8401. "3456789012345678901234567890";
  8402. std::string pre_compression_body;
  8403. std::string post_compression_body;
  8404. svr_.set_pre_compression_logger(
  8405. [&](const Request & /*req*/, const Response &res) {
  8406. pre_compression_body = res.body;
  8407. });
  8408. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8409. post_compression_body = res.body;
  8410. });
  8411. Headers headers;
  8412. headers.emplace("Accept-Encoding", "br");
  8413. auto res = cli_.Get("/compress", headers);
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::OK_200, res->status);
  8416. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8417. // Verify pre-compression content is uncompressed
  8418. EXPECT_EQ(test_content, pre_compression_body);
  8419. // Verify post-compression content is compressed
  8420. EXPECT_NE(test_content, post_compression_body);
  8421. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8422. }
  8423. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8424. const std::string test_content =
  8425. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8426. "3456789012345678901234567890";
  8427. std::string pre_compression_body;
  8428. std::string post_compression_body;
  8429. svr_.set_pre_compression_logger(
  8430. [&](const Request & /*req*/, const Response &res) {
  8431. pre_compression_body = res.body;
  8432. });
  8433. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8434. post_compression_body = res.body;
  8435. });
  8436. // Request without compression (use /nocompress endpoint)
  8437. Headers headers;
  8438. auto res = cli_.Get("/nocompress", headers);
  8439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8442. // Pre-compression logger should not be called when no compression is applied
  8443. EXPECT_TRUE(
  8444. pre_compression_body.empty()); // Pre-compression logger not called
  8445. EXPECT_EQ(
  8446. test_content,
  8447. post_compression_body); // Post-compression logger captures final content
  8448. }
  8449. TEST_F(ServerTest, LoggerSeesContentLength) {
  8450. size_t logged_content_length = 0;
  8451. std::string logged_content_length_header;
  8452. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8453. logged_content_length = res.content_length_;
  8454. logged_content_length_header = res.get_header_value("Content-Length");
  8455. });
  8456. auto res = cli_.Get("/nocompress");
  8457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8458. EXPECT_EQ(StatusCode::OK_200, res->status);
  8459. EXPECT_EQ(res->body.size(), logged_content_length);
  8460. EXPECT_EQ(std::to_string(logged_content_length),
  8461. logged_content_length_header);
  8462. }
  8463. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8464. const std::string test_content =
  8465. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8466. "3456789012345678901234567890";
  8467. std::string pre_compression_body;
  8468. bool pre_logger_called = false;
  8469. // Set only pre-compression logger
  8470. svr_.set_pre_compression_logger(
  8471. [&](const Request & /*req*/, const Response &res) {
  8472. pre_compression_body = res.body;
  8473. pre_logger_called = true;
  8474. });
  8475. Headers headers;
  8476. headers.emplace("Accept-Encoding", "gzip");
  8477. auto res = cli_.Get("/compress", headers);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8481. // Verify pre-compression logger was called
  8482. EXPECT_TRUE(pre_logger_called);
  8483. EXPECT_EQ(test_content, pre_compression_body);
  8484. }
  8485. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8486. {
  8487. // Test with Expect: 100-continue header - success case
  8488. // Server returns 100 Continue, client sends body, server returns 200 OK
  8489. Request req;
  8490. req.method = "POST";
  8491. req.path = "/post-large";
  8492. req.set_header("Expect", "100-continue");
  8493. req.body = LARGE_DATA;
  8494. Response res;
  8495. auto error = Error::Success;
  8496. cli_.set_keep_alive(true);
  8497. auto ret = cli_.send(req, res, error);
  8498. EXPECT_TRUE(ret);
  8499. EXPECT_EQ(StatusCode::OK_200, res.status);
  8500. EXPECT_EQ(LARGE_DATA, res.body);
  8501. }
  8502. {
  8503. // Test with Expect: 100-continue header - error case
  8504. // Client should not send the body when server returns an error
  8505. Request req;
  8506. req.method = "POST";
  8507. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8508. req.set_header("Expect", "100-continue");
  8509. req.body = LARGE_DATA;
  8510. Response res;
  8511. auto error = Error::Success;
  8512. auto start = std::chrono::high_resolution_clock::now();
  8513. cli_.set_keep_alive(true);
  8514. auto ret = cli_.send(req, res, error);
  8515. auto end = std::chrono::high_resolution_clock::now();
  8516. auto elapsed =
  8517. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8518. .count();
  8519. // With Expect: 100-continue, request completes successfully but with error
  8520. EXPECT_TRUE(ret);
  8521. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8522. EXPECT_EQ("close", res.get_header_value("Connection"));
  8523. EXPECT_FALSE(cli_.is_socket_open());
  8524. EXPECT_LE(elapsed, 2000);
  8525. }
  8526. {
  8527. // Send an extra GET request to ensure error recovery without hanging
  8528. Request req;
  8529. req.method = "GET";
  8530. req.path = "/hi";
  8531. auto start = std::chrono::high_resolution_clock::now();
  8532. auto res = cli_.send(req);
  8533. auto end = std::chrono::high_resolution_clock::now();
  8534. auto elapsed =
  8535. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8536. .count();
  8537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8538. EXPECT_EQ(StatusCode::OK_200, res->status);
  8539. EXPECT_EQ("Hello World!", res->body);
  8540. EXPECT_LE(elapsed, 500);
  8541. }
  8542. }
  8543. TEST(ZstdDecompressor, ChunkedDecompression) {
  8544. std::string data;
  8545. for (size_t i = 0; i < 32 * 1024; ++i) {
  8546. data.push_back(static_cast<char>('a' + i % 26));
  8547. }
  8548. std::string compressed_data;
  8549. {
  8550. httplib::detail::zstd_compressor compressor;
  8551. bool result = compressor.compress(
  8552. data.data(), data.size(),
  8553. /*last=*/true,
  8554. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8555. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8556. compressed_data_size);
  8557. return true;
  8558. });
  8559. ASSERT_TRUE(result);
  8560. }
  8561. std::string decompressed_data;
  8562. {
  8563. httplib::detail::zstd_decompressor decompressor;
  8564. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8565. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8566. size_t chunk_size = 130;
  8567. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8568. chunk_begin += chunk_size) {
  8569. size_t current_chunk_size =
  8570. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8571. bool result = decompressor.decompress(
  8572. compressed_data.data() + chunk_begin, current_chunk_size,
  8573. [&](const char *decompressed_data_chunk,
  8574. size_t decompressed_data_chunk_size) {
  8575. decompressed_data.insert(decompressed_data.size(),
  8576. decompressed_data_chunk,
  8577. decompressed_data_chunk_size);
  8578. return true;
  8579. });
  8580. ASSERT_TRUE(result);
  8581. }
  8582. }
  8583. ASSERT_EQ(data, decompressed_data);
  8584. }
  8585. TEST(ZstdDecompressor, Decompress) {
  8586. std::string original_text = "Compressed with ZSTD";
  8587. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8588. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8589. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8590. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8591. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8592. std::string decompressed_data;
  8593. {
  8594. httplib::detail::zstd_decompressor decompressor;
  8595. bool result = decompressor.decompress(
  8596. compressed_data.data(), compressed_data.size(),
  8597. [&](const char *decompressed_data_chunk,
  8598. size_t decompressed_data_chunk_size) {
  8599. decompressed_data.insert(decompressed_data.size(),
  8600. decompressed_data_chunk,
  8601. decompressed_data_chunk_size);
  8602. return true;
  8603. });
  8604. ASSERT_TRUE(result);
  8605. }
  8606. ASSERT_EQ(original_text, decompressed_data);
  8607. }
  8608. #endif
  8609. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8610. // separate chunks so that the server sees each part in its own read(). Used to
  8611. // place a read boundary at a specific offset of a request body.
  8612. static bool send_request_in_parts(time_t read_timeout_sec,
  8613. const std::vector<std::string> &parts,
  8614. std::string *resp = nullptr,
  8615. int port = PORT) {
  8616. auto error = Error::Success;
  8617. auto client_sock = detail::create_client_socket(
  8618. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8619. /*connection_timeout_sec=*/5, 0,
  8620. /*read_timeout_sec=*/5, 0,
  8621. /*write_timeout_sec=*/5, 0, std::string(), error);
  8622. if (client_sock == INVALID_SOCKET) { return false; }
  8623. auto ret = detail::process_client_socket(
  8624. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8625. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8626. for (size_t i = 0; i < parts.size(); i++) {
  8627. const auto &part = parts[i];
  8628. if (part.size() !=
  8629. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8630. return false;
  8631. }
  8632. if (i + 1 < parts.size()) {
  8633. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8634. }
  8635. }
  8636. char buf[512];
  8637. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8638. while (line_reader.getline()) {
  8639. if (resp) { *resp += line_reader.ptr(); }
  8640. }
  8641. return true;
  8642. });
  8643. detail::close_socket(client_sock);
  8644. return ret;
  8645. }
  8646. // Sends a raw request to a server listening at HOST:PORT.
  8647. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8648. std::string *resp = nullptr, int port = PORT) {
  8649. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8650. }
  8651. #ifdef CPPHTTPLIB_SSL_ENABLED
  8652. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8653. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8654. ASSERT_TRUE(svr.is_valid());
  8655. svr.set_read_timeout(1, 0);
  8656. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8657. auto se = detail::scope_exit([&] {
  8658. svr.stop();
  8659. t.join();
  8660. ASSERT_FALSE(svr.is_running());
  8661. });
  8662. svr.wait_until_ready();
  8663. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8664. // keeps each wait well within the read timeout. The server gives up a
  8665. // second in, so the bytes sent after that fail.
  8666. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8667. parts.resize(26, std::string(1, '\0'));
  8668. EXPECT_FALSE(send_request_in_parts(5, parts));
  8669. }
  8670. #endif
  8671. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8672. Server svr;
  8673. std::string header_value;
  8674. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8675. header_value = req.get_header_value("foo");
  8676. res.set_content("ok", "text/plain");
  8677. });
  8678. thread t = thread([&] { svr.listen(HOST, PORT); });
  8679. auto se = detail::scope_exit([&] {
  8680. svr.stop();
  8681. t.join();
  8682. ASSERT_FALSE(svr.is_running());
  8683. });
  8684. svr.wait_until_ready();
  8685. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8686. // like characters are not treated the same - use vertical tab and escape.
  8687. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8688. "foo: \t \v bar \x1B\t \r\n"
  8689. "Connection: close\r\n"
  8690. "\r\n";
  8691. std::string res;
  8692. ASSERT_TRUE(send_request(5, req, &res));
  8693. EXPECT_EQ(header_value, "");
  8694. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8695. }
  8696. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8697. Server svr;
  8698. std::string received;
  8699. svr.Get("/order", [&](const Request &req, Response &res) {
  8700. received = entries_to_string(req.headers);
  8701. res.set_content("ok", "text/plain");
  8702. });
  8703. auto port = svr.bind_to_any_port(HOST);
  8704. thread t = thread([&] { svr.listen_after_bind(); });
  8705. auto se = detail::scope_exit([&] {
  8706. svr.stop();
  8707. t.join();
  8708. ASSERT_FALSE(svr.is_running());
  8709. });
  8710. svr.wait_until_ready();
  8711. const std::string req = "GET /order HTTP/1.1\r\n"
  8712. "X-First: 1\r\n"
  8713. "X-Dup: a\r\n"
  8714. "X-Second: 2\r\n"
  8715. "X-Dup: b\r\n"
  8716. "Connection: close\r\n"
  8717. "\r\n";
  8718. std::string res;
  8719. ASSERT_TRUE(send_request(5, req, &res, port));
  8720. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8721. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8722. }
  8723. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8724. Server svr;
  8725. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8726. res.set_header("Set-Cookie", "first=1");
  8727. res.set_header("X-Between", "y");
  8728. res.set_header("Set-Cookie", "second=2");
  8729. res.set_content("ok", "text/plain");
  8730. });
  8731. auto port = svr.bind_to_any_port(HOST);
  8732. thread t = thread([&] { svr.listen_after_bind(); });
  8733. auto se = detail::scope_exit([&] {
  8734. svr.stop();
  8735. t.join();
  8736. ASSERT_FALSE(svr.is_running());
  8737. });
  8738. svr.wait_until_ready();
  8739. Client cli(HOST, port);
  8740. auto res = cli.Get("/cookies");
  8741. ASSERT_TRUE(res);
  8742. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8743. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8744. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8745. }
  8746. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8747. Server svr;
  8748. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8749. auto i = new int(0);
  8750. res.set_header("Trailer", "X-Safe, X-Reflected");
  8751. res.set_chunked_content_provider(
  8752. "text/plain",
  8753. [i](size_t /*offset*/, DataSink &sink) {
  8754. if (*i == 0) {
  8755. sink.os << "body";
  8756. } else {
  8757. Headers trailer;
  8758. // A valid trailer that must survive.
  8759. trailer.emplace("X-Safe", "safe");
  8760. // Attacker-controlled value carrying CR/LF (response splitting).
  8761. trailer.emplace("X-Reflected",
  8762. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8763. // Attacker-controlled name carrying CR/LF.
  8764. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8765. sink.done_with_trailer(trailer);
  8766. }
  8767. (*i)++;
  8768. return true;
  8769. },
  8770. [i](bool /*success*/) { delete i; });
  8771. });
  8772. thread t = thread([&] { svr.listen(HOST, PORT); });
  8773. auto se = detail::scope_exit([&] {
  8774. svr.stop();
  8775. t.join();
  8776. ASSERT_FALSE(svr.is_running());
  8777. });
  8778. svr.wait_until_ready();
  8779. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8780. "Host: " + HOST +
  8781. "\r\n"
  8782. "Connection: close\r\n"
  8783. "\r\n";
  8784. std::string res;
  8785. ASSERT_TRUE(send_request(5, req, &res));
  8786. // The injected fields must not appear anywhere in the raw response.
  8787. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8788. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8789. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8790. // Invalid trailers are dropped entirely, matching set_header().
  8791. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8792. // The valid trailer still passes through.
  8793. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8794. }
  8795. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8796. Server svr;
  8797. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8798. // res.headers is a public field an application can populate directly,
  8799. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8800. // A valid header that must survive.
  8801. res.headers.emplace("X-Safe", "safe");
  8802. // Attacker-controlled value carrying CR/LF (response splitting).
  8803. res.headers.emplace("X-Reflected",
  8804. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8805. // Attacker-controlled name carrying CR/LF.
  8806. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8807. res.set_content("body", "text/plain");
  8808. });
  8809. thread t = thread([&] { svr.listen(HOST, PORT); });
  8810. auto se = detail::scope_exit([&] {
  8811. svr.stop();
  8812. t.join();
  8813. ASSERT_FALSE(svr.is_running());
  8814. });
  8815. svr.wait_until_ready();
  8816. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8817. "Host: " + HOST +
  8818. "\r\n"
  8819. "Connection: close\r\n"
  8820. "\r\n";
  8821. std::string res;
  8822. ASSERT_TRUE(send_request(5, req, &res));
  8823. // The injected fields must not appear anywhere in the raw response.
  8824. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8825. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8826. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8827. // Invalid headers are dropped entirely, matching set_header().
  8828. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8829. // The valid header still passes through.
  8830. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8831. }
  8832. // Forward declaration: in split builds split.py strips `inline` and moves the
  8833. // definition into httplib.cc, so detail::write_request_line is not visible from
  8834. // the public httplib.h. Re-declaring it here lets the tests link against the
  8835. // symbol in both header-only and split builds.
  8836. namespace httplib {
  8837. namespace detail {
  8838. ssize_t write_request_line(Stream &strm, const std::string &method,
  8839. const std::string &path);
  8840. } // namespace detail
  8841. } // namespace httplib
  8842. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8843. // A well-formed target is written verbatim.
  8844. {
  8845. detail::BufferStream strm;
  8846. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8847. EXPECT_GT(n, 0);
  8848. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8849. }
  8850. // A target carrying CR/LF, SP or other control octets must be rejected
  8851. // before anything reaches the wire, otherwise it splits the request line and
  8852. // injects a header or a whole request.
  8853. const std::string evil_targets[] = {
  8854. "/a\r\nInjected: pwned",
  8855. "/a\rInjected",
  8856. "/a\nInjected",
  8857. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8858. "/a b",
  8859. "/a\tb",
  8860. "/a\x7f",
  8861. };
  8862. for (const auto &evil : evil_targets) {
  8863. detail::BufferStream strm;
  8864. auto n = detail::write_request_line(strm, "GET", evil);
  8865. EXPECT_LT(n, 0);
  8866. EXPECT_TRUE(strm.get_buffer().empty());
  8867. }
  8868. }
  8869. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8870. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8871. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8872. // target reaches write_request. The client must fail cleanly with
  8873. // Error::Write instead of putting a request-line-less, header-injecting
  8874. // request on the wire.
  8875. Server svr;
  8876. svr.Get("/a", [](const Request &, Response &res) {
  8877. res.set_content("ok", "text/plain");
  8878. });
  8879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8880. auto se = detail::scope_exit([&] {
  8881. svr.stop();
  8882. thread.join();
  8883. ASSERT_FALSE(svr.is_running());
  8884. });
  8885. svr.wait_until_ready();
  8886. {
  8887. Client cli(HOST, PORT);
  8888. cli.set_path_encode(false);
  8889. // The request is rejected before anything is written, so the connection
  8890. // stays silent and the subsequent response read would otherwise block for
  8891. // the full default read timeout. Shorten it -- the assertion is on the
  8892. // error, not the timeout.
  8893. cli.set_read_timeout(1, 0);
  8894. auto res = cli.Get("/a\r\nInjected: pwned");
  8895. EXPECT_FALSE(res);
  8896. EXPECT_EQ(Error::Write, res.error());
  8897. }
  8898. }
  8899. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8900. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8901. // including extension methods.
  8902. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8903. for (const auto &method : good_methods) {
  8904. detail::BufferStream strm;
  8905. auto n = detail::write_request_line(strm, method, "/");
  8906. EXPECT_GT(n, 0);
  8907. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8908. }
  8909. // A method carrying CR/LF would split the request line and smuggle a whole
  8910. // request ahead of the real one. A space or an empty method corrupts the
  8911. // request line. All must be rejected before anything reaches the wire.
  8912. const std::string evil_methods[] = {
  8913. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8914. "GET\r\nInjected: pwned",
  8915. "GET\r",
  8916. "GET\n",
  8917. "GE T",
  8918. "",
  8919. };
  8920. for (const auto &evil : evil_methods) {
  8921. detail::BufferStream strm;
  8922. auto n = detail::write_request_line(strm, evil, "/");
  8923. EXPECT_LT(n, 0);
  8924. EXPECT_TRUE(strm.get_buffer().empty());
  8925. }
  8926. }
  8927. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8928. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8929. // through Client::send must fail with Error::Write and no request, neither
  8930. // the smuggled one nor the real one, may reach the server.
  8931. Server svr;
  8932. std::atomic<int> request_count(0);
  8933. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8934. request_count++;
  8935. res.status = StatusCode::OK_200;
  8936. return Server::HandlerResponse::Handled;
  8937. });
  8938. auto port = svr.bind_to_any_port(HOST);
  8939. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8940. auto se = detail::scope_exit([&] {
  8941. svr.stop();
  8942. thread.join();
  8943. ASSERT_FALSE(svr.is_running());
  8944. });
  8945. svr.wait_until_ready();
  8946. {
  8947. Client cli(HOST, port);
  8948. const std::string evil_methods[] = {
  8949. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8950. "GE T",
  8951. "",
  8952. };
  8953. for (const auto &evil : evil_methods) {
  8954. Request req;
  8955. req.method = evil;
  8956. req.path = "/";
  8957. auto res = cli.send(req);
  8958. EXPECT_FALSE(res);
  8959. EXPECT_EQ(Error::Write, res.error());
  8960. }
  8961. auto handle =
  8962. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8963. EXPECT_FALSE(handle.is_valid());
  8964. EXPECT_EQ(Error::Write, handle.error);
  8965. // A valid request on the same client still goes through.
  8966. auto res = cli.Get("/");
  8967. ASSERT_TRUE(res);
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. }
  8970. EXPECT_EQ(1, request_count.load());
  8971. }
  8972. // Sends a raw request and verifies that there isn't a crash or exception.
  8973. static void test_raw_request(const std::string &req,
  8974. std::string *out = nullptr) {
  8975. Server svr;
  8976. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8977. res.set_content("ok", "text/plain");
  8978. });
  8979. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8980. res.set_content("ok", "text/plain");
  8981. });
  8982. svr.Get("/header_field_value_check",
  8983. [&](const Request & /*req*/, Response &res) {
  8984. res.set_content("ok", "text/plain");
  8985. });
  8986. svr.CustomRoute("PROPFIND", "/dav",
  8987. [&](const Request & /*req*/, Response &res) {
  8988. res.status = StatusCode::MultiStatus_207;
  8989. });
  8990. // Server read timeout must be longer than the client read timeout for the
  8991. // bug to reproduce, probably to force the server to process a request
  8992. // without a trailing blank line.
  8993. const time_t client_read_timeout_sec = 1;
  8994. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8995. bool listen_thread_ok = false;
  8996. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8997. auto se = detail::scope_exit([&] {
  8998. svr.stop();
  8999. t.join();
  9000. ASSERT_FALSE(svr.is_running());
  9001. EXPECT_TRUE(listen_thread_ok);
  9002. });
  9003. svr.wait_until_ready();
  9004. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9005. }
  9006. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9007. // A certain header line causes an exception if the header property is parsed
  9008. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9009. test_raw_request(
  9010. "GET /hi HTTP/1.1\r\n"
  9011. " : "
  9012. " "
  9013. " ");
  9014. }
  9015. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9016. // A certain header line causes an exception if the header property *name* is
  9017. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9018. // greedy matcher and requires backtracking when there are a lot of ":"
  9019. // characters.
  9020. // This occurs with libc++ but not libstdc++.
  9021. test_raw_request(
  9022. "GET /hi HTTP/1.1\r\n"
  9023. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9024. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9025. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9026. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9027. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9028. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9029. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9030. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9031. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9032. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9033. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9034. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9035. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9036. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9037. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9038. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9039. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9040. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9041. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9042. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9043. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9044. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9045. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9046. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9047. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9048. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9049. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9050. "&&&%%%");
  9051. }
  9052. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9053. // Make sure this doesn't crash the server.
  9054. // In a previous version of the header line regex, the "\r" rendered the line
  9055. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9056. // a new position where the leading white space ended and the field value
  9057. // began.
  9058. // The crash occurs with libc++ but not libstdc++.
  9059. test_raw_request("GET /hi HTTP/1.1\r\n"
  9060. "a:" +
  9061. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9062. "\r\n"
  9063. "\r\n");
  9064. }
  9065. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9066. std::string out;
  9067. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9068. "Content-Type: text/plain\r\n"
  9069. "Transfer-Encoding: chunked\r\n"
  9070. "\r\n"
  9071. "nothex\r\n",
  9072. &out);
  9073. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9074. }
  9075. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9076. std::string out;
  9077. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9078. "Content-Type: text/plain\r\n"
  9079. "Transfer-Encoding: chunked\r\n"
  9080. "\r\n"
  9081. "3\r\n"
  9082. "xyz\r\n"
  9083. "NaN\r\n",
  9084. &out);
  9085. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9086. }
  9087. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9088. std::string out;
  9089. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9090. "Content-Type: text/plain\r\n"
  9091. "Transfer-Encoding: chunked\r\n"
  9092. "\r\n"
  9093. // Length is too large for 64 bits.
  9094. "1ffffffffffffffff\r\n"
  9095. "xyz\r\n",
  9096. &out);
  9097. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9098. }
  9099. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9100. test_raw_request("GET /hi HTTP/1.1\r\n"
  9101. "Content-Type: text/plain\r\n\r");
  9102. }
  9103. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9104. std::string out;
  9105. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9106. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9107. }
  9108. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9109. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9110. std::string out;
  9111. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9112. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9113. }
  9114. }
  9115. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9116. std::string out;
  9117. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9118. "Connection: close\r\n\r\n",
  9119. &out);
  9120. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9121. }
  9122. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9123. Server svr;
  9124. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9125. EXPECT_TRUE(!req.remote_addr.empty());
  9126. });
  9127. thread t = thread([&] { svr.listen(HOST, PORT); });
  9128. auto se = detail::scope_exit([&] {
  9129. svr.stop();
  9130. t.join();
  9131. ASSERT_FALSE(svr.is_running());
  9132. });
  9133. svr.wait_until_ready();
  9134. // Send an invalid request line to trigger Bad Request
  9135. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9136. std::string out;
  9137. ASSERT_TRUE(send_request(5, bad_req, &out));
  9138. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9139. }
  9140. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9141. // answered right away rather than blocking on a read that waits for EOF.
  9142. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9143. std::string out;
  9144. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9145. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9146. }
  9147. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9148. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9149. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9150. for (const auto *method : methods) {
  9151. Server svr;
  9152. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9153. EXPECT_FALSE(svr.is_valid()) << method;
  9154. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9155. }
  9156. }
  9157. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9158. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9159. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9160. for (const auto *method : methods) {
  9161. Server svr;
  9162. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9163. EXPECT_FALSE(svr.is_valid()) << method;
  9164. }
  9165. }
  9166. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9167. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9168. "COPY", "MOVE", "LOCK",
  9169. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9170. Server svr;
  9171. for (const auto *method : methods) {
  9172. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9173. }
  9174. EXPECT_TRUE(svr.is_valid());
  9175. }
  9176. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9177. Server svr;
  9178. svr.CustomRoute("POST", "/x",
  9179. [](const Request &, Response &, const ContentReader &) {});
  9180. EXPECT_FALSE(svr.is_valid());
  9181. }
  9182. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9183. Server svr;
  9184. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9185. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9186. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9187. EXPECT_FALSE(svr.is_valid());
  9188. }
  9189. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9190. Server svr;
  9191. auto captured = Error::Success;
  9192. svr.set_error_logger(
  9193. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9194. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9195. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9196. }
  9197. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9198. std::string out;
  9199. std::string request(
  9200. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9201. test_raw_request(request, &out);
  9202. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9203. }
  9204. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9205. std::string out;
  9206. std::string request(
  9207. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9208. test_raw_request(request, &out);
  9209. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9210. }
  9211. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9212. std::string out;
  9213. std::string request(
  9214. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9215. test_raw_request(request, &out);
  9216. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9217. }
  9218. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9219. std::string out;
  9220. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9221. "Test: \r\n\r\n",
  9222. &out);
  9223. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9224. }
  9225. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9226. Server svr;
  9227. std::string x_custom;
  9228. std::string cookie;
  9229. std::string xff;
  9230. std::string x_unicode;
  9231. std::string x_iis;
  9232. svr.Get("/check", [&](const Request &req, Response &res) {
  9233. x_custom = req.get_header_value("X-Custom");
  9234. cookie = req.get_header_value("Cookie");
  9235. xff = req.get_header_value("X-Forwarded-For");
  9236. x_unicode = req.get_header_value("X-Unicode");
  9237. x_iis = req.get_header_value("X-IIS");
  9238. res.set_content("ok", "text/plain");
  9239. });
  9240. thread t = thread([&] { svr.listen(HOST, PORT); });
  9241. auto se = detail::scope_exit([&] {
  9242. svr.stop();
  9243. t.join();
  9244. ASSERT_FALSE(svr.is_running());
  9245. });
  9246. svr.wait_until_ready();
  9247. const std::string req = "GET /check HTTP/1.1\r\n"
  9248. "Host: localhost\r\n"
  9249. "X-Custom: a%0D%0AInjected: b\r\n"
  9250. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9251. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9252. "X-Unicode: %E3%81%82\r\n"
  9253. "X-IIS: %u00E9\r\n"
  9254. "Connection: close\r\n"
  9255. "\r\n";
  9256. std::string res;
  9257. ASSERT_TRUE(send_request(5, req, &res));
  9258. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9259. // Every value must be returned verbatim (wire form), with no decoding.
  9260. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9261. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9262. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9263. EXPECT_EQ("%E3%81%82", x_unicode);
  9264. EXPECT_EQ("%u00E9", x_iis);
  9265. }
  9266. // Applications that previously relied on automatic percent-decoding can
  9267. // reproduce the old behavior by explicitly calling decode_path_component()
  9268. // or, for RFC 3986 conformance, decode_uri_component().
  9269. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9270. Server svr;
  9271. std::string decoded;
  9272. svr.Get("/check", [&](const Request &req, Response &res) {
  9273. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9274. res.set_content("ok", "text/plain");
  9275. });
  9276. thread t = thread([&] { svr.listen(HOST, PORT); });
  9277. auto se = detail::scope_exit([&] {
  9278. svr.stop();
  9279. t.join();
  9280. ASSERT_FALSE(svr.is_running());
  9281. });
  9282. svr.wait_until_ready();
  9283. const std::string req = "GET /check HTTP/1.1\r\n"
  9284. "Host: localhost\r\n"
  9285. "X-Custom: hello%20world\r\n"
  9286. "Connection: close\r\n"
  9287. "\r\n";
  9288. std::string res;
  9289. ASSERT_TRUE(send_request(5, req, &res));
  9290. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9291. EXPECT_EQ("hello world", decoded);
  9292. }
  9293. // Regression test for #2033. Browsers send Referer values that include
  9294. // percent-encoded characters such as %0A inside the URL. Decoding the
  9295. // header value would either trip the post-decode CR/LF/NUL guard (the
  9296. // original bug, returning 400) or, after that guard was relaxed, silently
  9297. // store a literal LF — both unacceptable. The wire form must round-trip.
  9298. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9299. Server svr;
  9300. std::string referer;
  9301. svr.Get("/check", [&](const Request &req, Response &res) {
  9302. referer = req.get_header_value("Referer");
  9303. res.set_content("ok", "text/plain");
  9304. });
  9305. thread t = thread([&] { svr.listen(HOST, PORT); });
  9306. auto se = detail::scope_exit([&] {
  9307. svr.stop();
  9308. t.join();
  9309. ASSERT_FALSE(svr.is_running());
  9310. });
  9311. svr.wait_until_ready();
  9312. const std::string req = "GET /check HTTP/1.1\r\n"
  9313. "Host: localhost\r\n"
  9314. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9315. "Connection: close\r\n"
  9316. "\r\n";
  9317. std::string res;
  9318. ASSERT_TRUE(send_request(5, req, &res));
  9319. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9320. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9321. }
  9322. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9323. Server svr;
  9324. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9325. res.set_header("Cache-Control", "no-cache");
  9326. res.set_chunked_content_provider(
  9327. "text/event-stream", [](size_t offset, DataSink &sink) {
  9328. std::string s = "data:";
  9329. s += std::to_string(offset);
  9330. s += "\n\n";
  9331. auto ret = sink.write(s.data(), s.size());
  9332. EXPECT_TRUE(ret);
  9333. std::this_thread::sleep_for(std::chrono::seconds(1));
  9334. return true;
  9335. });
  9336. });
  9337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9338. svr.wait_until_ready();
  9339. Client client(HOST, PORT);
  9340. const Headers headers = {{"Accept", "text/event-stream"}};
  9341. auto get_thread = std::thread([&client, &headers]() {
  9342. auto res = client.Get(
  9343. "/events", headers,
  9344. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9345. });
  9346. auto se = detail::scope_exit([&] {
  9347. svr.stop();
  9348. get_thread.join();
  9349. listen_thread.join();
  9350. ASSERT_FALSE(svr.is_running());
  9351. });
  9352. // Give GET time to get a few messages.
  9353. std::this_thread::sleep_for(std::chrono::seconds(2));
  9354. }
  9355. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9356. httplib::Server svr;
  9357. svr.Post("/hi",
  9358. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9359. res.status = StatusCode::OK_200;
  9360. });
  9361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9362. svr.wait_until_ready();
  9363. Client cli(HOST, PORT);
  9364. auto res = cli.Post("/hi", "data", "text/plain");
  9365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9366. EXPECT_EQ(StatusCode::OK_200, res->status);
  9367. svr.stop();
  9368. thread.join();
  9369. ASSERT_FALSE(svr.is_running());
  9370. res = cli.Post("/hi", "data", "text/plain");
  9371. ASSERT_FALSE(res);
  9372. }
  9373. TEST(ServerStopTest, ListenFailure) {
  9374. Server svr;
  9375. auto t = thread([&]() {
  9376. auto ret = svr.listen("????", PORT);
  9377. EXPECT_FALSE(ret);
  9378. });
  9379. svr.wait_until_ready();
  9380. svr.stop();
  9381. t.join();
  9382. }
  9383. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9384. TEST(ServerStopTest, Decommision) {
  9385. Server svr;
  9386. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9387. for (int i = 0; i < 4; i++) {
  9388. auto is_even = !(i % 2);
  9389. std::thread t{[&] {
  9390. try {
  9391. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9392. if (is_even) {
  9393. throw std::runtime_error("Some thing that happens to go wrong.");
  9394. }
  9395. svr.listen(HOST, PORT);
  9396. } catch (...) { svr.decommission(); }
  9397. }};
  9398. svr.wait_until_ready();
  9399. // Server is up
  9400. {
  9401. Client cli(HOST, PORT);
  9402. auto res = cli.Get("/hi");
  9403. if (is_even) {
  9404. EXPECT_FALSE(res);
  9405. } else {
  9406. EXPECT_TRUE(res);
  9407. EXPECT_EQ("hi...", res->body);
  9408. }
  9409. }
  9410. svr.stop();
  9411. t.join();
  9412. // Server is down...
  9413. {
  9414. Client cli(HOST, PORT);
  9415. auto res = cli.Get("/hi");
  9416. EXPECT_FALSE(res);
  9417. }
  9418. }
  9419. }
  9420. #endif
  9421. // Helper function for string body upload progress tests
  9422. template <typename SetupHandler, typename ClientCall>
  9423. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9424. ClientCall &&client_call,
  9425. const string &body) {
  9426. Server svr;
  9427. setup_handler(svr);
  9428. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9429. auto se = detail::scope_exit([&] {
  9430. svr.stop();
  9431. t.join();
  9432. });
  9433. svr.wait_until_ready();
  9434. Client cli(HOST, PORT);
  9435. vector<uint64_t> progress_values;
  9436. bool progress_called = false;
  9437. auto res =
  9438. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9439. progress_values.push_back(current);
  9440. progress_called = true;
  9441. return true;
  9442. });
  9443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9444. EXPECT_EQ(200, res->status);
  9445. EXPECT_TRUE(progress_called);
  9446. }
  9447. TEST(UploadProgressTest, PostStringBodyBasic) {
  9448. TestStringBodyUploadProgress(
  9449. [](Server &svr) {
  9450. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9451. res.set_content("received", "text/plain");
  9452. });
  9453. },
  9454. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9455. return cli.Post("/test", body, "text/plain", progress_callback);
  9456. },
  9457. "test data for upload progress");
  9458. }
  9459. TEST(UploadProgressTest, PutStringBodyBasic) {
  9460. TestStringBodyUploadProgress(
  9461. [](Server &svr) {
  9462. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9463. res.set_content("put received", "text/plain");
  9464. });
  9465. },
  9466. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9467. return cli.Put("/test", body, "text/plain", progress_callback);
  9468. },
  9469. "put test data for upload progress");
  9470. }
  9471. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9472. TestStringBodyUploadProgress(
  9473. [](Server &svr) {
  9474. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9475. res.set_content("patch received", "text/plain");
  9476. });
  9477. },
  9478. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9479. return cli.Patch("/test", body, "text/plain", progress_callback);
  9480. },
  9481. "patch test data for upload progress");
  9482. }
  9483. // Helper function for content provider upload progress tests
  9484. template <typename SetupHandler, typename ClientCall>
  9485. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9486. ClientCall &&client_call) {
  9487. Server svr;
  9488. setup_handler(svr);
  9489. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9490. auto se = detail::scope_exit([&] {
  9491. svr.stop();
  9492. t.join();
  9493. });
  9494. svr.wait_until_ready();
  9495. Client cli(HOST, PORT);
  9496. vector<uint64_t> progress_values;
  9497. auto res =
  9498. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9499. progress_values.push_back(current);
  9500. return true;
  9501. });
  9502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9503. EXPECT_EQ(200, res->status);
  9504. EXPECT_FALSE(progress_values.empty());
  9505. }
  9506. TEST(UploadProgressTest, PostContentProviderProgress) {
  9507. TestContentProviderUploadProgress(
  9508. [](Server &svr) {
  9509. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9510. res.set_content("provider received", "text/plain");
  9511. });
  9512. },
  9513. [](Client &cli, UploadProgress progress_callback) {
  9514. return cli.Post(
  9515. "/test", 10,
  9516. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9517. sink.os << "test data";
  9518. return true;
  9519. },
  9520. "text/plain", progress_callback);
  9521. });
  9522. }
  9523. // Helper function for multipart upload progress tests
  9524. template <typename SetupHandler, typename ClientCall>
  9525. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9526. ClientCall &&client_call,
  9527. const string &endpoint) {
  9528. Server svr;
  9529. setup_handler(svr);
  9530. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9531. auto se = detail::scope_exit([&] {
  9532. svr.stop();
  9533. t.join();
  9534. });
  9535. svr.wait_until_ready();
  9536. Client cli(HOST, PORT);
  9537. vector<uint64_t> progress_values;
  9538. UploadFormDataItems items = {
  9539. {"field1", "value1", "", ""},
  9540. {"field2", "longer value for progress tracking test", "", ""},
  9541. {"file1", "file content data for upload progress", "test.txt",
  9542. "text/plain"}};
  9543. auto res = client_call(cli, endpoint, items,
  9544. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9545. progress_values.push_back(current);
  9546. return true;
  9547. });
  9548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9549. EXPECT_EQ(200, res->status);
  9550. EXPECT_FALSE(progress_values.empty());
  9551. }
  9552. TEST(UploadProgressTest, PostMultipartProgress) {
  9553. TestMultipartUploadProgress(
  9554. [](Server &svr) {
  9555. svr.Post("/multipart", [](const Request &req, Response &res) {
  9556. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9557. res.set_content("multipart received", "text/plain");
  9558. });
  9559. },
  9560. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9561. UploadProgress progress_callback) {
  9562. return cli.Post(endpoint, items, progress_callback);
  9563. },
  9564. "/multipart");
  9565. }
  9566. // Helper function for basic download progress tests
  9567. template <typename SetupHandler, typename ClientCall>
  9568. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9569. ClientCall &&client_call, const string &endpoint,
  9570. size_t expected_content_size) {
  9571. Server svr;
  9572. setup_handler(svr);
  9573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9574. auto se = detail::scope_exit([&] {
  9575. svr.stop();
  9576. t.join();
  9577. });
  9578. svr.wait_until_ready();
  9579. Client cli(HOST, PORT);
  9580. vector<uint64_t> progress_values;
  9581. auto res = client_call(cli, endpoint,
  9582. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9583. progress_values.push_back(current);
  9584. return true;
  9585. });
  9586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9587. EXPECT_EQ(200, res->status);
  9588. EXPECT_FALSE(progress_values.empty());
  9589. EXPECT_EQ(expected_content_size, res->body.size());
  9590. }
  9591. TEST(DownloadProgressTest, GetBasic) {
  9592. TestBasicDownloadProgress(
  9593. [](Server &svr) {
  9594. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9595. string content(1000, 'D');
  9596. res.set_content(content, "text/plain");
  9597. });
  9598. },
  9599. [](Client &cli, const string &endpoint,
  9600. DownloadProgress progress_callback) {
  9601. return cli.Get(endpoint, progress_callback);
  9602. },
  9603. "/download", 1000u);
  9604. }
  9605. // Helper function for content receiver download progress tests
  9606. template <typename SetupHandler, typename ClientCall>
  9607. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9608. ClientCall &&client_call,
  9609. const string &endpoint,
  9610. size_t expected_content_size) {
  9611. Server svr;
  9612. setup_handler(svr);
  9613. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9614. auto se = detail::scope_exit([&] {
  9615. svr.stop();
  9616. t.join();
  9617. });
  9618. svr.wait_until_ready();
  9619. Client cli(HOST, PORT);
  9620. vector<uint64_t> progress_values;
  9621. string received_body;
  9622. auto res = client_call(
  9623. cli, endpoint,
  9624. [&](const char *data, size_t data_length) -> bool {
  9625. received_body.append(data, data_length);
  9626. return true;
  9627. },
  9628. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9629. progress_values.push_back(current);
  9630. return true;
  9631. });
  9632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9633. EXPECT_EQ(200, res->status);
  9634. EXPECT_FALSE(progress_values.empty());
  9635. EXPECT_EQ(expected_content_size, received_body.size());
  9636. EXPECT_TRUE(res->body.empty());
  9637. }
  9638. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9639. TestContentReceiverDownloadProgress(
  9640. [](Server &svr) {
  9641. svr.Get("/download-receiver",
  9642. [](const Request & /*req*/, Response &res) {
  9643. string content(2000, 'R');
  9644. res.set_content(content, "text/plain");
  9645. });
  9646. },
  9647. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9648. DownloadProgress progress_callback) {
  9649. return cli.Get(endpoint, content_receiver, progress_callback);
  9650. },
  9651. "/download-receiver", 2000u);
  9652. }
  9653. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9654. // A provider reaching a pass with nothing to hand over - an empty buffer
  9655. // popped off a queue, say - must not be taken to mean the body is finished.
  9656. // It used to end the loop with the terminating chunk unwritten while the
  9657. // server still considered the response complete, so the peer waited for an
  9658. // end that never arrived.
  9659. Server svr;
  9660. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9661. auto step = std::make_shared<int>(0);
  9662. res.set_chunked_content_provider("text/plain",
  9663. [step](size_t /*offset*/, DataSink &sink) {
  9664. switch ((*step)++) {
  9665. case 0: sink.write("", 0); break;
  9666. case 1: sink.write("hello", 5); break;
  9667. default: sink.done(); break;
  9668. }
  9669. return true;
  9670. });
  9671. });
  9672. auto port = svr.bind_to_any_port(HOST);
  9673. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9674. auto listen_se = detail::scope_exit([&] {
  9675. svr.stop();
  9676. listen_thread.join();
  9677. ASSERT_FALSE(svr.is_running());
  9678. });
  9679. svr.wait_until_ready();
  9680. Client cli(HOST, port);
  9681. // Without the fix the body is never terminated, so bound the wait rather
  9682. // than letting the test hang on the default read timeout.
  9683. cli.set_read_timeout(5, 0);
  9684. auto res = cli.Get("/stream");
  9685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9686. EXPECT_EQ(StatusCode::OK_200, res->status);
  9687. EXPECT_EQ("hello", res->body);
  9688. }
  9689. TEST(StreamingTest, NoContentLengthStreaming) {
  9690. Server svr;
  9691. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9692. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9693. if (offset < 6) {
  9694. sink.os << (offset < 3 ? "a" : "b");
  9695. } else {
  9696. sink.done();
  9697. }
  9698. return true;
  9699. });
  9700. });
  9701. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9702. auto listen_se = detail::scope_exit([&] {
  9703. svr.stop();
  9704. listen_thread.join();
  9705. ASSERT_FALSE(svr.is_running());
  9706. });
  9707. svr.wait_until_ready();
  9708. Client client(HOST, PORT);
  9709. auto get_thread = std::thread([&client]() {
  9710. std::string s;
  9711. auto res =
  9712. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9713. s += std::string(data, len);
  9714. return true;
  9715. });
  9716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9717. EXPECT_EQ(StatusCode::OK_200, res->status);
  9718. EXPECT_EQ("aaabbb", s);
  9719. });
  9720. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9721. // Give GET time to get a few messages.
  9722. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9723. }
  9724. TEST(MountTest, Unmount) {
  9725. Server svr;
  9726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. listen_thread.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. });
  9732. svr.wait_until_ready();
  9733. Client cli("localhost", PORT);
  9734. svr.set_mount_point("/mount2", "./www2");
  9735. auto res = cli.Get("/");
  9736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9738. res = cli.Get("/mount2/dir/test.html");
  9739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9740. EXPECT_EQ(StatusCode::OK_200, res->status);
  9741. svr.set_mount_point("/", "./www");
  9742. res = cli.Get("/dir/");
  9743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9744. EXPECT_EQ(StatusCode::OK_200, res->status);
  9745. svr.remove_mount_point("/");
  9746. res = cli.Get("/dir/");
  9747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9748. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9749. svr.remove_mount_point("/mount2");
  9750. res = cli.Get("/mount2/dir/test.html");
  9751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9752. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9753. }
  9754. TEST(MountTest, PathSegmentBoundary) {
  9755. Server svr;
  9756. svr.set_mount_point("/mount2", "./www2");
  9757. svr.set_mount_point("/", "./www");
  9758. auto port = svr.bind_to_any_port(HOST);
  9759. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9760. auto se = detail::scope_exit([&] {
  9761. svr.stop();
  9762. listen_thread.join();
  9763. ASSERT_FALSE(svr.is_running());
  9764. });
  9765. svr.wait_until_ready();
  9766. Client cli(HOST, port);
  9767. auto res = cli.Get("/mount2/dir/test.html");
  9768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9769. EXPECT_EQ(StatusCode::OK_200, res->status);
  9770. // "/mount2" must not match part-way through a path segment.
  9771. res = cli.Get("/mount2dir/test.html");
  9772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9773. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9774. // A mount point ending in '/' keeps matching every path below it.
  9775. res = cli.Get("/dir/test.html");
  9776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9777. EXPECT_EQ(StatusCode::OK_200, res->status);
  9778. }
  9779. TEST(MountTest, Redicect) {
  9780. Server svr;
  9781. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9782. auto se = detail::scope_exit([&] {
  9783. svr.stop();
  9784. listen_thread.join();
  9785. ASSERT_FALSE(svr.is_running());
  9786. });
  9787. svr.set_mount_point("/", "./www");
  9788. svr.wait_until_ready();
  9789. Client cli("localhost", PORT);
  9790. auto res = cli.Get("/dir/");
  9791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9792. EXPECT_EQ(StatusCode::OK_200, res->status);
  9793. res = cli.Get("/dir");
  9794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9795. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9796. res = cli.Get("/file");
  9797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9798. EXPECT_EQ(StatusCode::OK_200, res->status);
  9799. res = cli.Get("/file/");
  9800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9801. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9802. cli.set_follow_location(true);
  9803. res = cli.Get("/dir");
  9804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9805. EXPECT_EQ(StatusCode::OK_200, res->status);
  9806. }
  9807. TEST(MountTest, MultibytesPathName) {
  9808. Server svr;
  9809. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9810. auto se = detail::scope_exit([&] {
  9811. svr.stop();
  9812. listen_thread.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. svr.set_mount_point("/", "./www");
  9816. svr.wait_until_ready();
  9817. Client cli("localhost", PORT);
  9818. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9820. EXPECT_EQ(StatusCode::OK_200, res->status);
  9821. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9822. }
  9823. #ifdef _WIN32
  9824. // Issue #2435: mmap::open() must succeed even when another handle holds
  9825. // the file open for writing (e.g. an active log file).
  9826. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9827. const char *path = "mmap_concurrent_writer_test.txt";
  9828. const char *content = "hello";
  9829. {
  9830. std::ofstream f(path, std::ios::binary);
  9831. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9832. }
  9833. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9834. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9835. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9836. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9837. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9838. detail::mmap m(path);
  9839. ASSERT_TRUE(m.is_open());
  9840. EXPECT_EQ(strlen(content), m.size());
  9841. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9842. }
  9843. #endif
  9844. #ifndef _WIN32
  9845. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9846. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9847. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9848. TEST(MmapTest, FailedMappingIsNotOpen) {
  9849. const char *path = "./mmap_failed_mapping_test_dir";
  9850. ASSERT_EQ(0, ::mkdir(path, 0755));
  9851. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9852. detail::mmap m(path);
  9853. EXPECT_FALSE(m.is_open());
  9854. EXPECT_EQ(0U, m.size());
  9855. EXPECT_NE(static_cast<const void *>(m.data()),
  9856. static_cast<const void *>(MAP_FAILED));
  9857. }
  9858. #endif
  9859. TEST(KeepAliveTest, ReadTimeout) {
  9860. Server svr;
  9861. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9862. std::this_thread::sleep_for(std::chrono::seconds(2));
  9863. res.set_content("a", "text/plain");
  9864. });
  9865. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9866. res.set_content("b", "text/plain");
  9867. });
  9868. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9869. auto se = detail::scope_exit([&] {
  9870. svr.stop();
  9871. listen_thread.join();
  9872. ASSERT_FALSE(svr.is_running());
  9873. });
  9874. svr.wait_until_ready();
  9875. Client cli("localhost", PORT);
  9876. cli.set_keep_alive(true);
  9877. cli.set_read_timeout(std::chrono::seconds(1));
  9878. auto resa = cli.Get("/a");
  9879. ASSERT_FALSE(resa);
  9880. EXPECT_EQ(Error::Read, resa.error());
  9881. auto resb = cli.Get("/b");
  9882. ASSERT_TRUE(resb);
  9883. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9884. EXPECT_EQ("b", resb->body);
  9885. }
  9886. TEST(KeepAliveTest, MaxCount) {
  9887. size_t keep_alive_max_count = 3;
  9888. Server svr;
  9889. svr.set_keep_alive_max_count(keep_alive_max_count);
  9890. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9891. res.set_content("Hello World!", "text/plain");
  9892. });
  9893. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. listen_thread.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. });
  9899. svr.wait_until_ready();
  9900. Client cli(HOST, PORT);
  9901. cli.set_keep_alive(true);
  9902. for (size_t i = 0; i < 5; i++) {
  9903. auto result = cli.Get("/hi");
  9904. ASSERT_TRUE(result);
  9905. EXPECT_EQ(StatusCode::OK_200, result->status);
  9906. if (i == keep_alive_max_count - 1) {
  9907. EXPECT_EQ("close", result->get_header_value("Connection"));
  9908. } else {
  9909. EXPECT_FALSE(result->has_header("Connection"));
  9910. }
  9911. }
  9912. }
  9913. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9914. // can pull the next one into the server's buffer. The server must serve it
  9915. // without waiting for the socket to become readable again. The keep-alive
  9916. // timeout outlasts the client's read timeout, so a request left waiting for it
  9917. // shows up as a missing response.
  9918. static void serve_pipelining_routes(Server &svr,
  9919. const std::function<void(int)> &client) {
  9920. svr.set_keep_alive_timeout(5);
  9921. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9922. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9923. });
  9924. svr.Post("/echo", [](const Request &req, Response &res) {
  9925. res.set_content("echo " + req.body, "text/plain");
  9926. });
  9927. auto port = svr.bind_to_any_port(HOST);
  9928. thread t = thread([&] { svr.listen_after_bind(); });
  9929. auto se = detail::scope_exit([&] {
  9930. svr.stop();
  9931. t.join();
  9932. });
  9933. svr.wait_until_ready();
  9934. client(port);
  9935. }
  9936. static std::string
  9937. send_pipelined_requests(const std::vector<std::string> &parts) {
  9938. Server svr;
  9939. std::string res;
  9940. serve_pipelining_routes(svr, [&](int port) {
  9941. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9942. });
  9943. return res;
  9944. }
  9945. static void expect_in_order(const std::string &res,
  9946. const std::vector<std::string> &bodies) {
  9947. size_t pos = 0;
  9948. for (const auto &body : bodies) {
  9949. pos = res.find(body, pos);
  9950. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9951. pos += body.size();
  9952. }
  9953. }
  9954. TEST(KeepAliveTest, PipelinedRequests) {
  9955. auto res = send_pipelined_requests(
  9956. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9957. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9958. "Content-Length: 4\r\n\r\nbody"
  9959. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9960. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9961. }
  9962. // The second request starts in the server's buffer and ends on the socket.
  9963. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9964. auto res =
  9965. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9966. "GET /hi/2 HTTP/1.1\r\nHo",
  9967. "st: localhost\r\nConnection: close\r\n\r\n"});
  9968. expect_in_order(res, {"hi 1", "hi 2"});
  9969. }
  9970. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9971. // CRLF after a body does not turn into a 400 for the next request.
  9972. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9973. auto res = send_pipelined_requests(
  9974. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9975. "Content-Length: 4\r\n\r\nbody\r\n"
  9976. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9977. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9978. expect_in_order(res, {"echo body", "hi 2"});
  9979. }
  9980. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9981. // must not be served as the next request.
  9982. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9983. auto res = send_pipelined_requests(
  9984. {"INVALID REQUEST LINE\r\n\r\n"
  9985. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9986. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9987. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9988. }
  9989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9990. // Over TLS, the next request is held by the TLS library as already decrypted
  9991. // data rather than on the socket.
  9992. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9994. std::string res;
  9995. serve_pipelining_routes(svr, [&](int port) {
  9996. auto error = Error::Success;
  9997. auto sock = detail::create_client_socket(
  9998. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9999. /*connection_timeout_sec=*/5, 0,
  10000. /*read_timeout_sec=*/2, 0,
  10001. /*write_timeout_sec=*/5, 0, std::string(), error);
  10002. ASSERT_NE(INVALID_SOCKET, sock);
  10003. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10004. auto ctx = SSL_CTX_new(TLS_client_method());
  10005. auto ssl = SSL_new(ctx);
  10006. auto ssl_se = detail::scope_exit([&] {
  10007. SSL_free(ssl);
  10008. SSL_CTX_free(ctx);
  10009. });
  10010. SSL_set_fd(ssl, static_cast<int>(sock));
  10011. ASSERT_EQ(1, SSL_connect(ssl));
  10012. // One write, so all three requests arrive in one TLS record
  10013. const std::string req =
  10014. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10015. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10016. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10017. ASSERT_EQ(static_cast<int>(req.size()),
  10018. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10019. char buf[512];
  10020. int n;
  10021. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10022. res.append(buf, static_cast<size_t>(n));
  10023. }
  10024. });
  10025. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10026. }
  10027. #endif
  10028. TEST(KeepAliveTest, Issue1041) {
  10029. Server svr;
  10030. svr.set_keep_alive_timeout(3);
  10031. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10032. res.set_content("Hello World!", "text/plain");
  10033. });
  10034. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10035. auto se = detail::scope_exit([&] {
  10036. svr.stop();
  10037. listen_thread.join();
  10038. ASSERT_FALSE(svr.is_running());
  10039. });
  10040. svr.wait_until_ready();
  10041. Client cli(HOST, PORT);
  10042. cli.set_keep_alive(true);
  10043. auto result = cli.Get("/hi");
  10044. ASSERT_TRUE(result);
  10045. EXPECT_EQ(StatusCode::OK_200, result->status);
  10046. std::this_thread::sleep_for(std::chrono::seconds(5));
  10047. result = cli.Get("/hi");
  10048. ASSERT_TRUE(result);
  10049. EXPECT_EQ(StatusCode::OK_200, result->status);
  10050. }
  10051. TEST(KeepAliveTest, Issue1959) {
  10052. Server svr;
  10053. svr.set_keep_alive_timeout(5);
  10054. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10055. res.set_content("a", "text/plain");
  10056. });
  10057. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10058. auto se = detail::scope_exit([&] {
  10059. if (!svr.is_running()) return;
  10060. svr.stop();
  10061. listen_thread.join();
  10062. ASSERT_FALSE(svr.is_running());
  10063. });
  10064. svr.wait_until_ready();
  10065. Client cli("localhost", PORT);
  10066. cli.set_keep_alive(true);
  10067. using namespace std::chrono;
  10068. auto start = steady_clock::now();
  10069. cli.Get("/a");
  10070. svr.stop();
  10071. listen_thread.join();
  10072. auto end = steady_clock::now();
  10073. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10074. EXPECT_LT(elapsed, 5000);
  10075. }
  10076. #ifdef CPPHTTPLIB_SSL_ENABLED
  10077. TEST(KeepAliveTest, SSLClientReconnection) {
  10078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10079. ASSERT_TRUE(svr.is_valid());
  10080. svr.set_keep_alive_timeout(1);
  10081. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10082. res.set_content("Hello World!", "text/plain");
  10083. });
  10084. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10085. auto se = detail::scope_exit([&] {
  10086. svr.stop();
  10087. listen_thread.join();
  10088. ASSERT_FALSE(svr.is_running());
  10089. });
  10090. svr.wait_until_ready();
  10091. SSLClient cli(HOST, PORT);
  10092. cli.enable_server_certificate_verification(false);
  10093. cli.set_keep_alive(true);
  10094. auto result = cli.Get("/hi");
  10095. ASSERT_TRUE(result);
  10096. EXPECT_EQ(StatusCode::OK_200, result->status);
  10097. result = cli.Get("/hi");
  10098. ASSERT_TRUE(result);
  10099. EXPECT_EQ(StatusCode::OK_200, result->status);
  10100. std::this_thread::sleep_for(std::chrono::seconds(2));
  10101. // Recoonect
  10102. result = cli.Get("/hi");
  10103. ASSERT_TRUE(result);
  10104. EXPECT_EQ(StatusCode::OK_200, result->status);
  10105. result = cli.Get("/hi");
  10106. ASSERT_TRUE(result);
  10107. EXPECT_EQ(StatusCode::OK_200, result->status);
  10108. }
  10109. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10111. ASSERT_TRUE(svr.is_valid());
  10112. svr.set_keep_alive_timeout(1);
  10113. std::string content = "reconnect";
  10114. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10115. res.set_content("Hello World!", "text/plain");
  10116. });
  10117. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10118. auto se = detail::scope_exit([&] {
  10119. svr.stop();
  10120. listen_thread.join();
  10121. ASSERT_FALSE(svr.is_running());
  10122. });
  10123. svr.wait_until_ready();
  10124. SSLClient cli(HOST, PORT);
  10125. cli.enable_server_certificate_verification(false);
  10126. cli.set_keep_alive(true);
  10127. auto result = cli.Post(
  10128. "/hi", content.size(),
  10129. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10130. sink.write(content.c_str(), content.size());
  10131. return true;
  10132. },
  10133. "text/plain");
  10134. ASSERT_TRUE(result);
  10135. EXPECT_EQ(200, result->status);
  10136. std::this_thread::sleep_for(std::chrono::seconds(2));
  10137. // Recoonect
  10138. result = cli.Post(
  10139. "/hi", content.size(),
  10140. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10141. sink.write(content.c_str(), content.size());
  10142. return true;
  10143. },
  10144. "text/plain");
  10145. ASSERT_TRUE(result);
  10146. EXPECT_EQ(200, result->status);
  10147. result = cli.Post(
  10148. "/hi", content.size(),
  10149. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10150. sink.write(content.c_str(), content.size());
  10151. return true;
  10152. },
  10153. "text/plain");
  10154. ASSERT_TRUE(result);
  10155. EXPECT_EQ(200, result->status);
  10156. }
  10157. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10158. using namespace httplib::tls;
  10159. {
  10160. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10161. ASSERT_TRUE(svr.is_valid());
  10162. svr.Get("/sni", [&](const Request &req, Response &res) {
  10163. std::string expected = req.sni();
  10164. EXPECT_EQ(expected, req.get_param_value("expected"));
  10165. res.set_content("ok", "text/plain");
  10166. });
  10167. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10168. auto se = detail::scope_exit([&] {
  10169. svr.stop();
  10170. listen_thread.join();
  10171. ASSERT_FALSE(svr.is_running());
  10172. });
  10173. svr.wait_until_ready();
  10174. {
  10175. SSLClient cli("localhost", PORT);
  10176. cli.enable_server_certificate_verification(false);
  10177. auto res = cli.Get("/sni?expected=localhost");
  10178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10179. }
  10180. {
  10181. SSLClient cli("::1", PORT);
  10182. cli.enable_server_certificate_verification(false);
  10183. auto res = cli.Get("/sni?expected=");
  10184. // NOTE: This may fail if the server is listening on IPv4 only
  10185. // (e.g., when localhost resolves to 127.0.0.1 only)
  10186. if (res) {
  10187. EXPECT_EQ(StatusCode::OK_200, res->status);
  10188. } else {
  10189. EXPECT_EQ(Error::Connection, res.error());
  10190. }
  10191. }
  10192. }
  10193. }
  10194. #endif
  10195. TEST(ClientProblemDetectionTest, ContentProvider) {
  10196. Server svr;
  10197. size_t content_length = 1024 * 1024;
  10198. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10199. res.set_content_provider(
  10200. content_length, "text/plain",
  10201. [&](size_t offset, size_t length, DataSink &sink) {
  10202. auto out_len = std::min(length, static_cast<size_t>(1024));
  10203. std::string out(out_len, '@');
  10204. sink.write(out.data(), out_len);
  10205. return offset < 4096;
  10206. },
  10207. [](bool success) { ASSERT_FALSE(success); });
  10208. });
  10209. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10210. res.set_content_provider(
  10211. 0, "text/plain",
  10212. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10213. EXPECT_TRUE(false);
  10214. return true;
  10215. },
  10216. [](bool success) { ASSERT_FALSE(success); });
  10217. });
  10218. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10219. auto se = detail::scope_exit([&] {
  10220. svr.stop();
  10221. listen_thread.join();
  10222. ASSERT_FALSE(svr.is_running());
  10223. });
  10224. svr.wait_until_ready();
  10225. Client cli("localhost", PORT);
  10226. {
  10227. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10228. size_t /*data_length*/) { return false; });
  10229. ASSERT_FALSE(res);
  10230. }
  10231. {
  10232. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10233. size_t /*data_length*/) { return false; });
  10234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10235. }
  10236. }
  10237. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10238. // A provider that reports success without writing anything and without
  10239. // calling done() used to be handed the same offset and length again on every
  10240. // pass, so it spun for as long as the peer stayed connected.
  10241. Server svr;
  10242. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10243. res.set_content("ok", "text/plain");
  10244. });
  10245. auto port = svr.bind_to_any_port(HOST);
  10246. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10247. auto se = detail::scope_exit([&] {
  10248. svr.stop();
  10249. listen_thread.join();
  10250. ASSERT_FALSE(svr.is_running());
  10251. });
  10252. svr.wait_until_ready();
  10253. std::atomic<int> call_count{0};
  10254. Client cli(HOST, port);
  10255. auto res = cli.Post(
  10256. "/", 1024,
  10257. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10258. // Give up after enough passes to show the spin, so that losing the
  10259. // check below fails this test instead of hanging it.
  10260. return ++call_count < 100;
  10261. },
  10262. "text/plain");
  10263. ASSERT_FALSE(res);
  10264. EXPECT_EQ(Error::Write, res.error());
  10265. EXPECT_EQ(1, call_count.load());
  10266. }
  10267. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10268. // A writer only has to assign `write`. The other three used to be left as
  10269. // empty std::functions, so a provider calling one threw
  10270. // std::bad_function_call out of the thread running it and took the whole
  10271. // process down.
  10272. DataSink sink;
  10273. std::string written;
  10274. sink.write = [&](const char *data, size_t data_len) {
  10275. written.append(data, data_len);
  10276. return true;
  10277. };
  10278. EXPECT_TRUE(sink.is_writable());
  10279. sink.done();
  10280. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10281. EXPECT_TRUE(written.empty());
  10282. }
  10283. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10284. // A sink that cannot carry trailers still has to finish.
  10285. DataSink sink;
  10286. auto done_count = 0;
  10287. sink.done = [&]() { done_count++; };
  10288. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10289. EXPECT_EQ(1, done_count);
  10290. }
  10291. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10292. Server svr;
  10293. const std::string body(4096, 'x');
  10294. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10295. res.set_content_provider(body.size(), "text/plain",
  10296. [&](size_t offset, size_t length, DataSink &sink) {
  10297. sink.write(body.data() + offset, length);
  10298. sink.done();
  10299. return true;
  10300. });
  10301. });
  10302. auto port = svr.bind_to_any_port(HOST);
  10303. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10304. auto se = detail::scope_exit([&] {
  10305. svr.stop();
  10306. listen_thread.join();
  10307. ASSERT_FALSE(svr.is_running());
  10308. });
  10309. svr.wait_until_ready();
  10310. Client cli(HOST, port);
  10311. auto res = cli.Get("/");
  10312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10313. EXPECT_EQ(StatusCode::OK_200, res->status);
  10314. EXPECT_EQ(body, res->body);
  10315. }
  10316. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10317. Server svr;
  10318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10319. res.set_content_provider(
  10320. 1024, "text/plain",
  10321. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10322. sink.write("hello", 5);
  10323. sink.done(); // short of the 1024 bytes the response promised
  10324. return true;
  10325. });
  10326. });
  10327. auto port = svr.bind_to_any_port(HOST);
  10328. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10329. auto se = detail::scope_exit([&] {
  10330. svr.stop();
  10331. listen_thread.join();
  10332. ASSERT_FALSE(svr.is_running());
  10333. });
  10334. svr.wait_until_ready();
  10335. Client cli(HOST, port);
  10336. cli.set_read_timeout(5, 0);
  10337. // The response is short of its Content-Length, so the client cannot read a
  10338. // complete body. What matters is that this returns at all: a no-op done()
  10339. // would leave the writer looping over a provider that never makes progress.
  10340. auto res = cli.Get("/");
  10341. EXPECT_FALSE(res);
  10342. }
  10343. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10344. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10345. // The compressed path builds the whole body before connecting, so this
  10346. // fails client-side and never reaches a server.
  10347. Client cli(HOST, PORT);
  10348. cli.set_compress(true);
  10349. auto res = cli.Post(
  10350. "/", 1024,
  10351. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10352. sink.write("hello", 5);
  10353. sink.done(); // short of the 1024 bytes the request announced
  10354. return true;
  10355. },
  10356. "text/plain");
  10357. ASSERT_FALSE(res);
  10358. EXPECT_EQ(Error::Write, res.error());
  10359. }
  10360. #endif
  10361. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10362. Server svr;
  10363. svr.set_error_handler([](Request const &, Response &res) -> void {
  10364. res.set_chunked_content_provider(
  10365. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10366. sink.os << "hello";
  10367. sink.os << "world";
  10368. sink.done();
  10369. return true;
  10370. });
  10371. });
  10372. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10373. auto se = detail::scope_exit([&] {
  10374. svr.stop();
  10375. listen_thread.join();
  10376. ASSERT_FALSE(svr.is_running());
  10377. });
  10378. svr.wait_until_ready();
  10379. Client cli("localhost", PORT);
  10380. auto res = cli.Get("/");
  10381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10383. EXPECT_EQ("helloworld", res->body);
  10384. }
  10385. // A body set after a content provider must replace it, not be sent through it.
  10386. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10387. Server svr;
  10388. svr.set_mount_point("/", "./www");
  10389. svr.set_file_request_handler([](const Request &req, Response &res) {
  10390. if (req.path == "/dir/test.html") {
  10391. res.status = StatusCode::Forbidden_403;
  10392. res.set_content(std::string(5000, 'D'), "text/plain");
  10393. } else if (req.path == "/file") {
  10394. res.status = StatusCode::Forbidden_403;
  10395. res.body = "Denied";
  10396. }
  10397. });
  10398. auto port = svr.bind_to_any_port(HOST);
  10399. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10400. auto se = detail::scope_exit([&] {
  10401. svr.stop();
  10402. t.join();
  10403. ASSERT_FALSE(svr.is_running());
  10404. });
  10405. svr.wait_until_ready();
  10406. Client cli(HOST, port);
  10407. {
  10408. auto res = cli.Get("/dir/test.html");
  10409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10410. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10411. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10412. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10413. }
  10414. {
  10415. auto res = cli.Get("/file");
  10416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10417. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10418. EXPECT_EQ("Denied", res->body);
  10419. }
  10420. {
  10421. auto res = cli.Get("/dir/index.html");
  10422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10423. EXPECT_EQ(StatusCode::OK_200, res->status);
  10424. EXPECT_EQ(0U, res->body.find("<html>"));
  10425. }
  10426. }
  10427. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10428. Server svr;
  10429. std::vector<bool> released;
  10430. std::mutex released_mutex;
  10431. auto releaser = [&](bool success) {
  10432. std::lock_guard<std::mutex> guard(released_mutex);
  10433. released.push_back(success);
  10434. };
  10435. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10436. return sink.write(&"hello"[offset], length);
  10437. };
  10438. svr.Get("/sized", [&](const Request &, Response &res) {
  10439. res.status = StatusCode::NotFound_404;
  10440. res.set_content_provider(5, "text/plain", provider, releaser);
  10441. });
  10442. svr.Get("/chunked", [&](const Request &, Response &res) {
  10443. res.status = StatusCode::ServiceUnavailable_503;
  10444. res.set_chunked_content_provider(
  10445. "text/plain",
  10446. [](size_t, DataSink &sink) {
  10447. sink.os << "chunk";
  10448. sink.done();
  10449. return true;
  10450. },
  10451. releaser);
  10452. });
  10453. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10454. res.set_content_provider(5, "text/plain", provider, releaser);
  10455. throw std::runtime_error("after the provider");
  10456. });
  10457. svr.set_error_handler([](const Request &req, Response &res) {
  10458. // Leave the exception handler's content to it.
  10459. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10460. res.set_content(std::string(1000, 'E'), "text/html");
  10461. return Server::HandlerResponse::Handled;
  10462. });
  10463. svr.set_exception_handler(
  10464. [](const Request &, Response &res, std::exception_ptr) {
  10465. res.status = StatusCode::InternalServerError_500;
  10466. res.set_content(std::string(1000, 'X'), "text/html");
  10467. });
  10468. auto port = svr.bind_to_any_port(HOST);
  10469. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10470. auto se = detail::scope_exit([&] {
  10471. svr.stop();
  10472. t.join();
  10473. ASSERT_FALSE(svr.is_running());
  10474. });
  10475. svr.wait_until_ready();
  10476. Client cli(HOST, port);
  10477. {
  10478. auto res = cli.Get("/sized");
  10479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10481. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10482. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10483. }
  10484. {
  10485. auto res = cli.Get("/chunked");
  10486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10487. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10488. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10489. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10490. }
  10491. {
  10492. auto res = cli.Get("/throw");
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10495. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10496. }
  10497. std::lock_guard<std::mutex> guard(released_mutex);
  10498. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10499. }
  10500. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10501. Server svr;
  10502. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10503. return sink.write(&"abc"[offset], length);
  10504. };
  10505. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10506. res.set_file_content("./www/dir/test.html");
  10507. res.set_content("body", "text/plain");
  10508. });
  10509. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10510. res.set_content(std::string(100, 'B'), "text/plain");
  10511. res.set_file_content("./www/dir/test.html");
  10512. });
  10513. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10514. res.set_content(std::string(100, 'B'), "text/plain");
  10515. res.set_content_provider(3, "text/plain", abc);
  10516. });
  10517. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10518. res.set_content_provider(3, "text/plain", abc);
  10519. res.set_content(std::string(100, 'B'), "text/plain");
  10520. });
  10521. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10522. res.set_content_provider(3, "text/plain", abc);
  10523. res.body = "direct";
  10524. });
  10525. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10526. res.set_file_content("./www/dir/test.html");
  10527. res.body = "direct";
  10528. });
  10529. auto port = svr.bind_to_any_port(HOST);
  10530. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10531. auto se = detail::scope_exit([&] {
  10532. svr.stop();
  10533. t.join();
  10534. ASSERT_FALSE(svr.is_running());
  10535. });
  10536. svr.wait_until_ready();
  10537. Client cli(HOST, port);
  10538. auto expect_body = [&](const char *path, const std::string &body) {
  10539. // Uncompressed, so Content-Length can be compared with the body.
  10540. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10541. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10542. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10543. EXPECT_EQ(body, res->body) << path;
  10544. EXPECT_EQ(std::to_string(body.size()),
  10545. res->get_header_value("Content-Length"))
  10546. << path;
  10547. };
  10548. expect_body("/file-then-body", "body");
  10549. expect_body("/body-then-file", "test.html");
  10550. expect_body("/body-then-provider", "abc");
  10551. expect_body("/provider-then-body", std::string(100, 'B'));
  10552. expect_body("/provider-then-direct-body", "direct");
  10553. expect_body("/file-then-direct-body", "direct");
  10554. // Ranges are checked against the body, not the dropped provider.
  10555. {
  10556. auto res = cli.Get("/provider-then-direct-body",
  10557. Headers{{make_range_header({{1, 2}})}});
  10558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10559. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10560. EXPECT_EQ("ir", res->body);
  10561. }
  10562. {
  10563. auto res = cli.Get("/file-then-direct-body",
  10564. Headers{{make_range_header({{7, 8}})}});
  10565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10566. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10567. }
  10568. }
  10569. // Forward declaration (see the base64_encode note).
  10570. namespace httplib {
  10571. namespace detail {
  10572. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10573. const std::string &content_type,
  10574. EncodingType encoding);
  10575. } // namespace detail
  10576. } // namespace httplib
  10577. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10578. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10579. ASSERT_TRUE(mm->is_open());
  10580. Response res;
  10581. detail::set_file_content_provider(res, mm, "text/html",
  10582. detail::EncodingType::None);
  10583. std::string out;
  10584. DataSink sink;
  10585. sink.write = [&](const char *d, size_t l) {
  10586. out.append(d, l);
  10587. return true;
  10588. };
  10589. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10590. EXPECT_EQ("test.html", out);
  10591. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10592. EXPECT_EQ("test.html", out);
  10593. }
  10594. TEST(LongPollingTest, ClientCloseDetection) {
  10595. Server svr;
  10596. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10597. res.set_chunked_content_provider(
  10598. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10599. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10600. sink.os << "hello";
  10601. auto count = 10;
  10602. while (count > 0 && sink.is_writable()) {
  10603. this_thread::sleep_for(chrono::milliseconds(10));
  10604. count--;
  10605. }
  10606. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10607. return true;
  10608. });
  10609. });
  10610. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10611. auto se = detail::scope_exit([&] {
  10612. svr.stop();
  10613. listen_thread.join();
  10614. ASSERT_FALSE(svr.is_running());
  10615. });
  10616. svr.wait_until_ready();
  10617. Client cli("localhost", PORT);
  10618. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10619. EXPECT_EQ("hello", string(data, data_length));
  10620. return false; // close the socket immediately.
  10621. });
  10622. ASSERT_FALSE(res);
  10623. }
  10624. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10625. Server svr;
  10626. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10627. res.set_chunked_content_provider(
  10628. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10629. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10630. sink.os << "hello";
  10631. EXPECT_TRUE(sink.os.good());
  10632. // Wait for the client to close the connection
  10633. auto count = 10;
  10634. while (count > 0 && sink.is_writable()) {
  10635. this_thread::sleep_for(chrono::milliseconds(10));
  10636. count--;
  10637. }
  10638. // After client disconnect, write repeatedly until the socket
  10639. // write actually fails (small writes may be absorbed by the
  10640. // kernel buffer)
  10641. std::string chunk(1024, 'x');
  10642. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10643. sink.os << chunk;
  10644. }
  10645. EXPECT_TRUE(sink.os.fail());
  10646. return true;
  10647. });
  10648. });
  10649. auto port = svr.bind_to_any_port("localhost");
  10650. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. listen_thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli("localhost", port);
  10658. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10659. EXPECT_EQ("hello", string(data, data_length));
  10660. return false; // close the socket immediately.
  10661. });
  10662. ASSERT_FALSE(res);
  10663. }
  10664. TEST(GetWithParametersTest, GetWithParameters) {
  10665. Server svr;
  10666. svr.Get("/", [&](const Request &req, Response &) {
  10667. EXPECT_EQ("world", req.get_param_value("hello"));
  10668. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10669. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10670. });
  10671. svr.Get("/params", [&](const Request &req, Response &) {
  10672. EXPECT_EQ("world", req.get_param_value("hello"));
  10673. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10674. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10675. });
  10676. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10677. EXPECT_EQ("resource-id", req.matches[1]);
  10678. EXPECT_EQ("foo", req.get_param_value("param1"));
  10679. EXPECT_EQ("bar", req.get_param_value("param2"));
  10680. });
  10681. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10682. EXPECT_EQ("user-id", req.path_params.at("id"));
  10683. EXPECT_EQ("foo", req.get_param_value("param1"));
  10684. EXPECT_EQ("bar", req.get_param_value("param2"));
  10685. });
  10686. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. listen_thread.join();
  10690. ASSERT_FALSE(svr.is_running());
  10691. });
  10692. svr.wait_until_ready();
  10693. {
  10694. Client cli(HOST, PORT);
  10695. Params params;
  10696. params.emplace("hello", "world");
  10697. params.emplace("hello2", "world2");
  10698. params.emplace("hello3", "world3");
  10699. auto res = cli.Get("/", params, Headers{});
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::OK_200, res->status);
  10702. }
  10703. {
  10704. Client cli(HOST, PORT);
  10705. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10707. EXPECT_EQ(StatusCode::OK_200, res->status);
  10708. }
  10709. {
  10710. Client cli(HOST, PORT);
  10711. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10713. EXPECT_EQ(StatusCode::OK_200, res->status);
  10714. }
  10715. {
  10716. Client cli(HOST, PORT);
  10717. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10719. EXPECT_EQ(StatusCode::OK_200, res->status);
  10720. }
  10721. }
  10722. TEST(GetWithParametersTest, GetWithParameters2) {
  10723. Server svr;
  10724. svr.Get("/", [&](const Request &req, Response &res) {
  10725. auto text = req.get_param_value("hello");
  10726. res.set_content(text, "text/plain");
  10727. });
  10728. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10729. auto se = detail::scope_exit([&] {
  10730. svr.stop();
  10731. listen_thread.join();
  10732. ASSERT_FALSE(svr.is_running());
  10733. });
  10734. svr.wait_until_ready();
  10735. Client cli("localhost", PORT);
  10736. Params params;
  10737. params.emplace("hello", "world");
  10738. std::string body;
  10739. auto res = cli.Get("/", params, Headers{},
  10740. [&](const char *data, size_t data_length) {
  10741. body.append(data, data_length);
  10742. return true;
  10743. });
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ(StatusCode::OK_200, res->status);
  10746. EXPECT_EQ("world", body);
  10747. }
  10748. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10749. Server svr;
  10750. svr.Get("/search", [&](const Request &req, Response &res) {
  10751. auto q = req.get_param_value("q");
  10752. res.set_content(q, "text/plain");
  10753. });
  10754. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10755. auto se = detail::scope_exit([&] {
  10756. svr.stop();
  10757. listen_thread.join();
  10758. ASSERT_FALSE(svr.is_running());
  10759. });
  10760. svr.wait_until_ready();
  10761. Client cli("localhost", PORT);
  10762. // Verify that Get(path, params) works without requiring Headers argument
  10763. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10765. EXPECT_EQ(StatusCode::OK_200, res->status);
  10766. EXPECT_EQ("cpp-httplib", res->body);
  10767. }
  10768. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10769. auto host = "httpbingo.org";
  10770. auto path = std::string{"/range/32"};
  10771. #ifdef CPPHTTPLIB_SSL_ENABLED
  10772. SSLClient cli(host);
  10773. #else
  10774. Client cli(host);
  10775. #endif
  10776. cli.set_default_headers({make_range_header({{1, 10}})});
  10777. cli.set_connection_timeout(5);
  10778. {
  10779. auto res = cli.Get(path);
  10780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10781. EXPECT_EQ("bcdefghijk", res->body);
  10782. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10783. }
  10784. {
  10785. auto res = cli.Get(path);
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. EXPECT_EQ("bcdefghijk", res->body);
  10788. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10789. }
  10790. }
  10791. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10792. Server svr;
  10793. svr.set_default_headers({{"Hello", "World"}});
  10794. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10795. res.set_content("ok", "text/plain");
  10796. });
  10797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. listen_thread.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. Client cli("localhost", PORT);
  10805. auto res = cli.Get("/");
  10806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10807. EXPECT_EQ(StatusCode::OK_200, res->status);
  10808. EXPECT_EQ("ok", res->body);
  10809. EXPECT_EQ("World", res->get_header_value("Hello"));
  10810. }
  10811. #ifdef CPPHTTPLIB_SSL_ENABLED
  10812. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10814. ASSERT_TRUE(svr.is_valid());
  10815. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10816. std::this_thread::sleep_for(std::chrono::seconds(2));
  10817. res.set_content("a", "text/plain");
  10818. });
  10819. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10820. res.set_content("b", "text/plain");
  10821. });
  10822. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10823. auto se = detail::scope_exit([&] {
  10824. svr.stop();
  10825. listen_thread.join();
  10826. ASSERT_FALSE(svr.is_running());
  10827. });
  10828. svr.wait_until_ready();
  10829. SSLClient cli("localhost", PORT);
  10830. cli.enable_server_certificate_verification(false);
  10831. cli.set_keep_alive(true);
  10832. cli.set_read_timeout(std::chrono::seconds(1));
  10833. auto resa = cli.Get("/a");
  10834. ASSERT_TRUE(!resa);
  10835. EXPECT_EQ(Error::Read, resa.error());
  10836. auto resb = cli.Get("/b");
  10837. ASSERT_TRUE(resb);
  10838. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10839. EXPECT_EQ("b", resb->body);
  10840. }
  10841. // Closing an idle keep-alive connection sends close_notify and returns. The
  10842. // server must not wait for the client's close_notify: an idle client never
  10843. // sends one, so the worker would be held until the read timeout expires, and
  10844. // stop() would wait for it.
  10845. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10847. ASSERT_TRUE(svr.is_valid());
  10848. svr.set_keep_alive_timeout(1);
  10849. svr.set_read_timeout(10, 0);
  10850. svr.Get("/", [](const Request &, Response &res) {
  10851. res.set_content("ok", "text/plain");
  10852. });
  10853. auto port = svr.bind_to_any_port(HOST);
  10854. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10855. auto se = detail::scope_exit([&] {
  10856. if (listen_thread.joinable()) {
  10857. svr.stop();
  10858. listen_thread.join();
  10859. }
  10860. });
  10861. svr.wait_until_ready();
  10862. SSLClient cli(HOST, port);
  10863. cli.enable_server_certificate_verification(false);
  10864. cli.set_keep_alive(true);
  10865. auto res = cli.Get("/");
  10866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10867. EXPECT_EQ(StatusCode::OK_200, res->status);
  10868. // Stay idle past the keep-alive timeout so the server closes the connection.
  10869. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10870. auto start = std::chrono::steady_clock::now();
  10871. svr.stop();
  10872. listen_thread.join();
  10873. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10874. std::chrono::steady_clock::now() - start)
  10875. .count();
  10876. EXPECT_LT(elapsed, 3000);
  10877. }
  10878. #endif
  10879. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10880. protected:
  10881. ServerTestWithAI_PASSIVE()
  10882. : cli_(HOST, PORT)
  10883. #ifdef CPPHTTPLIB_SSL_ENABLED
  10884. ,
  10885. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10886. #endif
  10887. {
  10888. #ifdef CPPHTTPLIB_SSL_ENABLED
  10889. cli_.enable_server_certificate_verification(false);
  10890. #endif
  10891. }
  10892. virtual void SetUp() {
  10893. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10894. res.set_content("Hello World!", "text/plain");
  10895. });
  10896. t_ = thread(
  10897. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10898. svr_.wait_until_ready();
  10899. }
  10900. virtual void TearDown() {
  10901. svr_.stop();
  10902. t_.join();
  10903. }
  10904. #ifdef CPPHTTPLIB_SSL_ENABLED
  10905. SSLClient cli_;
  10906. SSLServer svr_;
  10907. #else
  10908. Client cli_;
  10909. Server svr_;
  10910. #endif
  10911. thread t_;
  10912. };
  10913. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10914. auto res = cli_.Get("/hi");
  10915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10916. EXPECT_EQ(StatusCode::OK_200, res->status);
  10917. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10918. EXPECT_EQ("Hello World!", res->body);
  10919. }
  10920. class ServerUpDownTest : public ::testing::Test {
  10921. protected:
  10922. ServerUpDownTest() : cli_(HOST, PORT) {}
  10923. virtual void SetUp() {
  10924. t_ = thread([&]() {
  10925. svr_.bind_to_any_port(HOST);
  10926. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10927. ASSERT_TRUE(svr_.listen_after_bind());
  10928. });
  10929. svr_.wait_until_ready();
  10930. }
  10931. virtual void TearDown() {
  10932. svr_.stop();
  10933. t_.join();
  10934. }
  10935. Client cli_;
  10936. Server svr_;
  10937. thread t_;
  10938. };
  10939. TEST_F(ServerUpDownTest, QuickStartStop) {
  10940. // Should not crash, especially when run with
  10941. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10942. }
  10943. class PayloadMaxLengthTest : public ::testing::Test {
  10944. protected:
  10945. PayloadMaxLengthTest()
  10946. : cli_(HOST, PORT)
  10947. #ifdef CPPHTTPLIB_SSL_ENABLED
  10948. ,
  10949. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10950. #endif
  10951. {
  10952. #ifdef CPPHTTPLIB_SSL_ENABLED
  10953. cli_.enable_server_certificate_verification(false);
  10954. #endif
  10955. }
  10956. virtual void SetUp() {
  10957. svr_.set_payload_max_length(8);
  10958. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content("test", "text/plain");
  10960. });
  10961. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10962. svr_.wait_until_ready();
  10963. }
  10964. virtual void TearDown() {
  10965. svr_.stop();
  10966. t_.join();
  10967. }
  10968. #ifdef CPPHTTPLIB_SSL_ENABLED
  10969. SSLClient cli_;
  10970. SSLServer svr_;
  10971. #else
  10972. Client cli_;
  10973. Server svr_;
  10974. #endif
  10975. thread t_;
  10976. };
  10977. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10978. auto res = cli_.Post("/test", "123456789", "text/plain");
  10979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10980. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10981. res = cli_.Post("/test", "12345678", "text/plain");
  10982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10983. EXPECT_EQ(StatusCode::OK_200, res->status);
  10984. }
  10985. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10986. // Test chunked encoding with payload exceeding the 8-byte limit
  10987. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10988. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10990. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10991. }
  10992. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10993. // Test chunked encoding with payload within the 8-byte limit
  10994. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10995. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10997. EXPECT_EQ(StatusCode::OK_200, res->status);
  10998. }
  10999. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11000. // Test using send_request to send chunked data exceeding payload limit
  11001. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11002. "Host: " +
  11003. std::string(HOST) + ":" + std::to_string(PORT) +
  11004. "\r\n"
  11005. "Transfer-Encoding: chunked\r\n"
  11006. "Connection: close\r\n"
  11007. "\r\n"
  11008. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11009. "0123456789\r\n"
  11010. "0\r\n" // End chunk
  11011. "\r\n";
  11012. std::string response;
  11013. bool result = send_request(1, chunked_request, &response);
  11014. if (!result) {
  11015. // If send_request fails, it might be because the server closed the
  11016. // connection due to payload limit enforcement, which is acceptable
  11017. SUCCEED()
  11018. << "Server rejected oversized chunked request (connection closed)";
  11019. } else {
  11020. // If we got a response, check if it's an error response or connection was
  11021. // closed early Short response length indicates connection was closed due to
  11022. // payload limit
  11023. if (response.length() <= 10) {
  11024. SUCCEED() << "Server closed connection for oversized chunked request";
  11025. } else {
  11026. // Check for error status codes
  11027. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11028. response.find("Payload Too Large") != std::string::npos ||
  11029. response.find("400") != std::string::npos);
  11030. }
  11031. }
  11032. }
  11033. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11034. // Test request without Content-Length header exceeding payload limit
  11035. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11036. "Host: " +
  11037. std::string(HOST) + ":" +
  11038. std::to_string(PORT) +
  11039. "\r\n"
  11040. "Connection: close\r\n"
  11041. "\r\n";
  11042. // Add payload exceeding the 8-byte limit
  11043. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11044. request_without_content_length += large_payload;
  11045. std::string response;
  11046. bool result = send_request(1, request_without_content_length, &response);
  11047. if (!result) {
  11048. // If send_request fails, server likely closed connection due to payload
  11049. // limit
  11050. SUCCEED() << "Server rejected oversized request without Content-Length "
  11051. "(connection closed)";
  11052. } else {
  11053. // Check if server responded with error or closed connection early
  11054. if (response.length() <= 10) {
  11055. SUCCEED() << "Server closed connection for oversized request without "
  11056. "Content-Length";
  11057. } else {
  11058. // Check for error status codes
  11059. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11060. response.find("Payload Too Large") != std::string::npos ||
  11061. response.find("400") != std::string::npos);
  11062. }
  11063. }
  11064. }
  11065. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11066. // Test request without Content-Length header within payload limit
  11067. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11068. "Host: " +
  11069. std::string(HOST) + ":" +
  11070. std::to_string(PORT) +
  11071. "\r\n"
  11072. "Connection: close\r\n"
  11073. "\r\n";
  11074. // Add payload within the 8-byte limit
  11075. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11076. request_without_content_length += small_payload;
  11077. std::string response;
  11078. bool result = send_request(1, request_without_content_length, &response);
  11079. // For requests without Content-Length, the server may have different behavior
  11080. // The key is that it should not reject due to payload limit for small
  11081. // payloads
  11082. if (result) {
  11083. // Check for any HTTP response (success or error, but not connection closed)
  11084. if (response.length() > 10) {
  11085. SUCCEED()
  11086. << "Server processed request without Content-Length within limit";
  11087. } else {
  11088. // Short response might indicate connection closed, which is acceptable
  11089. SUCCEED() << "Server closed connection for request without "
  11090. "Content-Length (acceptable behavior)";
  11091. }
  11092. } else {
  11093. // Connection failure might be due to protocol requirements
  11094. SUCCEED() << "Connection issue with request without Content-Length "
  11095. "(environment-specific)";
  11096. }
  11097. }
  11098. class LargePayloadMaxLengthTest : public ::testing::Test {
  11099. protected:
  11100. LargePayloadMaxLengthTest()
  11101. : cli_(HOST, PORT)
  11102. #ifdef CPPHTTPLIB_SSL_ENABLED
  11103. ,
  11104. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11105. #endif
  11106. {
  11107. #ifdef CPPHTTPLIB_SSL_ENABLED
  11108. cli_.enable_server_certificate_verification(false);
  11109. #endif
  11110. }
  11111. virtual void SetUp() {
  11112. // Set 10MB payload limit
  11113. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11114. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11115. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11116. res.set_content("Large payload test", "text/plain");
  11117. });
  11118. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11119. svr_.wait_until_ready();
  11120. }
  11121. virtual void TearDown() {
  11122. svr_.stop();
  11123. t_.join();
  11124. }
  11125. #ifdef CPPHTTPLIB_SSL_ENABLED
  11126. SSLClient cli_;
  11127. SSLServer svr_;
  11128. #else
  11129. Client cli_;
  11130. Server svr_;
  11131. #endif
  11132. thread t_;
  11133. };
  11134. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11135. // Test chunked encoding with payload within 10MB limit
  11136. std::string medium_payload(5 * 1024 * 1024,
  11137. 'A'); // 5MB payload, within 10MB limit
  11138. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11140. EXPECT_EQ(StatusCode::OK_200, res->status);
  11141. }
  11142. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11143. // Test chunked encoding with payload exceeding 10MB limit
  11144. std::string large_payload(12 * 1024 * 1024,
  11145. 'B'); // 12MB payload, exceeds 10MB limit
  11146. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11147. // Server may either return 413 or close the connection
  11148. if (res) {
  11149. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11150. } else {
  11151. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11152. }
  11153. }
  11154. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11155. // Test request without Content-Length header within 10MB limit
  11156. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11157. "Host: " +
  11158. std::string(HOST) + ":" +
  11159. std::to_string(PORT) +
  11160. "\r\n"
  11161. "Connection: close\r\n"
  11162. "\r\n";
  11163. // Add 1MB payload (within 10MB limit)
  11164. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11165. request_without_content_length += medium_payload;
  11166. std::string response;
  11167. bool result = send_request(5, request_without_content_length, &response);
  11168. if (result) {
  11169. // Should get a proper HTTP response for payloads within limit
  11170. if (response.length() > 10) {
  11171. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11172. "10MB limit";
  11173. } else {
  11174. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11175. "Content-Length)";
  11176. }
  11177. } else {
  11178. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11179. }
  11180. }
  11181. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11182. // Test request without Content-Length header exceeding 10MB limit
  11183. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11184. "Host: " +
  11185. std::string(HOST) + ":" +
  11186. std::to_string(PORT) +
  11187. "\r\n"
  11188. "Connection: close\r\n"
  11189. "\r\n";
  11190. // Add 12MB payload (exceeds 10MB limit)
  11191. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11192. request_without_content_length += large_payload;
  11193. std::string response;
  11194. bool result = send_request(10, request_without_content_length, &response);
  11195. if (!result) {
  11196. // Server should close connection due to payload limit
  11197. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11198. "(connection closed)";
  11199. } else {
  11200. // Check for error response
  11201. if (response.length() <= 10) {
  11202. SUCCEED()
  11203. << "Server closed connection for 12MB request exceeding 10MB limit";
  11204. } else {
  11205. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11206. response.find("Payload Too Large") != std::string::npos ||
  11207. response.find("400") != std::string::npos);
  11208. }
  11209. }
  11210. }
  11211. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11212. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11213. // path.
  11214. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11215. Server svr;
  11216. const size_t LIMIT = 64 * 1024; // 64KB
  11217. svr.set_payload_max_length(LIMIT);
  11218. size_t total = 0;
  11219. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11220. const ContentReader &content_reader) {
  11221. content_reader([&](const char * /*data*/, size_t len) {
  11222. total += len;
  11223. return true;
  11224. });
  11225. res.status = 200;
  11226. res.set_content("stream_ok", "text/plain");
  11227. });
  11228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. thread.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. // Prepare 256KB raw data and gzip-compress it
  11236. std::string raw(256 * 1024, 'A');
  11237. std::string gz;
  11238. {
  11239. z_stream zs{};
  11240. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11241. Z_DEFAULT_STRATEGY);
  11242. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11243. zs.avail_in = static_cast<uInt>(raw.size());
  11244. char outbuf[4096];
  11245. int ret;
  11246. do {
  11247. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11248. zs.avail_out = sizeof(outbuf);
  11249. ret = deflate(&zs, Z_FINISH);
  11250. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11251. } while (ret != Z_STREAM_END);
  11252. deflateEnd(&zs);
  11253. }
  11254. Client cli(HOST, PORT);
  11255. cli.set_connection_timeout(std::chrono::seconds(5));
  11256. Headers headers = {{"Content-Encoding", "gzip"}};
  11257. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11258. "application/octet-stream");
  11259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11260. // Server must reject oversized decompressed payloads with 413.
  11261. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11262. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11263. EXPECT_LE(total, LIMIT);
  11264. }
  11265. #ifndef CPPHTTPLIB_SSL_ENABLED
  11266. // For a request with neither Content-Length nor Transfer-Encoding, the
  11267. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11268. // compressed wire bytes straight to the ContentReader without ever routing
  11269. // them through the decompressor, so payload_max_length_ only bounded the
  11270. // compressed size on the wire, not the decompressed size.
  11271. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11272. Server svr;
  11273. const size_t LIMIT = 64 * 1024; // 64KB
  11274. svr.set_payload_max_length(LIMIT);
  11275. size_t total = 0;
  11276. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11277. const ContentReader &content_reader) {
  11278. content_reader([&](const char * /*data*/, size_t len) {
  11279. total += len;
  11280. return true;
  11281. });
  11282. res.status = 200;
  11283. res.set_content("stream_ok", "text/plain");
  11284. });
  11285. auto port = svr.bind_to_any_port(HOST);
  11286. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11287. auto se = detail::scope_exit([&] {
  11288. svr.stop();
  11289. thread.join();
  11290. ASSERT_FALSE(svr.is_running());
  11291. });
  11292. svr.wait_until_ready();
  11293. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11294. // StreamingGzipDecompression test above.
  11295. std::string raw(256 * 1024, 'A');
  11296. std::string gz;
  11297. {
  11298. httplib::detail::gzip_compressor compressor;
  11299. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11300. [&](const char *chunk, size_t len) {
  11301. gz.append(chunk, len);
  11302. return true;
  11303. });
  11304. ASSERT_TRUE(result);
  11305. }
  11306. // Send the gzip body over raw TCP with neither Content-Length nor
  11307. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11308. // kicks in.
  11309. std::string req = "POST /stream HTTP/1.1\r\n"
  11310. "Host: " +
  11311. std::string(HOST) + ":" + std::to_string(port) +
  11312. "\r\n"
  11313. "Content-Encoding: gzip\r\n"
  11314. "Connection: close\r\n"
  11315. "\r\n" +
  11316. gz;
  11317. std::string response;
  11318. ASSERT_TRUE(send_request(5, req, &response, port));
  11319. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11320. EXPECT_LE(total, LIMIT);
  11321. }
  11322. #endif
  11323. #endif
  11324. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11325. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11326. // the payload must be passed through untouched instead of being rejected.
  11327. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11328. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11329. Server svr;
  11330. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11331. res.set_content(body, "image/jpeg");
  11332. res.set_header("Content-Encoding", "UTF-8");
  11333. });
  11334. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11335. res.set_content(body, "image/jpeg");
  11336. res.set_header("Content-Encoding", "identity");
  11337. });
  11338. svr.Post("/echo", [](const Request &req, Response &res) {
  11339. res.set_content(req.body, "image/jpeg");
  11340. });
  11341. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11342. auto se = detail::scope_exit([&] {
  11343. svr.stop();
  11344. t.join();
  11345. ASSERT_FALSE(svr.is_running());
  11346. });
  11347. svr.wait_until_ready();
  11348. Client cli(HOST, PORT);
  11349. {
  11350. auto res = cli.Get("/image");
  11351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11352. EXPECT_EQ(StatusCode::OK_200, res->status);
  11353. EXPECT_EQ(body, res->body);
  11354. }
  11355. {
  11356. auto res = cli.Get("/identity");
  11357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11358. EXPECT_EQ(StatusCode::OK_200, res->status);
  11359. EXPECT_EQ(body, res->body);
  11360. }
  11361. {
  11362. // The same applies to a request body reaching the server.
  11363. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11364. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. EXPECT_EQ(StatusCode::OK_200, res->status);
  11367. EXPECT_EQ(body, res->body);
  11368. }
  11369. }
  11370. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11371. // gzip-encoded response even when the build has no zlib support.
  11372. static const char GZIPPED_HELLO_WORLD[] = {
  11373. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11374. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11375. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11376. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11377. // A content coding is a whole token, not something the field value merely
  11378. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11379. // as "fibre" look like Brotli, and turned a multi-coding value like
  11380. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11381. // it was never meant to see.
  11382. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11383. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11384. Server svr;
  11385. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11386. res.set_content(body, "image/jpeg");
  11387. res.set_header("Content-Encoding", "fibre");
  11388. });
  11389. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11390. res.set_content(body, "image/jpeg");
  11391. res.set_header("Content-Encoding", "gzip, br");
  11392. });
  11393. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11394. res.set_content(body, "image/jpeg");
  11395. res.set_header("Content-Encoding", "x-zstd-ish");
  11396. });
  11397. auto port = svr.bind_to_any_port(HOST);
  11398. thread t = thread([&]() { svr.listen_after_bind(); });
  11399. auto se = detail::scope_exit([&] {
  11400. svr.stop();
  11401. t.join();
  11402. ASSERT_FALSE(svr.is_running());
  11403. });
  11404. svr.wait_until_ready();
  11405. Client cli(HOST, port);
  11406. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11407. auto res = cli.Get(path);
  11408. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11409. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11410. // Not a coding we recognize, so the payload comes back untouched
  11411. EXPECT_EQ(body, res->body) << path;
  11412. }
  11413. }
  11414. // A content coding cpp-httplib recognizes but was not built with must be
  11415. // reported as such. Handing the still-compressed payload back to the caller
  11416. // would silently corrupt it.
  11417. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11418. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11419. Server svr;
  11420. // "image/jpeg" keeps the server from applying a content coding of its own,
  11421. // so the hand-crafted Content-Encoding below survives.
  11422. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11423. res.set_content(gzipped, "image/jpeg");
  11424. res.set_header("Content-Encoding", "gzip");
  11425. });
  11426. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11427. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11428. res.set_content(gzipped, "image/jpeg");
  11429. res.set_header("Content-Encoding", "GZIP");
  11430. });
  11431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11432. auto se = detail::scope_exit([&] {
  11433. svr.stop();
  11434. t.join();
  11435. ASSERT_FALSE(svr.is_running());
  11436. });
  11437. svr.wait_until_ready();
  11438. Client cli(HOST, PORT);
  11439. {
  11440. auto res = cli.Get("/gzipped");
  11441. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. EXPECT_EQ("Hello World!", res->body);
  11444. #else
  11445. ASSERT_FALSE(res);
  11446. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11447. #endif
  11448. }
  11449. {
  11450. // open_stream() must behave the same way.
  11451. auto handle = cli.open_stream("GET", "/gzipped");
  11452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11453. ASSERT_TRUE(handle.is_valid());
  11454. std::string received;
  11455. char buf[256];
  11456. ssize_t n;
  11457. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11458. received.append(buf, static_cast<size_t>(n));
  11459. }
  11460. EXPECT_EQ("Hello World!", received);
  11461. #else
  11462. EXPECT_FALSE(handle.is_valid());
  11463. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11464. #endif
  11465. }
  11466. {
  11467. // A differently-cased coding must not be mistaken for an unknown one, or
  11468. // the body would be handed back still compressed.
  11469. auto res = cli.Get("/gzipped-uppercase");
  11470. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11472. EXPECT_EQ("Hello World!", res->body);
  11473. #else
  11474. ASSERT_FALSE(res);
  11475. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11476. #endif
  11477. }
  11478. }
  11479. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11480. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11481. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11482. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11483. // body a second time and appending a second Content-Encoding field line, so
  11484. // clients that decode one coding per listed value handed back raw gzip bytes.
  11485. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11486. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11487. Server svr;
  11488. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11489. // keeps the server from applying a coding of its own.
  11490. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11491. res.set_content(gzipped, "text/plain");
  11492. res.set_header("Content-Encoding", "gzip");
  11493. });
  11494. auto port = svr.bind_to_any_port(HOST);
  11495. thread t = thread([&]() { svr.listen_after_bind(); });
  11496. auto se = detail::scope_exit([&] {
  11497. svr.stop();
  11498. t.join();
  11499. ASSERT_FALSE(svr.is_running());
  11500. });
  11501. svr.wait_until_ready();
  11502. Client cli(HOST, port);
  11503. Headers headers = {{"Accept-Encoding", "gzip"}};
  11504. auto res = cli.Get("/pre-gzipped", headers);
  11505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11506. EXPECT_EQ(StatusCode::OK_200, res->status);
  11507. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11508. EXPECT_EQ("Hello World!", res->body);
  11509. }
  11510. // A chunked provider settles its coding where the headers are written and
  11511. // reuses it at write time. Both ends of that have to hold: a handler's own
  11512. // Content-Encoding suppresses the coding, and a response without one is still
  11513. // compressed as it always was.
  11514. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11515. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11516. const std::string plain = "Hello World! Hello World! Hello World!";
  11517. Server svr;
  11518. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11519. res.set_header("Content-Encoding", "gzip");
  11520. res.set_chunked_content_provider(
  11521. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11522. sink.write(gzipped.data(), gzipped.size());
  11523. sink.done();
  11524. return true;
  11525. });
  11526. });
  11527. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11528. res.set_chunked_content_provider(
  11529. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11530. sink.write(plain.data(), plain.size());
  11531. sink.done();
  11532. return true;
  11533. });
  11534. });
  11535. auto port = svr.bind_to_any_port(HOST);
  11536. thread t = thread([&]() { svr.listen_after_bind(); });
  11537. auto se = detail::scope_exit([&] {
  11538. svr.stop();
  11539. t.join();
  11540. ASSERT_FALSE(svr.is_running());
  11541. });
  11542. svr.wait_until_ready();
  11543. Client cli(HOST, port);
  11544. Headers headers = {{"Accept-Encoding", "gzip"}};
  11545. {
  11546. auto res = cli.Get("/pre-gzipped", headers);
  11547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11548. EXPECT_EQ(StatusCode::OK_200, res->status);
  11549. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11550. EXPECT_EQ("Hello World!", res->body);
  11551. }
  11552. {
  11553. auto res = cli.Get("/negotiated", headers);
  11554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11555. EXPECT_EQ(StatusCode::OK_200, res->status);
  11556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11557. EXPECT_EQ(plain, res->body);
  11558. }
  11559. }
  11560. #endif
  11561. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11562. // the same message as the comma-joined one, so both have to be read the same
  11563. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11564. // single gzip coding, and a body the sender says was encoded twice was handed
  11565. // back after one pass, still compressed but presented as decoded.
  11566. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11567. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11568. Server svr;
  11569. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11570. res.set_content(body, "image/jpeg");
  11571. res.headers.emplace("Content-Encoding", "gzip");
  11572. res.headers.emplace("Content-Encoding", "gzip");
  11573. });
  11574. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11575. res.set_content(body, "image/jpeg");
  11576. res.set_header("Content-Encoding", "gzip, gzip");
  11577. });
  11578. auto port = svr.bind_to_any_port(HOST);
  11579. thread t = thread([&]() { svr.listen_after_bind(); });
  11580. auto se = detail::scope_exit([&] {
  11581. svr.stop();
  11582. t.join();
  11583. ASSERT_FALSE(svr.is_running());
  11584. });
  11585. svr.wait_until_ready();
  11586. Client cli(HOST, port);
  11587. // Two codings is not something cpp-httplib decodes, so both representations
  11588. // take the pass-through path rather than one of them being gunzipped once.
  11589. for (const char *path : {"/split", "/joined"}) {
  11590. auto res = cli.Get(path);
  11591. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11592. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11593. EXPECT_EQ(body, res->body) << path;
  11594. }
  11595. }
  11596. // Regression test for DoS vulnerability: a malicious server sending a response
  11597. // without Content-Length header must not cause unbounded memory consumption on
  11598. // the client side. The client should stop reading after a reasonable limit,
  11599. // similar to the server-side set_payload_max_length protection.
  11600. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11601. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11602. #ifndef _WIN32
  11603. signal(SIGPIPE, SIG_IGN);
  11604. #endif
  11605. auto server_thread = std::thread([] {
  11606. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11607. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11608. default_socket_options(srv);
  11609. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11610. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11611. sockaddr_in addr{};
  11612. addr.sin_family = AF_INET;
  11613. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11614. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11615. int opt = 1;
  11616. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11617. #ifdef _WIN32
  11618. reinterpret_cast<const char *>(&opt),
  11619. #else
  11620. &opt,
  11621. #endif
  11622. sizeof(opt));
  11623. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11624. ::listen(srv, 1);
  11625. sockaddr_in cli_addr{};
  11626. socklen_t cli_len = sizeof(cli_addr);
  11627. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11628. if (cli != INVALID_SOCKET) {
  11629. char buf[4096];
  11630. ::recv(cli, buf, sizeof(buf), 0);
  11631. // Malicious response: no Content-Length, no chunked encoding
  11632. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11633. "Connection: close\r\n"
  11634. "\r\n";
  11635. ::send(cli,
  11636. #ifdef _WIN32
  11637. static_cast<const char *>(response_header.c_str()),
  11638. static_cast<int>(response_header.size()),
  11639. #else
  11640. response_header.c_str(), response_header.size(),
  11641. #endif
  11642. 0);
  11643. // Send 10MB of data
  11644. std::string chunk(64 * 1024, 'A');
  11645. size_t total_sent = 0;
  11646. while (total_sent < MALICIOUS_DATA_SIZE) {
  11647. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11648. auto sent = ::send(cli,
  11649. #ifdef _WIN32
  11650. static_cast<const char *>(chunk.c_str()),
  11651. static_cast<int>(to_send),
  11652. #else
  11653. chunk.c_str(), to_send,
  11654. #endif
  11655. 0);
  11656. if (sent <= 0) break;
  11657. total_sent += static_cast<size_t>(sent);
  11658. }
  11659. detail::close_socket(cli);
  11660. }
  11661. detail::close_socket(srv);
  11662. });
  11663. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11664. size_t total_read = 0;
  11665. {
  11666. Client cli("127.0.0.1", PORT + 2);
  11667. cli.set_read_timeout(5, 0);
  11668. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11669. auto stream = cli.open_stream("GET", "/malicious");
  11670. ASSERT_TRUE(stream.is_valid());
  11671. char buffer[64 * 1024];
  11672. ssize_t n;
  11673. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11674. total_read += static_cast<size_t>(n);
  11675. }
  11676. } // StreamHandle and Client destroyed here, closing the socket
  11677. server_thread.join();
  11678. // With set_payload_max_length, the client must stop reading before consuming
  11679. // all 10MB. The read loop should be cut off at or near the configured limit.
  11680. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11681. << "Client read " << total_read << " bytes, exceeding the configured "
  11682. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11683. }
  11684. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11685. // the entire response body without truncation.
  11686. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11687. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11688. #ifndef _WIN32
  11689. signal(SIGPIPE, SIG_IGN);
  11690. #endif
  11691. auto server_thread = std::thread([] {
  11692. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11693. default_socket_options(srv);
  11694. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11695. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11696. sockaddr_in addr{};
  11697. addr.sin_family = AF_INET;
  11698. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11699. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11700. int opt = 1;
  11701. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11702. #ifdef _WIN32
  11703. reinterpret_cast<const char *>(&opt),
  11704. #else
  11705. &opt,
  11706. #endif
  11707. sizeof(opt));
  11708. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11709. ::listen(srv, 1);
  11710. sockaddr_in cli_addr{};
  11711. socklen_t cli_len = sizeof(cli_addr);
  11712. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11713. if (cli != INVALID_SOCKET) {
  11714. char buf[4096];
  11715. ::recv(cli, buf, sizeof(buf), 0);
  11716. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11717. "Connection: close\r\n"
  11718. "\r\n";
  11719. ::send(cli,
  11720. #ifdef _WIN32
  11721. static_cast<const char *>(response_header.c_str()),
  11722. static_cast<int>(response_header.size()),
  11723. #else
  11724. response_header.c_str(), response_header.size(),
  11725. #endif
  11726. 0);
  11727. std::string chunk(64 * 1024, 'A');
  11728. size_t total_sent = 0;
  11729. while (total_sent < DATA_SIZE) {
  11730. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11731. auto sent = ::send(cli,
  11732. #ifdef _WIN32
  11733. static_cast<const char *>(chunk.c_str()),
  11734. static_cast<int>(to_send),
  11735. #else
  11736. chunk.c_str(), to_send,
  11737. #endif
  11738. 0);
  11739. if (sent <= 0) break;
  11740. total_sent += static_cast<size_t>(sent);
  11741. }
  11742. #ifdef _WIN32
  11743. ::shutdown(cli, SD_SEND);
  11744. #else
  11745. ::shutdown(cli, SHUT_WR);
  11746. #endif
  11747. // Drain until the client closes its end, ensuring all data is delivered
  11748. char drain[1024];
  11749. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11750. detail::close_socket(cli);
  11751. }
  11752. detail::close_socket(srv);
  11753. });
  11754. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11755. size_t total_read = 0;
  11756. {
  11757. Client cli("127.0.0.1", PORT + 2);
  11758. cli.set_read_timeout(5, 0);
  11759. cli.set_payload_max_length(0); // 0 means no limit
  11760. auto stream = cli.open_stream("GET", "/data");
  11761. ASSERT_TRUE(stream.is_valid());
  11762. char buffer[64 * 1024];
  11763. ssize_t n;
  11764. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11765. total_read += static_cast<size_t>(n);
  11766. }
  11767. }
  11768. server_thread.join();
  11769. EXPECT_EQ(total_read, DATA_SIZE)
  11770. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11771. << " bytes without truncation, but only read " << total_read << " bytes.";
  11772. }
  11773. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11774. // enormous Content-Length must not cause the client to pre-allocate a huge
  11775. // response body buffer. The reservation is capped at payload_max_length_, and
  11776. // the read itself fails when the body exceeds the limit.
  11777. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11778. #ifndef _WIN32
  11779. signal(SIGPIPE, SIG_IGN);
  11780. #endif
  11781. auto server_thread = std::thread([] {
  11782. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11783. default_socket_options(srv);
  11784. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11786. sockaddr_in addr{};
  11787. addr.sin_family = AF_INET;
  11788. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11789. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11790. int opt = 1;
  11791. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11792. #ifdef _WIN32
  11793. reinterpret_cast<const char *>(&opt),
  11794. #else
  11795. &opt,
  11796. #endif
  11797. sizeof(opt));
  11798. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11799. ::listen(srv, 1);
  11800. sockaddr_in cli_addr{};
  11801. socklen_t cli_len = sizeof(cli_addr);
  11802. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11803. if (cli != INVALID_SOCKET) {
  11804. char buf[4096];
  11805. ::recv(cli, buf, sizeof(buf), 0);
  11806. // Malicious response: claim a 20GB body but send only a tiny payload.
  11807. std::string response = "HTTP/1.1 200 OK\r\n"
  11808. "Content-Length: 20000000000\r\n"
  11809. "\r\n"
  11810. "abc";
  11811. ::send(cli,
  11812. #ifdef _WIN32
  11813. static_cast<const char *>(response.c_str()),
  11814. static_cast<int>(response.size()),
  11815. #else
  11816. response.c_str(), response.size(),
  11817. #endif
  11818. 0);
  11819. detail::close_socket(cli);
  11820. }
  11821. detail::close_socket(srv);
  11822. });
  11823. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11824. {
  11825. Client cli("127.0.0.1", PORT + 2);
  11826. cli.set_read_timeout(5, 0);
  11827. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11828. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11829. // (server claims more bytes than payload_max_length permits), but it must
  11830. // not exhaust memory before getting there.
  11831. auto res = cli.Get("/malicious");
  11832. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11833. }
  11834. server_thread.join();
  11835. }
  11836. // Verify that content_receiver bypasses the default payload_max_length,
  11837. // allowing streaming downloads larger than 100MB without requiring an explicit
  11838. // set_payload_max_length call.
  11839. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11840. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11841. #ifndef _WIN32
  11842. signal(SIGPIPE, SIG_IGN);
  11843. #endif
  11844. auto server_thread = std::thread([] {
  11845. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11846. default_socket_options(srv);
  11847. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11848. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11849. sockaddr_in addr{};
  11850. addr.sin_family = AF_INET;
  11851. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11852. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11853. int opt = 1;
  11854. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11855. #ifdef _WIN32
  11856. reinterpret_cast<const char *>(&opt),
  11857. #else
  11858. &opt,
  11859. #endif
  11860. sizeof(opt));
  11861. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11862. ::listen(srv, 1);
  11863. sockaddr_in cli_addr{};
  11864. socklen_t cli_len = sizeof(cli_addr);
  11865. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11866. if (cli != INVALID_SOCKET) {
  11867. char buf[4096];
  11868. ::recv(cli, buf, sizeof(buf), 0);
  11869. // Response with Content-Length larger than default 100MB limit
  11870. auto content_length = std::to_string(DATA_SIZE);
  11871. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11872. "Content-Length: " +
  11873. content_length +
  11874. "\r\n"
  11875. "Connection: close\r\n"
  11876. "\r\n";
  11877. ::send(cli,
  11878. #ifdef _WIN32
  11879. static_cast<const char *>(response_header.c_str()),
  11880. static_cast<int>(response_header.size()),
  11881. #else
  11882. response_header.c_str(), response_header.size(),
  11883. #endif
  11884. 0);
  11885. std::string chunk(64 * 1024, 'A');
  11886. size_t total_sent = 0;
  11887. while (total_sent < DATA_SIZE) {
  11888. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11889. auto sent = ::send(cli,
  11890. #ifdef _WIN32
  11891. static_cast<const char *>(chunk.c_str()),
  11892. static_cast<int>(to_send),
  11893. #else
  11894. chunk.c_str(), to_send,
  11895. #endif
  11896. 0);
  11897. if (sent <= 0) break;
  11898. total_sent += static_cast<size_t>(sent);
  11899. }
  11900. detail::close_socket(cli);
  11901. }
  11902. detail::close_socket(srv);
  11903. });
  11904. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11905. size_t total_received = 0;
  11906. {
  11907. Client cli("127.0.0.1", PORT + 2);
  11908. cli.set_read_timeout(10, 0);
  11909. // Do NOT call set_payload_max_length — use the default 100MB limit
  11910. auto res =
  11911. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11912. total_received += data_length;
  11913. return true;
  11914. });
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. }
  11918. server_thread.join();
  11919. EXPECT_EQ(total_received, DATA_SIZE)
  11920. << "With content_receiver, the client should read all " << DATA_SIZE
  11921. << " bytes despite the default 100MB payload_max_length, but only read "
  11922. << total_received << " bytes.";
  11923. }
  11924. // Verify that an explicit set_payload_max_length smaller than the response is
  11925. // enforced even when a content_receiver is used.
  11926. TEST(ClientVulnerabilityTest,
  11927. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11928. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11929. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11930. #ifndef _WIN32
  11931. signal(SIGPIPE, SIG_IGN);
  11932. #endif
  11933. auto server_thread = std::thread([] {
  11934. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11935. default_socket_options(srv);
  11936. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11937. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11938. sockaddr_in addr{};
  11939. addr.sin_family = AF_INET;
  11940. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11941. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11942. int opt = 1;
  11943. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11944. #ifdef _WIN32
  11945. reinterpret_cast<const char *>(&opt),
  11946. #else
  11947. &opt,
  11948. #endif
  11949. sizeof(opt));
  11950. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11951. ::listen(srv, 1);
  11952. sockaddr_in cli_addr{};
  11953. socklen_t cli_len = sizeof(cli_addr);
  11954. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11955. if (cli != INVALID_SOCKET) {
  11956. char buf[4096];
  11957. ::recv(cli, buf, sizeof(buf), 0);
  11958. auto content_length = std::to_string(DATA_SIZE);
  11959. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11960. "Content-Length: " +
  11961. content_length +
  11962. "\r\n"
  11963. "Connection: close\r\n"
  11964. "\r\n";
  11965. ::send(cli,
  11966. #ifdef _WIN32
  11967. static_cast<const char *>(response_header.c_str()),
  11968. static_cast<int>(response_header.size()),
  11969. #else
  11970. response_header.c_str(), response_header.size(),
  11971. #endif
  11972. 0);
  11973. std::string chunk(64 * 1024, 'A');
  11974. size_t total_sent = 0;
  11975. while (total_sent < DATA_SIZE) {
  11976. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11977. auto sent = ::send(cli,
  11978. #ifdef _WIN32
  11979. static_cast<const char *>(chunk.c_str()),
  11980. static_cast<int>(to_send),
  11981. #else
  11982. chunk.c_str(), to_send,
  11983. #endif
  11984. 0);
  11985. if (sent <= 0) break;
  11986. total_sent += static_cast<size_t>(sent);
  11987. }
  11988. detail::close_socket(cli);
  11989. }
  11990. detail::close_socket(srv);
  11991. });
  11992. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11993. size_t total_received = 0;
  11994. {
  11995. Client cli("127.0.0.1", PORT + 2);
  11996. cli.set_read_timeout(10, 0);
  11997. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11998. auto res =
  11999. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12000. total_received += data_length;
  12001. return true;
  12002. });
  12003. // Should fail because 200MB exceeds the explicit 150MB limit
  12004. EXPECT_FALSE(res);
  12005. }
  12006. server_thread.join();
  12007. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12008. << "Client with content_receiver should respect the explicit "
  12009. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12010. << total_received << " bytes.";
  12011. }
  12012. // Verify that an explicit set_payload_max_length larger than the response
  12013. // allows the content_receiver to read all data successfully.
  12014. TEST(ClientVulnerabilityTest,
  12015. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12016. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12017. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12018. #ifndef _WIN32
  12019. signal(SIGPIPE, SIG_IGN);
  12020. #endif
  12021. auto server_thread = std::thread([] {
  12022. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12023. default_socket_options(srv);
  12024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12025. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12026. sockaddr_in addr{};
  12027. addr.sin_family = AF_INET;
  12028. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12029. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12030. int opt = 1;
  12031. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12032. #ifdef _WIN32
  12033. reinterpret_cast<const char *>(&opt),
  12034. #else
  12035. &opt,
  12036. #endif
  12037. sizeof(opt));
  12038. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12039. ::listen(srv, 1);
  12040. sockaddr_in cli_addr{};
  12041. socklen_t cli_len = sizeof(cli_addr);
  12042. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12043. if (cli != INVALID_SOCKET) {
  12044. char buf[4096];
  12045. ::recv(cli, buf, sizeof(buf), 0);
  12046. auto content_length = std::to_string(DATA_SIZE);
  12047. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12048. "Content-Length: " +
  12049. content_length +
  12050. "\r\n"
  12051. "Connection: close\r\n"
  12052. "\r\n";
  12053. ::send(cli,
  12054. #ifdef _WIN32
  12055. static_cast<const char *>(response_header.c_str()),
  12056. static_cast<int>(response_header.size()),
  12057. #else
  12058. response_header.c_str(), response_header.size(),
  12059. #endif
  12060. 0);
  12061. std::string chunk(64 * 1024, 'A');
  12062. size_t total_sent = 0;
  12063. while (total_sent < DATA_SIZE) {
  12064. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12065. auto sent = ::send(cli,
  12066. #ifdef _WIN32
  12067. static_cast<const char *>(chunk.c_str()),
  12068. static_cast<int>(to_send),
  12069. #else
  12070. chunk.c_str(), to_send,
  12071. #endif
  12072. 0);
  12073. if (sent <= 0) break;
  12074. total_sent += static_cast<size_t>(sent);
  12075. }
  12076. #ifdef _WIN32
  12077. ::shutdown(cli, SD_SEND);
  12078. #else
  12079. ::shutdown(cli, SHUT_WR);
  12080. #endif
  12081. char drain[1024];
  12082. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12083. detail::close_socket(cli);
  12084. }
  12085. detail::close_socket(srv);
  12086. });
  12087. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12088. size_t total_received = 0;
  12089. {
  12090. Client cli("127.0.0.1", PORT + 2);
  12091. cli.set_read_timeout(10, 0);
  12092. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12093. auto res =
  12094. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12095. total_received += data_length;
  12096. return true;
  12097. });
  12098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12099. EXPECT_EQ(StatusCode::OK_200, res->status);
  12100. }
  12101. server_thread.join();
  12102. EXPECT_EQ(total_received, DATA_SIZE)
  12103. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12104. << " bytes (larger than " << DATA_SIZE
  12105. << " bytes response), content_receiver should read all data, but only "
  12106. "read "
  12107. << total_received << " bytes.";
  12108. }
  12109. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12110. // Regression test for "zip bomb" attack on the client side: a malicious server
  12111. // sends a small gzip-compressed response that decompresses to a huge payload.
  12112. // The client must enforce payload_max_length on the decompressed size.
  12113. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12114. constexpr size_t DECOMPRESSED_SIZE =
  12115. 10 * 1024 * 1024; // 10MB after decompression
  12116. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12117. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12118. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12119. std::string compressed;
  12120. {
  12121. httplib::detail::gzip_compressor compressor;
  12122. bool ok =
  12123. compressor.compress(uncompressed.data(), uncompressed.size(),
  12124. /*last=*/true, [&](const char *buf, size_t len) {
  12125. compressed.append(buf, len);
  12126. return true;
  12127. });
  12128. ASSERT_TRUE(ok);
  12129. }
  12130. // Sanity: compressed data should be much smaller than the decompressed size
  12131. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12132. #ifndef _WIN32
  12133. signal(SIGPIPE, SIG_IGN);
  12134. #endif
  12135. // Set up the listening socket in the main thread so the server is guaranteed
  12136. // to be ready before the client connects (eliminates race condition).
  12137. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12138. default_socket_options(srv);
  12139. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12140. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12141. sockaddr_in addr{};
  12142. addr.sin_family = AF_INET;
  12143. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12144. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12145. int opt = 1;
  12146. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12147. #ifdef _WIN32
  12148. reinterpret_cast<const char *>(&opt),
  12149. #else
  12150. &opt,
  12151. #endif
  12152. sizeof(opt));
  12153. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12154. ASSERT_EQ(0, ::listen(srv, 1));
  12155. auto server_thread = std::thread([&compressed, srv] {
  12156. sockaddr_in cli_addr{};
  12157. socklen_t cli_len = sizeof(cli_addr);
  12158. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12159. if (cli != INVALID_SOCKET) {
  12160. // Read the full HTTP request (until \r\n\r\n)
  12161. char buf[4096];
  12162. size_t total = 0;
  12163. while (total < sizeof(buf)) {
  12164. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12165. if (n <= 0) break;
  12166. total += static_cast<size_t>(n);
  12167. // Check for end of headers
  12168. if (total >= 4) {
  12169. std::string req(buf, total);
  12170. if (req.find("\r\n\r\n") != std::string::npos) break;
  12171. }
  12172. }
  12173. // Malicious response: gzip-compressed body, no Content-Length
  12174. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12175. "Content-Encoding: gzip\r\n"
  12176. "Connection: close\r\n"
  12177. "\r\n";
  12178. ::send(cli,
  12179. #ifdef _WIN32
  12180. static_cast<const char *>(response_header.c_str()),
  12181. static_cast<int>(response_header.size()),
  12182. #else
  12183. response_header.c_str(), response_header.size(),
  12184. #endif
  12185. 0);
  12186. // Send the compressed payload (small on the wire, huge when decompressed)
  12187. size_t total_sent = 0;
  12188. while (total_sent < compressed.size()) {
  12189. auto to_send = std::min(compressed.size() - total_sent,
  12190. static_cast<size_t>(64 * 1024));
  12191. auto sent =
  12192. ::send(cli,
  12193. #ifdef _WIN32
  12194. static_cast<const char *>(compressed.c_str() + total_sent),
  12195. static_cast<int>(to_send),
  12196. #else
  12197. compressed.c_str() + total_sent, to_send,
  12198. #endif
  12199. 0);
  12200. if (sent <= 0) break;
  12201. total_sent += static_cast<size_t>(sent);
  12202. }
  12203. detail::close_socket(cli);
  12204. }
  12205. });
  12206. auto se = detail::scope_exit([&] {
  12207. detail::close_socket(srv);
  12208. server_thread.join();
  12209. });
  12210. size_t total_decompressed = 0;
  12211. {
  12212. Client cli("127.0.0.1", PORT + 3);
  12213. cli.set_read_timeout(5, 0);
  12214. cli.set_decompress(true);
  12215. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12216. auto stream = cli.open_stream("GET", "/zipbomb");
  12217. ASSERT_TRUE(stream.is_valid());
  12218. char buffer[64 * 1024];
  12219. ssize_t n;
  12220. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12221. total_decompressed += static_cast<size_t>(n);
  12222. }
  12223. }
  12224. // The decompressed size must be capped by payload_max_length. Without
  12225. // protection, the client would decompress the full 10MB from a tiny
  12226. // compressed payload, enabling a zip bomb DoS attack.
  12227. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12228. << "Client decompressed " << total_decompressed
  12229. << " bytes from a gzip response. The decompressed size should be "
  12230. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12231. }
  12232. #endif
  12233. TEST(HostAndPortPropertiesTest, NoSSL) {
  12234. httplib::Client cli("www.google.com", 1234);
  12235. ASSERT_EQ("www.google.com", cli.host());
  12236. ASSERT_EQ(1234, cli.port());
  12237. }
  12238. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12239. httplib::Client cli("www.google.com:1234");
  12240. ASSERT_EQ("www.google.com", cli.host());
  12241. ASSERT_EQ(1234, cli.port());
  12242. }
  12243. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12244. // Port number that overflows int — should not crash, client becomes invalid
  12245. httplib::Client cli("http://www.google.com:99999999999999999999");
  12246. ASSERT_FALSE(cli.is_valid());
  12247. }
  12248. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12249. // Port 99999 exceeds valid range (1-65535) — should not crash
  12250. httplib::Client cli("http://www.google.com:99999");
  12251. ASSERT_FALSE(cli.is_valid());
  12252. }
  12253. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12254. httplib::Client cli("http://www.google.com:80abc");
  12255. ASSERT_FALSE(cli.is_valid());
  12256. }
  12257. #ifdef CPPHTTPLIB_SSL_ENABLED
  12258. TEST(HostAndPortPropertiesTest, SSL) {
  12259. httplib::SSLClient cli("www.google.com");
  12260. ASSERT_EQ("www.google.com", cli.host());
  12261. ASSERT_EQ(443, cli.port());
  12262. }
  12263. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12264. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12265. std::string cert;
  12266. read_file(CA_CERT_FILE, cert);
  12267. httplib::SSLClient httplib_client("www.google.com");
  12268. // Load CA store first time
  12269. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12270. // Load CA store second time (update)
  12271. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12272. // Verify client is still valid and can make connections
  12273. httplib_client.enable_server_certificate_verification(true);
  12274. auto res = httplib_client.Get("/");
  12275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12276. // Google may return 200 or 301 depending on various factors
  12277. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12278. res->status == StatusCode::MovedPermanently_301);
  12279. }
  12280. TEST(SSLClientTest, ServerNameIndication_Online) {
  12281. auto host = "httpbingo.org";
  12282. auto path = std::string{"/get"};
  12283. SSLClient cli(host, 443);
  12284. auto res = cli.Get(path);
  12285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12286. ASSERT_EQ(StatusCode::OK_200, res->status);
  12287. }
  12288. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12289. // Use a site that will cause SSL verification failure due to self-signed cert
  12290. SSLClient cli("self-signed.badssl.com", 443);
  12291. cli.enable_server_certificate_verification(true);
  12292. auto res = cli.Get("/");
  12293. ASSERT_TRUE(!res);
  12294. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12295. // Verify backend error is captured for SSLServerVerification
  12296. // This occurs when certificate verification fails
  12297. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12298. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12299. EXPECT_NE(0UL, res.ssl_backend_error());
  12300. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12301. // For OpenSSL, ssl_error is 0 for verification errors
  12302. EXPECT_EQ(0, res.ssl_error());
  12303. #if !defined(_WIN32) || \
  12304. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12305. // On non-Windows or when Windows Schannel is disabled, the error comes
  12306. // from OpenSSL's verification
  12307. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12308. res.ssl_backend_error());
  12309. #endif
  12310. #endif
  12311. }
  12312. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12313. // Use a site where hostname doesn't match the certificate
  12314. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12315. SSLClient cli("wrong.host.badssl.com", 443);
  12316. cli.enable_server_certificate_verification(true);
  12317. cli.enable_server_hostname_verification(true);
  12318. auto res = cli.Get("/");
  12319. ASSERT_TRUE(!res);
  12320. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12321. // Verify backend error is captured for hostname verification failure
  12322. EXPECT_NE(0UL, res.ssl_backend_error());
  12323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12324. // For OpenSSL, ssl_error is 0 for verification errors
  12325. EXPECT_EQ(0, res.ssl_error());
  12326. #if !defined(_WIN32) || \
  12327. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12328. // On non-Windows or when Windows Schannel is disabled, the error comes
  12329. // from OpenSSL's hostname verification
  12330. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12331. res.ssl_backend_error());
  12332. #endif
  12333. #endif
  12334. }
  12335. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12336. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12337. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12338. SSLClient cli("www.google.com", 443);
  12339. cli.enable_server_certificate_verification(true);
  12340. auto res = cli.Get("/");
  12341. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12342. }
  12343. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12344. SSLClient cli("www.google.com", 443);
  12345. cli.enable_server_certificate_verification(true);
  12346. cli.enable_windows_certificate_verification(false);
  12347. auto res = cli.Get("/");
  12348. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12349. }
  12350. // The server sends an intermediate cross-signed by a root Windows trusts,
  12351. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12352. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12353. SSLClient cli("accounts.spotify.com", 443);
  12354. auto res = cli.Get("/");
  12355. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12356. << " ssl_backend_error=" << res.ssl_backend_error();
  12357. }
  12358. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12359. // policy status, which no backend reports for a self-signed certificate.
  12360. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12361. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12362. ASSERT_TRUE(svr.is_valid());
  12363. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12364. auto se = detail::scope_exit([&] {
  12365. svr.stop();
  12366. t.join();
  12367. ASSERT_FALSE(svr.is_running());
  12368. });
  12369. svr.wait_until_ready();
  12370. SSLClient cli("127.0.0.1", PORT);
  12371. cli.set_connection_timeout(30);
  12372. auto res = cli.Get("/");
  12373. ASSERT_FALSE(res);
  12374. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12375. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12376. }
  12377. #endif
  12378. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12379. Client cli("https://google.com");
  12380. auto res = cli.Get("/");
  12381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12382. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12383. }
  12384. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12385. SSLClient cli("google.com");
  12386. cli.set_ca_cert_path(CA_CERT_FILE);
  12387. auto res = cli.Get("/");
  12388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12389. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12390. }
  12391. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12392. SSLClient cli("google.com");
  12393. cli.enable_server_certificate_verification(true);
  12394. cli.set_ca_cert_path("hello");
  12395. auto res = cli.Get("/");
  12396. ASSERT_TRUE(!res);
  12397. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12398. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12399. // should be set
  12400. EXPECT_EQ(0, res.ssl_error());
  12401. // Verify backend error is captured for SSLLoadingCerts
  12402. // This error occurs when loading CA certificates fails
  12403. EXPECT_NE(0UL, res.ssl_backend_error());
  12404. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12405. // OpenSSL specific error codes:
  12406. // > openssl errstr 0x80000002
  12407. // error:80000002:system library::No such file or directory
  12408. // > openssl errstr 0xA000126
  12409. // error:0A000126:SSL routines::unexpected eof while reading
  12410. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12411. res.ssl_backend_error() == 0xA000126);
  12412. #endif
  12413. }
  12414. TEST(SSLClientTest, ServerCertificateVerification4) {
  12415. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12416. ASSERT_TRUE(svr.is_valid());
  12417. svr.Get("/test", [&](const Request &, Response &res) {
  12418. res.set_content("test", "text/plain");
  12419. svr.stop();
  12420. ASSERT_TRUE(true);
  12421. });
  12422. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12423. auto se = detail::scope_exit([&] {
  12424. t.join();
  12425. ASSERT_FALSE(svr.is_running());
  12426. });
  12427. svr.wait_until_ready();
  12428. SSLClient cli("127.0.0.1", PORT);
  12429. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12430. cli.enable_server_certificate_verification(true);
  12431. cli.set_connection_timeout(30);
  12432. auto res = cli.Get("/test");
  12433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12434. ASSERT_EQ(StatusCode::OK_200, res->status);
  12435. }
  12436. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12437. std::string cert;
  12438. read_file(CA_CERT_FILE, cert);
  12439. SSLClient cli("google.com");
  12440. cli.load_ca_cert_store(cert.data(), cert.size());
  12441. const auto res = cli.Get("/");
  12442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12443. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12444. }
  12445. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12446. // clang-format off
  12447. static constexpr char cert[] =
  12448. "GlobalSign Root CA\n"
  12449. "==================\n"
  12450. "-----BEGIN CERTIFICATE-----\n"
  12451. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12452. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12453. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12454. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12455. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12456. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12457. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12458. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12459. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12460. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12461. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12462. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12463. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12464. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12465. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12466. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12467. "-----END CERTIFICATE-----\n";
  12468. // clang-format on
  12469. SSLClient cli("google.com");
  12470. cli.load_ca_cert_store(cert, sizeof(cert));
  12471. const auto res = cli.Get("/");
  12472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12473. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12474. }
  12475. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12476. SSLClient cli("www.youtube.com");
  12477. cli.set_ca_cert_path(CA_CERT_FILE);
  12478. cli.enable_server_certificate_verification(true);
  12479. cli.set_follow_location(true);
  12480. auto res = cli.Get("/");
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. ASSERT_EQ(StatusCode::OK_200, res->status);
  12483. }
  12484. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12485. SSLClient cli("wWw.YouTube.Com");
  12486. cli.set_ca_cert_path(CA_CERT_FILE);
  12487. cli.enable_server_certificate_verification(true);
  12488. cli.enable_server_hostname_verification(true);
  12489. cli.set_follow_location(true);
  12490. auto res = cli.Get("/");
  12491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12492. ASSERT_EQ(StatusCode::OK_200, res->status);
  12493. }
  12494. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12495. SSLClient cli("gOoGlE.COm");
  12496. cli.enable_server_certificate_verification(true);
  12497. cli.enable_server_hostname_verification(true);
  12498. cli.set_follow_location(true);
  12499. auto res = cli.Get("/");
  12500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12501. ASSERT_EQ(StatusCode::OK_200, res->status);
  12502. }
  12503. TEST(SSLClientTest, Issue2004_Online) {
  12504. Client client("https://google.com");
  12505. client.set_follow_location(true);
  12506. auto res = client.Get("/");
  12507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12508. ASSERT_EQ(StatusCode::OK_200, res->status);
  12509. auto body = res->body;
  12510. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12511. }
  12512. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12513. // Create SSLClient with invalid cert/key to make is_valid() return false
  12514. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12515. "nonexistent_key.pem");
  12516. // is_valid() should be false due to cert loading failure
  12517. ASSERT_FALSE(cli.is_valid());
  12518. auto res = cli.Get("/");
  12519. ASSERT_FALSE(res);
  12520. EXPECT_EQ(Error::SSLConnection, res.error());
  12521. }
  12522. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12523. // Test for Issue #2251: SSL error not properly reported when client cert
  12524. // and key paths are swapped or mismatched
  12525. // This simulates the scenario where user accidentally swaps the cert and key
  12526. // files
  12527. // Using client cert file as private key and vice versa (completely wrong)
  12528. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12529. // Should fail validation due to cert/key mismatch
  12530. ASSERT_FALSE(cli.is_valid());
  12531. // Attempt to make a request should fail with proper error
  12532. auto res = cli.Get("/");
  12533. ASSERT_FALSE(res);
  12534. EXPECT_EQ(Error::SSLConnection, res.error());
  12535. // SSL error should be recorded in the Result object (this is the key fix for
  12536. // Issue #2251)
  12537. auto backend_error = res.ssl_backend_error();
  12538. EXPECT_NE(0u, backend_error);
  12539. }
  12540. // Tests cert/key mismatch detection at the TLS context level
  12541. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12542. // Test that using mismatched cert/key causes connection failure.
  12543. // We verify this at the SSLClient level rather than through internal
  12544. // TLS API functions.
  12545. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12546. cli.enable_server_certificate_verification(false);
  12547. cli.set_connection_timeout(2);
  12548. // The mismatch should cause a connection or handshake error
  12549. auto res = cli.Get("/test");
  12550. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12551. // Either way, the request should fail
  12552. EXPECT_FALSE(res);
  12553. }
  12554. #endif
  12555. #if 0
  12556. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12557. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12558. ASSERT_TRUE(cli != nullptr);
  12559. cli->set_address_family(AF_INET6);
  12560. cli->set_interface("en0");
  12561. auto res = cli->Get("/get");
  12562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12563. ASSERT_EQ(StatusCode::OK_200, res->status);
  12564. }
  12565. #endif
  12566. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12567. #ifdef CPPHTTPLIB_SSL_ENABLED
  12568. void ClientCertPresent(
  12569. const std::string &client_cert_file,
  12570. const std::string &client_private_key_file,
  12571. const std::string &client_encrypted_private_key_pass = std::string()) {
  12572. using namespace httplib::tls;
  12573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12574. CLIENT_CA_CERT_DIR);
  12575. ASSERT_TRUE(svr.is_valid());
  12576. svr.Get("/test", [&](const Request &req, Response &res) {
  12577. res.set_content("test", "text/plain");
  12578. auto cert = req.peer_cert();
  12579. ASSERT_TRUE(static_cast<bool>(cert));
  12580. std::string common_name = cert.subject_cn();
  12581. EXPECT_EQ("Common Name", common_name);
  12582. });
  12583. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12584. auto se = detail::scope_exit([&] {
  12585. svr.stop();
  12586. t.join();
  12587. ASSERT_FALSE(svr.is_running());
  12588. });
  12589. svr.wait_until_ready();
  12590. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12591. client_encrypted_private_key_pass);
  12592. cli.enable_server_certificate_verification(false);
  12593. cli.set_connection_timeout(30);
  12594. auto res = cli.Get("/test");
  12595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12596. ASSERT_EQ(StatusCode::OK_200, res->status);
  12597. }
  12598. TEST(SSLClientServerTest, ClientCertPresent) {
  12599. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12600. }
  12601. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12602. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12603. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12604. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12605. }
  12606. // PEM memory-based constructor tests (works with all TLS backends)
  12607. void PemMemoryClientCertPresent(
  12608. const std::string &client_cert_file,
  12609. const std::string &client_private_key_file,
  12610. const std::string &client_encrypted_private_key_pass = std::string()) {
  12611. // Read PEM files into memory
  12612. std::string server_cert_pem, server_key_pem;
  12613. std::string client_ca_pem;
  12614. std::string client_cert_pem, client_key_pem;
  12615. read_file(SERVER_CERT_FILE, server_cert_pem);
  12616. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12617. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12618. read_file(client_cert_file, client_cert_pem);
  12619. read_file(client_private_key_file, client_key_pem);
  12620. // Create server with PEM memory
  12621. SSLServer::PemMemory server_pem = {
  12622. server_cert_pem.c_str(),
  12623. server_cert_pem.size(),
  12624. server_key_pem.c_str(),
  12625. server_key_pem.size(),
  12626. client_ca_pem.c_str(),
  12627. client_ca_pem.size(),
  12628. nullptr // no password for server key
  12629. };
  12630. SSLServer svr(server_pem);
  12631. ASSERT_TRUE(svr.is_valid());
  12632. svr.Get("/test", [&](const Request &, Response &res) {
  12633. res.set_content("test", "text/plain");
  12634. });
  12635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12636. auto se = detail::scope_exit([&] {
  12637. svr.stop();
  12638. t.join();
  12639. ASSERT_FALSE(svr.is_running());
  12640. });
  12641. svr.wait_until_ready();
  12642. // Create client with PEM memory
  12643. const char *password = client_encrypted_private_key_pass.empty()
  12644. ? nullptr
  12645. : client_encrypted_private_key_pass.c_str();
  12646. SSLClient::PemMemory client_pem = {
  12647. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12648. client_key_pem.size(), password};
  12649. SSLClient cli(HOST, PORT, client_pem);
  12650. cli.enable_server_certificate_verification(false);
  12651. cli.set_connection_timeout(30);
  12652. auto res = cli.Get("/test");
  12653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12654. ASSERT_EQ(StatusCode::OK_200, res->status);
  12655. }
  12656. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12657. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12658. }
  12659. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12660. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12661. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12662. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12663. }
  12664. TEST(SSLClientServerTest, ClientCertMissing) {
  12665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12666. CLIENT_CA_CERT_DIR);
  12667. ASSERT_TRUE(svr.is_valid());
  12668. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12669. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12670. auto se = detail::scope_exit([&] {
  12671. svr.stop();
  12672. t.join();
  12673. ASSERT_FALSE(svr.is_running());
  12674. });
  12675. svr.wait_until_ready();
  12676. SSLClient cli(HOST, PORT);
  12677. cli.set_connection_timeout(30);
  12678. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12679. // the chain check on Windows, so the result does not depend on the order.
  12680. cli.enable_server_hostname_verification(false);
  12681. auto res = cli.Get("/test");
  12682. ASSERT_TRUE(!res);
  12683. // When client cert is missing and server requires it, connection fails
  12684. // Error type depends on backend implementation
  12685. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12686. res.error() == Error::SSLConnection);
  12687. // Verify backend error is captured
  12688. // Note: This test may have different error codes depending on the exact
  12689. // verification failure
  12690. EXPECT_NE(0UL, res.ssl_backend_error());
  12691. }
  12692. TEST(SSLClientServerTest, TrustDirOptional) {
  12693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12694. ASSERT_TRUE(svr.is_valid());
  12695. svr.Get("/test", [&](const Request &, Response &res) {
  12696. res.set_content("test", "text/plain");
  12697. });
  12698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12699. auto se = detail::scope_exit([&] {
  12700. svr.stop();
  12701. t.join();
  12702. ASSERT_FALSE(svr.is_running());
  12703. });
  12704. svr.wait_until_ready();
  12705. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12706. cli.enable_server_certificate_verification(false);
  12707. cli.set_connection_timeout(30);
  12708. auto res = cli.Get("/test");
  12709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12710. ASSERT_EQ(StatusCode::OK_200, res->status);
  12711. }
  12712. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12713. class NoListenSSLServer : public SSLServer {
  12714. public:
  12715. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12716. const char *client_ca_cert_file_path,
  12717. const char *client_ca_cert_dir_path = nullptr)
  12718. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12719. client_ca_cert_dir_path),
  12720. stop_(false) {}
  12721. std::atomic_bool stop_;
  12722. private:
  12723. bool process_and_close_socket(socket_t /*sock*/) override {
  12724. // Don't create SSL context
  12725. while (!stop_.load()) {
  12726. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12727. }
  12728. return true;
  12729. }
  12730. };
  12731. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12732. CLIENT_CA_CERT_FILE);
  12733. ASSERT_TRUE(svr.is_valid());
  12734. svr.Get("/test", [&](const Request &, Response &res) {
  12735. res.set_content("test", "text/plain");
  12736. });
  12737. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12738. auto se = detail::scope_exit([&] {
  12739. svr.stop_ = true;
  12740. svr.stop();
  12741. t.join();
  12742. ASSERT_FALSE(svr.is_running());
  12743. });
  12744. svr.wait_until_ready();
  12745. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12746. cli.enable_server_certificate_verification(false);
  12747. cli.set_connection_timeout(1);
  12748. auto res = cli.Get("/test");
  12749. ASSERT_TRUE(!res);
  12750. EXPECT_EQ(Error::SSLConnection, res.error());
  12751. // Timeout results in WantRead error code (maps to backend-specific value)
  12752. EXPECT_NE(0, res.ssl_error());
  12753. }
  12754. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12755. // Test SSLServer with client certificate verification using the standard
  12756. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12758. CLIENT_CA_CERT_DIR);
  12759. ASSERT_TRUE(svr.is_valid());
  12760. svr.Get("/test", [&](const Request &req, Response &res) {
  12761. res.set_content("test", "text/plain");
  12762. auto cert = req.peer_cert();
  12763. ASSERT_TRUE(static_cast<bool>(cert));
  12764. auto common_name = cert.subject_cn();
  12765. EXPECT_EQ("Common Name", common_name);
  12766. });
  12767. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. t.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12775. cli.enable_server_certificate_verification(false);
  12776. cli.set_connection_timeout(30);
  12777. auto res = cli.Get("/test");
  12778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12779. ASSERT_EQ(StatusCode::OK_200, res->status);
  12780. }
  12781. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12782. // Verifies that wildcard matching and exact matching work consistently
  12783. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12784. using namespace httplib::tls;
  12785. // We need a running server to test against
  12786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12787. ASSERT_TRUE(svr.is_valid());
  12788. svr.Get("/test", [](const Request &, Response &res) {
  12789. res.set_content("ok", "text/plain");
  12790. });
  12791. thread t([&]() { svr.listen(HOST, PORT); });
  12792. auto se = detail::scope_exit([&] {
  12793. svr.stop();
  12794. t.join();
  12795. });
  12796. svr.wait_until_ready();
  12797. bool verify_callback_called = false;
  12798. bool verify_result_wrong = false;
  12799. SSLClient cli(HOST, PORT);
  12800. cli.enable_server_certificate_verification(true);
  12801. cli.set_ca_cert_path(CA_CERT_FILE);
  12802. cli.set_connection_timeout(5);
  12803. // Note: Test certificate has CN="Common Name", not "localhost"
  12804. bool verify_result_cn = false;
  12805. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12806. verify_callback_called = true;
  12807. if (!ctx.cert) return false;
  12808. // Test 1: "Common Name" should match (our test server cert CN)
  12809. verify_result_cn = ctx.check_hostname("Common Name");
  12810. // Test 2: wrong hostname should not match
  12811. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12812. return true; // Accept for the purpose of this test
  12813. });
  12814. auto res = cli.Get("/test");
  12815. // The request may succeed or fail depending on cert configuration
  12816. // but the callback should have been called
  12817. ASSERT_TRUE(verify_callback_called)
  12818. << "Verify callback should have been called";
  12819. // CN="Common Name" should match our test certificate
  12820. //
  12821. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12822. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12823. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12824. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12825. // <openssl/base.h>, which is included transitively when
  12826. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12827. #if defined(OPENSSL_IS_BORINGSSL)
  12828. EXPECT_FALSE(verify_result_cn)
  12829. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12830. #else
  12831. EXPECT_TRUE(verify_result_cn)
  12832. << "verify_hostname should match 'Common Name' (certificate CN)";
  12833. #endif
  12834. // Wrong hostname should not match
  12835. EXPECT_FALSE(verify_result_wrong)
  12836. << "verify_hostname should not match 'wronghost.example.com'";
  12837. }
  12838. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12839. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12840. // X509_check_ip behavior and must hold for every backend.
  12841. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12842. using namespace httplib::tls;
  12843. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12844. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12845. ASSERT_TRUE(svr.is_valid());
  12846. svr.Get("/test", [](const Request &, Response &res) {
  12847. res.set_content("ok", "text/plain");
  12848. });
  12849. thread t([&]() { svr.listen(HOST, PORT); });
  12850. auto se = detail::scope_exit([&] {
  12851. svr.stop();
  12852. t.join();
  12853. });
  12854. svr.wait_until_ready();
  12855. bool verify_callback_called = false;
  12856. bool ip_matched_via_cn = true;
  12857. SSLClient cli(HOST, PORT);
  12858. cli.enable_server_certificate_verification(true);
  12859. cli.set_ca_cert_path(CA_CERT_FILE);
  12860. cli.set_connection_timeout(5);
  12861. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12862. verify_callback_called = true;
  12863. if (!ctx.cert) return false;
  12864. // The IP appears only in the CN, so it must NOT be accepted.
  12865. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12866. return true; // Accept for the purpose of this test
  12867. });
  12868. cli.Get("/test");
  12869. ASSERT_TRUE(verify_callback_called)
  12870. << "Verify callback should have been called";
  12871. EXPECT_FALSE(ip_matched_via_cn)
  12872. << "An IP host must not be authenticated via the certificate CN";
  12873. }
  12874. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12875. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12876. using namespace httplib::tls;
  12877. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12878. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12879. ASSERT_TRUE(svr.is_valid());
  12880. svr.Get("/test", [](const Request &, Response &res) {
  12881. res.set_content("ok", "text/plain");
  12882. });
  12883. thread t([&]() { svr.listen(HOST, PORT); });
  12884. auto se = detail::scope_exit([&] {
  12885. svr.stop();
  12886. t.join();
  12887. });
  12888. svr.wait_until_ready();
  12889. bool verify_callback_called = false;
  12890. bool san_matched = false;
  12891. bool wrong_ipv6_matched = true;
  12892. bool cn_ipv6_matched = true;
  12893. SSLClient cli(HOST, PORT);
  12894. cli.enable_server_certificate_verification(true);
  12895. cli.set_ca_cert_path(CA_CERT_FILE);
  12896. cli.set_connection_timeout(5);
  12897. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12898. verify_callback_called = true;
  12899. if (!ctx.cert) return false;
  12900. // Matches the IPv6 iPAddress SAN.
  12901. san_matched = ctx.check_hostname("2001:db8::1");
  12902. // A different IPv6 address must not match.
  12903. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12904. // "::1" lives only in the CN, so it must not be accepted.
  12905. cn_ipv6_matched = ctx.check_hostname("::1");
  12906. return true; // Accept for the purpose of this test
  12907. });
  12908. cli.Get("/test");
  12909. ASSERT_TRUE(verify_callback_called)
  12910. << "Verify callback should have been called";
  12911. EXPECT_TRUE(san_matched)
  12912. << "verify_hostname should match an IPv6 iPAddress SAN";
  12913. EXPECT_FALSE(wrong_ipv6_matched)
  12914. << "verify_hostname should not match a non-matching IPv6 address";
  12915. EXPECT_FALSE(cn_ipv6_matched)
  12916. << "An IPv6 host must not be authenticated via the certificate CN";
  12917. }
  12918. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12919. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12920. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12921. using namespace httplib::tls;
  12922. // SANs: DNS:a.zz, IP:42.46.122.122
  12923. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12924. ASSERT_TRUE(svr.is_valid());
  12925. svr.Get("/test", [](const Request &, Response &res) {
  12926. res.set_content("ok", "text/plain");
  12927. });
  12928. auto port = svr.bind_to_any_port(HOST);
  12929. thread t([&]() { svr.listen_after_bind(); });
  12930. auto se = detail::scope_exit([&] {
  12931. svr.stop();
  12932. t.join();
  12933. });
  12934. svr.wait_until_ready();
  12935. bool verify_callback_called = false;
  12936. bool dns_san_matched = false;
  12937. bool ip_san_matched = false;
  12938. bool ip_matched_via_dns_san = true;
  12939. bool dns_matched_via_ip_san = true;
  12940. SSLClient cli(HOST, port);
  12941. cli.enable_server_certificate_verification(true);
  12942. cli.set_ca_cert_path(CA_CERT_FILE);
  12943. cli.set_connection_timeout(5);
  12944. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12945. verify_callback_called = true;
  12946. if (!ctx.cert) return false;
  12947. dns_san_matched = ctx.check_hostname("a.zz");
  12948. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12949. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12950. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12951. return true; // Accept for the purpose of this test
  12952. });
  12953. cli.Get("/test");
  12954. ASSERT_TRUE(verify_callback_called)
  12955. << "Verify callback should have been called";
  12956. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12957. EXPECT_TRUE(ip_san_matched)
  12958. << "verify_hostname should match an iPAddress SAN";
  12959. EXPECT_FALSE(ip_matched_via_dns_san)
  12960. << "An IP host must not be authenticated via a dNSName SAN";
  12961. EXPECT_FALSE(dns_matched_via_ip_san)
  12962. << "A DNS host must not be authenticated via an iPAddress SAN";
  12963. }
  12964. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12965. // "www.*.example.test" names one host and not every host under example.test.
  12966. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12967. using namespace httplib::tls;
  12968. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12969. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12970. ASSERT_TRUE(svr.is_valid());
  12971. svr.Get("/test", [](const Request &, Response &res) {
  12972. res.set_content("ok", "text/plain");
  12973. });
  12974. auto port = svr.bind_to_any_port(HOST);
  12975. thread t([&]() { svr.listen_after_bind(); });
  12976. auto se = detail::scope_exit([&] {
  12977. svr.stop();
  12978. t.join();
  12979. });
  12980. svr.wait_until_ready();
  12981. bool verify_callback_called = false;
  12982. bool leftmost_wildcard_matched = false;
  12983. bool wildcard_spanned_labels = true;
  12984. bool inner_wildcard_matched = true;
  12985. SSLClient cli(HOST, port);
  12986. cli.enable_server_certificate_verification(true);
  12987. cli.set_ca_cert_path(CA_CERT_FILE);
  12988. cli.set_connection_timeout(5);
  12989. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12990. verify_callback_called = true;
  12991. if (!ctx.cert) return false;
  12992. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12993. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12994. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12995. return true; // Accept for the purpose of this test
  12996. });
  12997. cli.Get("/test");
  12998. ASSERT_TRUE(verify_callback_called)
  12999. << "Verify callback should have been called";
  13000. EXPECT_TRUE(leftmost_wildcard_matched)
  13001. << "A leftmost wildcard should match a single label";
  13002. EXPECT_FALSE(wildcard_spanned_labels)
  13003. << "A wildcard label must not match more than one label";
  13004. EXPECT_FALSE(inner_wildcard_matched)
  13005. << "A wildcard outside the leftmost label must not be honoured";
  13006. }
  13007. // sans() must report each SAN entry under its own type.
  13008. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13009. using namespace httplib::tls;
  13010. // SANs: DNS:a.zz, IP:42.46.122.122
  13011. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13012. ASSERT_TRUE(svr.is_valid());
  13013. svr.Get("/test", [](const Request &, Response &res) {
  13014. res.set_content("ok", "text/plain");
  13015. });
  13016. auto port = svr.bind_to_any_port(HOST);
  13017. thread t([&]() { svr.listen_after_bind(); });
  13018. auto se = detail::scope_exit([&] {
  13019. svr.stop();
  13020. t.join();
  13021. });
  13022. svr.wait_until_ready();
  13023. bool verify_callback_called = false;
  13024. std::vector<SanEntry> sans;
  13025. SSLClient cli(HOST, port);
  13026. cli.enable_server_certificate_verification(true);
  13027. cli.set_ca_cert_path(CA_CERT_FILE);
  13028. cli.set_connection_timeout(5);
  13029. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13030. verify_callback_called = true;
  13031. if (!ctx.cert) return false;
  13032. sans = ctx.sans();
  13033. return true; // Accept for the purpose of this test
  13034. });
  13035. cli.Get("/test");
  13036. ASSERT_TRUE(verify_callback_called)
  13037. << "Verify callback should have been called";
  13038. auto has_san = [&](SanType type, const std::string &value) {
  13039. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13040. return san.type == type && san.value == value;
  13041. });
  13042. };
  13043. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13044. << "sans() should report the dNSName SAN";
  13045. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13046. << "sans() should report the iPAddress SAN";
  13047. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13048. << "sans() must not report the dNSName SAN as an address";
  13049. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13050. << "sans() must not report the iPAddress SAN as a DNS name";
  13051. }
  13052. #endif
  13053. // mbedTLS-specific callback constructor test
  13054. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13055. #ifdef CPPHTTPLIB_SSL_ENABLED
  13056. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13058. ASSERT_TRUE(svr.is_valid());
  13059. // Set up a handler to verify client certificate is present
  13060. bool client_cert_verified = false;
  13061. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13062. // Verify that client certificate was provided
  13063. client_cert_verified = true;
  13064. res.set_content("success", "text/plain");
  13065. });
  13066. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13067. auto se = detail::scope_exit([&] {
  13068. svr.stop();
  13069. t.join();
  13070. ASSERT_FALSE(svr.is_running());
  13071. });
  13072. svr.wait_until_ready();
  13073. // Client with certificate
  13074. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13075. cli.enable_server_certificate_verification(false);
  13076. cli.set_connection_timeout(30);
  13077. auto res = cli.Get("/test");
  13078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13079. ASSERT_EQ(StatusCode::OK_200, res->status);
  13080. ASSERT_TRUE(client_cert_verified);
  13081. EXPECT_EQ("success", res->body);
  13082. }
  13083. #endif
  13084. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13085. // backends
  13086. #ifdef CPPHTTPLIB_SSL_ENABLED
  13087. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13088. using namespace httplib::tls;
  13089. // Test that when client CA cert file is provided,
  13090. // the server properly requests and validates client certificates
  13091. // Create a server with client authentication
  13092. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13093. ASSERT_TRUE(svr.is_valid());
  13094. bool handler_called = false;
  13095. svr.Get("/test", [&](const Request &req, Response &res) {
  13096. handler_called = true;
  13097. // Verify that a client certificate was provided
  13098. auto cert = req.peer_cert();
  13099. ASSERT_TRUE(static_cast<bool>(cert));
  13100. // Get the issuer name
  13101. std::string issuer_str = cert.issuer_name();
  13102. ASSERT_FALSE(issuer_str.empty());
  13103. // The client certificate should be issued by our test CA
  13104. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13105. res.set_content("authenticated", "text/plain");
  13106. });
  13107. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13108. auto se = detail::scope_exit([&] {
  13109. svr.stop();
  13110. t.join();
  13111. ASSERT_FALSE(svr.is_running());
  13112. });
  13113. svr.wait_until_ready();
  13114. // Connect with a client certificate issued by the CA
  13115. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13116. cli.enable_server_certificate_verification(false);
  13117. cli.set_connection_timeout(30);
  13118. auto res = cli.Get("/test");
  13119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13120. ASSERT_EQ(StatusCode::OK_200, res->status);
  13121. ASSERT_TRUE(handler_called);
  13122. EXPECT_EQ("authenticated", res->body);
  13123. }
  13124. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13125. using namespace httplib::tls;
  13126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13127. ASSERT_TRUE(svr.is_valid());
  13128. svr.Get("/test", [](const Request &, Response &res) {
  13129. res.set_content("ok", "text/plain");
  13130. });
  13131. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13132. auto se = detail::scope_exit([&] {
  13133. svr.stop();
  13134. t.join();
  13135. });
  13136. svr.wait_until_ready();
  13137. SSLClient cli(HOST, PORT);
  13138. cli.enable_server_certificate_verification(false);
  13139. cli.set_connection_timeout(30);
  13140. bool cert_checked = false;
  13141. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13142. if (ctx.cert) {
  13143. auto sans = ctx.sans();
  13144. // Test certificate may or may not have SANs - just verify the API
  13145. // works If SANs exist, verify the types are valid
  13146. for (const auto &san : sans) {
  13147. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13148. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13149. san.type == SanType::OTHER);
  13150. EXPECT_FALSE(san.value.empty());
  13151. }
  13152. cert_checked = true;
  13153. }
  13154. return true;
  13155. });
  13156. auto res = cli.Get("/test");
  13157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13158. EXPECT_TRUE(cert_checked);
  13159. }
  13160. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13161. using namespace httplib::tls;
  13162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13163. ASSERT_TRUE(svr.is_valid());
  13164. svr.Get("/test", [](const Request &, Response &res) {
  13165. res.set_content("ok", "text/plain");
  13166. });
  13167. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13168. auto se = detail::scope_exit([&] {
  13169. svr.stop();
  13170. t.join();
  13171. });
  13172. svr.wait_until_ready();
  13173. SSLClient cli(HOST, PORT);
  13174. cli.enable_server_certificate_verification(false);
  13175. cli.set_connection_timeout(30);
  13176. bool validity_checked = false;
  13177. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13178. if (ctx.cert) {
  13179. time_t not_before = 0, not_after = 0;
  13180. bool result = ctx.validity(not_before, not_after);
  13181. EXPECT_TRUE(result);
  13182. // Verify that not_before < now < not_after for a valid cert
  13183. time_t now = time(nullptr);
  13184. EXPECT_LT(not_before, now);
  13185. EXPECT_GT(not_after, now);
  13186. validity_checked = true;
  13187. }
  13188. return true;
  13189. });
  13190. auto res = cli.Get("/test");
  13191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13192. EXPECT_TRUE(validity_checked);
  13193. }
  13194. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13195. using namespace httplib::tls;
  13196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13197. ASSERT_TRUE(svr.is_valid());
  13198. svr.Get("/test", [](const Request &, Response &res) {
  13199. res.set_content("ok", "text/plain");
  13200. });
  13201. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13202. auto se = detail::scope_exit([&] {
  13203. svr.stop();
  13204. t.join();
  13205. });
  13206. svr.wait_until_ready();
  13207. SSLClient cli(HOST, PORT);
  13208. cli.enable_server_certificate_verification(false);
  13209. cli.set_connection_timeout(30);
  13210. bool serial_checked = false;
  13211. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13212. if (ctx.cert) {
  13213. std::string serial = ctx.serial();
  13214. EXPECT_FALSE(serial.empty());
  13215. // Serial should be a hex string
  13216. for (char c : serial) {
  13217. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13218. (c >= 'a' && c <= 'f'));
  13219. }
  13220. serial_checked = true;
  13221. }
  13222. return true;
  13223. });
  13224. auto res = cli.Get("/test");
  13225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13226. EXPECT_TRUE(serial_checked);
  13227. }
  13228. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13229. // Test 1: Valid CA file - no error should be recorded
  13230. {
  13231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13232. CLIENT_CA_CERT_FILE);
  13233. ASSERT_TRUE(svr.is_valid());
  13234. // With valid setup, last_ssl_error should be 0
  13235. EXPECT_EQ(0, svr.ssl_last_error());
  13236. }
  13237. // Test 2: Invalid CA file content
  13238. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13239. {
  13240. // Create a temporary file with completely invalid content
  13241. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13242. {
  13243. std::ofstream ofs(temp_invalid_ca);
  13244. ofs << "This is not a certificate file at all\n";
  13245. ofs << "Just plain text content\n";
  13246. }
  13247. // Create server with invalid CA file
  13248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13249. // Clean up temporary file
  13250. std::remove(temp_invalid_ca);
  13251. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13252. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13253. // Note: SSL_CTX_load_verify_locations typically fails first,
  13254. // but our error handling code path is still exercised
  13255. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13256. }
  13257. }
  13258. TEST(VerifyCallbackTest, VerifyContextFields) {
  13259. using namespace httplib::tls;
  13260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13261. ASSERT_TRUE(svr.is_valid());
  13262. svr.Get("/test", [](const Request &, Response &res) {
  13263. res.set_content("ok", "text/plain");
  13264. });
  13265. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13266. auto se = detail::scope_exit([&] {
  13267. svr.stop();
  13268. t.join();
  13269. });
  13270. svr.wait_until_ready();
  13271. SSLClient cli(HOST, PORT);
  13272. cli.enable_server_certificate_verification(false);
  13273. cli.set_connection_timeout(30);
  13274. int callback_count = 0;
  13275. bool saw_leaf_cert = false;
  13276. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13277. if (ctx.cert) {
  13278. callback_count++;
  13279. // We should see at least one certificate (the leaf)
  13280. std::string cn = ctx.subject_cn();
  13281. if (!cn.empty()) { saw_leaf_cert = true; }
  13282. // Verify context fields are populated
  13283. EXPECT_NE(ctx.session, nullptr);
  13284. EXPECT_GE(ctx.depth, 0);
  13285. }
  13286. return true;
  13287. });
  13288. auto res = cli.Get("/test");
  13289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13290. EXPECT_GT(callback_count, 0);
  13291. EXPECT_TRUE(saw_leaf_cert);
  13292. }
  13293. // A verifier belongs to the client that set it, not to the thread that set it.
  13294. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13295. using namespace httplib::tls;
  13296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13297. ASSERT_TRUE(svr.is_valid());
  13298. svr.Get("/test", [](const Request &, Response &res) {
  13299. res.set_content("ok", "text/plain");
  13300. });
  13301. auto port = svr.bind_to_any_port(HOST);
  13302. thread t([&]() { svr.listen_after_bind(); });
  13303. auto se = detail::scope_exit([&] {
  13304. svr.stop();
  13305. t.join();
  13306. });
  13307. svr.wait_until_ready();
  13308. auto rejecting_calls = 0;
  13309. SSLClient rejecting(HOST, port);
  13310. rejecting.enable_server_certificate_verification(false);
  13311. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13312. rejecting_calls++;
  13313. return false;
  13314. });
  13315. auto accepting_calls = 0;
  13316. SSLClient accepting(HOST, port);
  13317. accepting.enable_server_certificate_verification(false);
  13318. // Set on another thread than the requests below.
  13319. thread([&]() {
  13320. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13321. accepting_calls++;
  13322. return true;
  13323. });
  13324. }).join();
  13325. // Requested on another thread than the verifier was set on.
  13326. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13327. EXPECT_GT(rejecting_calls, 0);
  13328. auto res = accepting.Get("/test");
  13329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13330. EXPECT_GT(accepting_calls, 0);
  13331. }
  13332. // VerifyContext::session is the same handle the other tls:: functions take.
  13333. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13334. using namespace httplib::tls;
  13335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13336. ASSERT_TRUE(svr.is_valid());
  13337. svr.Get("/test", [](const Request &, Response &res) {
  13338. res.set_content("ok", "text/plain");
  13339. });
  13340. auto port = svr.bind_to_any_port(HOST);
  13341. thread t([&]() { svr.listen_after_bind(); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. });
  13346. svr.wait_until_ready();
  13347. SSLClient cli(HOST, port);
  13348. cli.enable_server_certificate_verification(false);
  13349. session_t verifier_session = nullptr;
  13350. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13351. verifier_session = ctx.session;
  13352. return true;
  13353. });
  13354. session_t session_verifier_session = nullptr;
  13355. cli.set_session_verifier([&](session_t session) {
  13356. session_verifier_session = session;
  13357. return SSLVerifierResponse::NoDecisionMade;
  13358. });
  13359. auto res = cli.Get("/test");
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. EXPECT_NE(nullptr, verifier_session);
  13362. EXPECT_EQ(session_verifier_session, verifier_session);
  13363. }
  13364. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13365. using httplib::tls::TlsError;
  13366. // Test that verify_error_to_string returns empty for success
  13367. std::string success_str = TlsError::verify_error_to_string(0);
  13368. EXPECT_TRUE(success_str.empty());
  13369. // Test that verify_error_to_string returns non-empty for error codes
  13370. // Using a common error code (certificate expired)
  13371. std::string error_str =
  13372. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13373. EXPECT_FALSE(error_str.empty());
  13374. }
  13375. TEST(SessionVerifierTest, CertificateAccepted) {
  13376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13377. ASSERT_TRUE(svr.is_valid());
  13378. svr.Get("/test", [](const Request &, Response &res) {
  13379. res.set_content("ok", "text/plain");
  13380. });
  13381. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13382. auto se = detail::scope_exit([&] {
  13383. svr.stop();
  13384. t.join();
  13385. });
  13386. svr.wait_until_ready();
  13387. SSLClient cli(HOST, PORT);
  13388. cli.enable_server_certificate_verification(false);
  13389. cli.set_connection_timeout(30);
  13390. bool callback_called = false;
  13391. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13392. EXPECT_NE(session, nullptr);
  13393. callback_called = true;
  13394. return SSLVerifierResponse::CertificateAccepted;
  13395. });
  13396. auto res = cli.Get("/test");
  13397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13398. EXPECT_EQ(200, res->status);
  13399. EXPECT_TRUE(callback_called);
  13400. }
  13401. TEST(SessionVerifierTest, CertificateRejected) {
  13402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13403. ASSERT_TRUE(svr.is_valid());
  13404. svr.Get("/test", [](const Request &, Response &res) {
  13405. res.set_content("ok", "text/plain");
  13406. });
  13407. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13408. auto se = detail::scope_exit([&] {
  13409. svr.stop();
  13410. t.join();
  13411. });
  13412. svr.wait_until_ready();
  13413. SSLClient cli(HOST, PORT);
  13414. cli.enable_server_certificate_verification(false);
  13415. cli.set_connection_timeout(30);
  13416. bool callback_called = false;
  13417. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13418. EXPECT_NE(session, nullptr);
  13419. callback_called = true;
  13420. return SSLVerifierResponse::CertificateRejected;
  13421. });
  13422. auto res = cli.Get("/test");
  13423. EXPECT_FALSE(res);
  13424. EXPECT_TRUE(callback_called);
  13425. }
  13426. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13428. ASSERT_TRUE(svr.is_valid());
  13429. svr.Get("/test", [](const Request &, Response &res) {
  13430. res.set_content("ok", "text/plain");
  13431. });
  13432. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13433. auto se = detail::scope_exit([&] {
  13434. svr.stop();
  13435. t.join();
  13436. });
  13437. svr.wait_until_ready();
  13438. // NoDecisionMade with verification disabled should succeed (no default check)
  13439. SSLClient cli(HOST, PORT);
  13440. cli.enable_server_certificate_verification(false);
  13441. cli.set_connection_timeout(30);
  13442. bool callback_called = false;
  13443. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13444. EXPECT_NE(session, nullptr);
  13445. callback_called = true;
  13446. return SSLVerifierResponse::NoDecisionMade;
  13447. });
  13448. auto res = cli.Get("/test");
  13449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13450. EXPECT_EQ(200, res->status);
  13451. EXPECT_TRUE(callback_called);
  13452. }
  13453. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13455. ASSERT_TRUE(svr.is_valid());
  13456. svr.Get("/test", [](const Request &, Response &res) {
  13457. res.set_content("ok", "text/plain");
  13458. });
  13459. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13460. auto se = detail::scope_exit([&] {
  13461. svr.stop();
  13462. t.join();
  13463. });
  13464. svr.wait_until_ready();
  13465. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13466. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13467. // so we only check that the request fails, not whether the callback was
  13468. // called.
  13469. SSLClient cli(HOST, PORT);
  13470. cli.enable_server_certificate_verification(true);
  13471. cli.set_connection_timeout(30);
  13472. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13473. EXPECT_NE(session, nullptr);
  13474. return SSLVerifierResponse::NoDecisionMade;
  13475. });
  13476. auto res = cli.Get("/test");
  13477. EXPECT_FALSE(res);
  13478. }
  13479. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13480. // Test SSL server using PemMemory constructor with client CA certificates
  13481. // Read PEM files
  13482. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13483. read_file(SERVER_CERT_FILE, server_cert_pem);
  13484. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13485. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13486. // Create SSLServer with PemMemory constructor including client CA
  13487. SSLServer::PemMemory server_pem = {
  13488. server_cert_pem.c_str(),
  13489. server_cert_pem.size(),
  13490. server_key_pem.c_str(),
  13491. server_key_pem.size(),
  13492. client_ca_pem.c_str(),
  13493. client_ca_pem.size(),
  13494. nullptr // no password for server key
  13495. };
  13496. SSLServer svr(server_pem);
  13497. ASSERT_TRUE(svr.is_valid());
  13498. // No SSL error should be recorded for valid setup
  13499. EXPECT_EQ(0, svr.ssl_last_error());
  13500. // Set up server endpoints
  13501. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13502. res.set_content("ok", "text/plain");
  13503. });
  13504. // Start server in a thread
  13505. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13506. svr.wait_until_ready();
  13507. // Connect with client certificate (using constructor with paths)
  13508. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13509. cli.enable_server_certificate_verification(false);
  13510. auto res = cli.Get("/test-pem-ca");
  13511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13512. EXPECT_EQ(200, res->status);
  13513. EXPECT_EQ("ok", res->body);
  13514. svr.stop();
  13515. server_thread.join();
  13516. }
  13517. #endif
  13518. #ifdef _WIN32
  13519. TEST(CleanupTest, WSACleanup) {
  13520. int ret = WSACleanup();
  13521. ASSERT_EQ(0, ret);
  13522. }
  13523. #endif
  13524. #ifndef CPPHTTPLIB_SSL_ENABLED
  13525. TEST(NoSSLSupport, SimpleInterface) {
  13526. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13527. }
  13528. #endif
  13529. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13530. TEST(InvalidScheme, SimpleInterface) {
  13531. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13532. }
  13533. #endif
  13534. TEST(NoScheme, SimpleInterface) {
  13535. Client cli("yahoo.com:80");
  13536. ASSERT_TRUE(cli.is_valid());
  13537. }
  13538. TEST(SendAPI, SimpleInterface_Online) {
  13539. Client cli("http://yahoo.com");
  13540. Request req;
  13541. req.method = "GET";
  13542. req.path = "/";
  13543. auto res = cli.send(req);
  13544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13545. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13546. }
  13547. TEST(SendAPI, WithParamsInRequest) {
  13548. Server svr;
  13549. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13550. EXPECT_TRUE(req.has_param("test"));
  13551. EXPECT_EQ("test_value", req.get_param_value("test"));
  13552. });
  13553. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13554. auto se = detail::scope_exit([&] {
  13555. svr.stop();
  13556. t.join();
  13557. ASSERT_FALSE(svr.is_running());
  13558. });
  13559. svr.wait_until_ready();
  13560. Client cli(HOST, PORT);
  13561. {
  13562. Request req;
  13563. req.method = "GET";
  13564. req.path = "/";
  13565. req.params.emplace("test", "test_value");
  13566. auto res = cli.send(req);
  13567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13568. }
  13569. {
  13570. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13572. }
  13573. }
  13574. TEST(ClientImplMethods, GetSocketTest) {
  13575. httplib::Server svr;
  13576. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13577. res.status = StatusCode::OK_200;
  13578. });
  13579. auto port = svr.bind_to_any_port("127.0.0.1");
  13580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13581. auto se = detail::scope_exit([&] {
  13582. svr.stop();
  13583. thread.join();
  13584. ASSERT_FALSE(svr.is_running());
  13585. });
  13586. svr.wait_until_ready();
  13587. {
  13588. httplib::Client cli("127.0.0.1", port);
  13589. cli.set_keep_alive(true);
  13590. // Use the behavior of cpp-httplib of opening the connection
  13591. // only when the first request happens. If that changes,
  13592. // this test would be obsolete.
  13593. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13594. // This also implicitly tests the server. But other tests would fail much
  13595. // earlier than this one to be considered.
  13596. auto res = cli.Get("/");
  13597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13598. EXPECT_EQ(StatusCode::OK_200, res->status);
  13599. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13600. }
  13601. }
  13602. #ifdef CPPHTTPLIB_SSL_ENABLED
  13603. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13604. Client cli("http://yahoo.com");
  13605. auto res = cli.Get("/");
  13606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13607. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13608. cli.set_follow_location(true);
  13609. res = cli.Get("/");
  13610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13611. EXPECT_EQ(StatusCode::OK_200, res->status);
  13612. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13613. }
  13614. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13615. Client cli("https://yahoo.com");
  13616. auto res = cli.Get("/");
  13617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13618. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13619. cli.set_follow_location(true);
  13620. res = cli.Get("/");
  13621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13622. EXPECT_EQ(StatusCode::OK_200, res->status);
  13623. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13624. }
  13625. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13626. Client cli("https://yahoo.com");
  13627. auto res = cli.Get("/");
  13628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13629. ASSERT_FALSE(!res);
  13630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13631. ASSERT_FALSE(res == nullptr);
  13632. ASSERT_TRUE(res != nullptr);
  13633. EXPECT_EQ(Error::Success, res.error());
  13634. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13635. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13636. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13637. cli.set_follow_location(true);
  13638. res = cli.Get("/");
  13639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13640. EXPECT_EQ(Error::Success, res.error());
  13641. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13642. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13643. EXPECT_EQ(StatusCode::OK_200, res->status);
  13644. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13645. }
  13646. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13647. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13648. Client cli("https://cdnjs.cloudflare.com");
  13649. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13650. Headers{{"Accept-Encoding", "br"}});
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. EXPECT_EQ(StatusCode::OK_200, res->status);
  13653. EXPECT_EQ(287630U, res->body.size());
  13654. EXPECT_EQ("application/javascript; charset=utf-8",
  13655. res->get_header_value("Content-Type"));
  13656. }
  13657. #endif
  13658. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13659. #undef REDIR_HOST // Silence compiler warning
  13660. #define REDIR_HOST "https://httpbingo.org"
  13661. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13662. Client cli(REDIR_HOST);
  13663. cli.set_follow_location(true);
  13664. auto res =
  13665. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13667. EXPECT_EQ(StatusCode::OK_200, res->status);
  13668. }
  13669. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13670. Client cli(REDIR_HOST);
  13671. cli.set_follow_location(true);
  13672. Params params;
  13673. params.emplace("url", "http://example.com");
  13674. params.emplace("status_code", "302");
  13675. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13677. EXPECT_EQ(StatusCode::OK_200, res->status);
  13678. }
  13679. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13680. Client cli(REDIR_HOST);
  13681. cli.set_follow_location(true);
  13682. Params params;
  13683. params.emplace("url", "http://example.com");
  13684. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13686. EXPECT_EQ(StatusCode::OK_200, res->status);
  13687. }
  13688. TEST(HttpToHttpsRedirectTest, CertFile) {
  13689. auto ssl_port = PORT + 1;
  13690. Server svr;
  13691. ASSERT_TRUE(svr.is_valid());
  13692. svr.Get("/index", [&](const Request &, Response &res) {
  13693. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13694. "/index");
  13695. svr.stop();
  13696. });
  13697. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13698. ASSERT_TRUE(ssl_svr.is_valid());
  13699. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13700. res.set_content("test", "text/plain");
  13701. ssl_svr.stop();
  13702. });
  13703. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13704. thread t2 =
  13705. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13706. auto se = detail::scope_exit([&] {
  13707. t2.join();
  13708. t.join();
  13709. ASSERT_FALSE(svr.is_running());
  13710. });
  13711. svr.wait_until_ready();
  13712. ssl_svr.wait_until_ready();
  13713. Client cli("127.0.0.1", PORT);
  13714. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13715. cli.enable_server_certificate_verification(true);
  13716. cli.set_follow_location(true);
  13717. cli.set_connection_timeout(30);
  13718. auto res = cli.Get("/index");
  13719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13720. ASSERT_EQ(StatusCode::OK_200, res->status);
  13721. }
  13722. TEST(SSLClientRedirectTest, CertFile) {
  13723. auto ssl_port = PORT + 1;
  13724. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13725. ASSERT_TRUE(ssl_svr1.is_valid());
  13726. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13727. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13728. "/index");
  13729. ssl_svr1.stop();
  13730. });
  13731. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13732. ASSERT_TRUE(ssl_svr2.is_valid());
  13733. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13734. res.set_content("test", "text/plain");
  13735. ssl_svr2.stop();
  13736. });
  13737. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13738. thread t2 =
  13739. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13740. auto se = detail::scope_exit([&] {
  13741. t2.join();
  13742. t.join();
  13743. ASSERT_FALSE(ssl_svr1.is_running());
  13744. });
  13745. ssl_svr1.wait_until_ready();
  13746. ssl_svr2.wait_until_ready();
  13747. SSLClient cli("127.0.0.1", PORT);
  13748. std::string cert;
  13749. read_file(SERVER_CERT2_FILE, cert);
  13750. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13751. cli.enable_server_certificate_verification(true);
  13752. cli.set_follow_location(true);
  13753. cli.set_connection_timeout(30);
  13754. auto res = cli.Get("/index");
  13755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13756. ASSERT_EQ(StatusCode::OK_200, res->status);
  13757. }
  13758. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13759. // another port, so the client follows it with a new client.
  13760. static Result GetThroughTlsRedirectToDifferentPort(
  13761. const std::function<void(SSLClient &)> &setup,
  13762. const char *target_cert = SERVER_CERT2_FILE) {
  13763. auto ssl_port = PORT + 1;
  13764. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13765. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13766. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13767. "/index");
  13768. });
  13769. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13770. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13771. res.set_content("test", "text/plain");
  13772. });
  13773. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13774. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13775. auto se = detail::scope_exit([&] {
  13776. ssl_svr2.stop();
  13777. ssl_svr1.stop();
  13778. t2.join();
  13779. t.join();
  13780. });
  13781. ssl_svr1.wait_until_ready();
  13782. ssl_svr2.wait_until_ready();
  13783. SSLClient cli("127.0.0.1", PORT);
  13784. cli.set_follow_location(true);
  13785. cli.set_connection_timeout(30);
  13786. setup(cli);
  13787. return cli.Get("/index");
  13788. }
  13789. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13790. auto calls = 0;
  13791. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13792. cli.enable_server_certificate_verification(false);
  13793. // Accept the first server only.
  13794. cli.set_session_verifier([&](tls::session_t) {
  13795. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13796. : SSLVerifierResponse::CertificateRejected;
  13797. });
  13798. });
  13799. EXPECT_FALSE(res);
  13800. EXPECT_EQ(2, calls);
  13801. }
  13802. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13803. std::string pinned;
  13804. auto res = GetThroughTlsRedirectToDifferentPort(
  13805. [&](SSLClient &cli) {
  13806. cli.enable_server_certificate_verification(false);
  13807. // Pin the first certificate seen.
  13808. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13809. if (pinned.empty()) { pinned = ctx.serial(); }
  13810. return ctx.serial() == pinned;
  13811. });
  13812. },
  13813. // A certificate other than the first server's.
  13814. SERVER_CERT_FILE);
  13815. EXPECT_FALSE(res);
  13816. EXPECT_FALSE(pinned.empty());
  13817. }
  13818. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13819. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13820. std::string cert;
  13821. read_file(SERVER_CERT2_FILE, cert);
  13822. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13823. });
  13824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13825. EXPECT_EQ(StatusCode::OK_200, res->status);
  13826. }
  13827. #endif
  13828. #ifdef CPPHTTPLIB_SSL_ENABLED
  13829. // Test that set_ca_cert_store() skips system certs (consistent with
  13830. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13831. // should be trusted - system certs should NOT be loaded.
  13832. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13833. // Load a specific cert that is NOT a system CA cert
  13834. std::string cert;
  13835. read_file(SERVER_CERT2_FILE, cert);
  13836. SSLClient cli("google.com");
  13837. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13838. cli.enable_server_certificate_verification(true);
  13839. // This should FAIL because:
  13840. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13841. // 2. System certs should NOT be loaded when custom store is set
  13842. // If system certs WERE loaded, this would succeed
  13843. auto res = cli.Get("/");
  13844. ASSERT_FALSE(res);
  13845. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13846. }
  13847. // Same as above, but through the native store handle path. Regression test:
  13848. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13849. // merged system certs into the user-provided store.
  13850. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13851. std::string cert;
  13852. read_file(SERVER_CERT2_FILE, cert);
  13853. SSLClient cli("google.com");
  13854. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13855. cli.enable_server_certificate_verification(true);
  13856. auto res = cli.Get("/");
  13857. ASSERT_FALSE(res);
  13858. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13859. }
  13860. // A custom store set via the native handle must still verify a server whose
  13861. // cert it does contain.
  13862. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13863. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13864. ASSERT_TRUE(svr.is_valid());
  13865. svr.Get("/test", [&](const Request &, Response &res) {
  13866. res.set_content("test", "text/plain");
  13867. });
  13868. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13869. auto se = detail::scope_exit([&] {
  13870. svr.stop();
  13871. t.join();
  13872. ASSERT_FALSE(svr.is_running());
  13873. });
  13874. svr.wait_until_ready();
  13875. SSLClient cli("127.0.0.1", PORT);
  13876. std::string cert;
  13877. read_file(SERVER_CERT2_FILE, cert);
  13878. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13879. cli.enable_server_certificate_verification(true);
  13880. cli.set_connection_timeout(30);
  13881. auto res = cli.Get("/test");
  13882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13883. ASSERT_EQ(StatusCode::OK_200, res->status);
  13884. }
  13885. // CA certs loaded through the universal Client must be transferred to the
  13886. // client created internally for following an HTTPS redirect. Regression test:
  13887. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13888. // the CA data for redirect transfer.
  13889. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13890. auto ssl_port = PORT + 1;
  13891. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13892. ASSERT_TRUE(ssl_svr1.is_valid());
  13893. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13894. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13895. "/index");
  13896. });
  13897. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13898. ASSERT_TRUE(ssl_svr2.is_valid());
  13899. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13900. res.set_content("test", "text/plain");
  13901. });
  13902. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13903. thread t2 =
  13904. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13905. auto se = detail::scope_exit([&] {
  13906. ssl_svr2.stop();
  13907. ssl_svr1.stop();
  13908. t2.join();
  13909. t.join();
  13910. ASSERT_FALSE(ssl_svr1.is_running());
  13911. });
  13912. ssl_svr1.wait_until_ready();
  13913. ssl_svr2.wait_until_ready();
  13914. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13915. std::string cert;
  13916. read_file(SERVER_CERT2_FILE, cert);
  13917. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13918. cli.enable_server_certificate_verification(true);
  13919. cli.set_follow_location(true);
  13920. cli.set_connection_timeout(30);
  13921. auto res = cli.Get("/index");
  13922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13923. ASSERT_EQ(StatusCode::OK_200, res->status);
  13924. }
  13925. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13926. // so a host signed by a system CA verifies even though a custom CA is set
  13927. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13928. std::string cert;
  13929. read_file(SERVER_CERT2_FILE, cert);
  13930. SSLClient cli("google.com");
  13931. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13932. cli.enable_system_ca(true);
  13933. cli.enable_server_certificate_verification(true);
  13934. auto res = cli.Get("/");
  13935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13936. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13937. }
  13938. // The custom CA remains effective when combined with the system CA
  13939. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13940. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13941. ASSERT_TRUE(svr.is_valid());
  13942. svr.Get("/test", [&](const Request &, Response &res) {
  13943. res.set_content("test", "text/plain");
  13944. });
  13945. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13946. auto se = detail::scope_exit([&] {
  13947. svr.stop();
  13948. t.join();
  13949. ASSERT_FALSE(svr.is_running());
  13950. });
  13951. svr.wait_until_ready();
  13952. SSLClient cli("127.0.0.1", PORT);
  13953. std::string cert;
  13954. read_file(SERVER_CERT2_FILE, cert);
  13955. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13956. cli.enable_system_ca(true);
  13957. cli.enable_server_certificate_verification(true);
  13958. cli.set_connection_timeout(30);
  13959. auto res = cli.Get("/test");
  13960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13961. ASSERT_EQ(StatusCode::OK_200, res->status);
  13962. }
  13963. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13964. // skip chain verification entirely (only the certificate identity was
  13965. // checked), so a server presenting an untrusted certificate with a matching
  13966. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13967. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13968. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13969. ASSERT_TRUE(svr.is_valid());
  13970. svr.Get("/test", [&](const Request &, Response &res) {
  13971. res.set_content("test", "text/plain");
  13972. });
  13973. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13974. auto se = detail::scope_exit([&] {
  13975. svr.stop();
  13976. t.join();
  13977. ASSERT_FALSE(svr.is_running());
  13978. });
  13979. svr.wait_until_ready();
  13980. SSLClient cli("127.0.0.1", PORT);
  13981. std::string cert;
  13982. // A trusted CA that did not sign the server certificate. The server cert
  13983. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13984. // this connection.
  13985. read_file(CLIENT_CA_CERT_FILE, cert);
  13986. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13987. cli.enable_server_certificate_verification(true);
  13988. cli.set_connection_timeout(30);
  13989. auto res = cli.Get("/test");
  13990. ASSERT_FALSE(res);
  13991. }
  13992. // enable_system_ca(false) prevents system CA loading entirely
  13993. TEST(SSLClientTest, DisableSystemCa_Online) {
  13994. SSLClient cli("google.com");
  13995. cli.enable_system_ca(false);
  13996. cli.enable_server_certificate_verification(true);
  13997. auto res = cli.Get("/");
  13998. ASSERT_FALSE(res);
  13999. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14000. // itself when the CA chain is empty
  14001. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14002. res.error() == Error::SSLConnection);
  14003. }
  14004. // The universal Client forwards enable_system_ca()
  14005. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14006. std::string cert;
  14007. read_file(SERVER_CERT2_FILE, cert);
  14008. Client cli("https://google.com");
  14009. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14010. cli.enable_system_ca(true);
  14011. cli.enable_server_certificate_verification(true);
  14012. auto res = cli.Get("/");
  14013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14014. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14015. }
  14016. // The system CA policy must carry over to the client created internally for
  14017. // following a cross-host HTTPS redirect
  14018. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14019. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14020. ASSERT_TRUE(svr.is_valid());
  14021. svr.Get("/index", [&](const Request &, Response &res) {
  14022. res.set_redirect("https://www.google.com/");
  14023. });
  14024. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14025. auto se = detail::scope_exit([&] {
  14026. svr.stop();
  14027. t.join();
  14028. ASSERT_FALSE(svr.is_running());
  14029. });
  14030. svr.wait_until_ready();
  14031. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14032. std::string cert;
  14033. read_file(SERVER_CERT2_FILE, cert);
  14034. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14035. cli.enable_system_ca(true);
  14036. cli.enable_server_certificate_verification(true);
  14037. cli.set_follow_location(true);
  14038. cli.set_connection_timeout(30);
  14039. // Receiving any response proves the redirect client completed the TLS
  14040. // handshake with a system-CA-signed host
  14041. auto res = cli.Get("/index");
  14042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14043. }
  14044. TEST(MultipartFormDataTest, LargeData) {
  14045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14046. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14047. const ContentReader &content_reader) {
  14048. if (req.is_multipart_form_data()) {
  14049. std::vector<FormData> items;
  14050. content_reader(
  14051. [&](const FormData &file) {
  14052. items.push_back(file);
  14053. return true;
  14054. },
  14055. [&](const char *data, size_t data_length) {
  14056. items.back().content.append(data, data_length);
  14057. return true;
  14058. });
  14059. EXPECT_TRUE(std::string(items[0].name) == "document");
  14060. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14061. EXPECT_TRUE(items[0].filename == "2MB_data");
  14062. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14063. EXPECT_TRUE(items[1].name == "hello");
  14064. EXPECT_TRUE(items[1].content == "world");
  14065. EXPECT_TRUE(items[1].filename == "");
  14066. EXPECT_TRUE(items[1].content_type == "");
  14067. } else {
  14068. std::string body;
  14069. content_reader([&](const char *data, size_t data_length) {
  14070. body.append(data, data_length);
  14071. return true;
  14072. });
  14073. }
  14074. });
  14075. auto port = svr.bind_to_any_port(HOST);
  14076. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14077. auto se = detail::scope_exit([&] {
  14078. svr.stop();
  14079. t.join();
  14080. ASSERT_FALSE(svr.is_running());
  14081. });
  14082. svr.wait_until_ready();
  14083. {
  14084. std::string data(1024 * 1024 * 2, '.');
  14085. std::stringstream buffer;
  14086. buffer << data;
  14087. SSLClient cli(HOST, port);
  14088. cli.enable_server_certificate_verification(false);
  14089. UploadFormDataItems items{
  14090. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14091. {"hello", "world", "", ""},
  14092. };
  14093. auto res = cli.Post("/post", items);
  14094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14095. ASSERT_EQ(StatusCode::OK_200, res->status);
  14096. }
  14097. }
  14098. TEST(MultipartFormDataTest, DataProviderItems) {
  14099. std::random_device seed_gen;
  14100. std::mt19937 random(seed_gen());
  14101. std::string rand1;
  14102. rand1.resize(1000);
  14103. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14104. std::string rand2;
  14105. rand2.resize(3000);
  14106. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14107. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14108. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14109. const ContentReader &content_reader) {
  14110. ASSERT_FALSE(req.is_multipart_form_data());
  14111. std::string body;
  14112. content_reader([&](const char *data, size_t data_length) {
  14113. body.append(data, data_length);
  14114. return true;
  14115. });
  14116. EXPECT_EQ(body, "");
  14117. });
  14118. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14119. const ContentReader &content_reader) {
  14120. ASSERT_TRUE(req.is_multipart_form_data());
  14121. std::vector<FormData> items;
  14122. content_reader(
  14123. [&](const FormData &file) {
  14124. items.push_back(file);
  14125. return true;
  14126. },
  14127. [&](const char *data, size_t data_length) {
  14128. items.back().content.append(data, data_length);
  14129. return true;
  14130. });
  14131. ASSERT_TRUE(items.size() == 2);
  14132. EXPECT_EQ(std::string(items[0].name), "name1");
  14133. EXPECT_EQ(items[0].content, "Testing123");
  14134. EXPECT_EQ(items[0].filename, "filename1");
  14135. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14136. EXPECT_EQ(items[1].name, "name2");
  14137. EXPECT_EQ(items[1].content, "Testing456");
  14138. EXPECT_EQ(items[1].filename, "");
  14139. EXPECT_EQ(items[1].content_type, "");
  14140. });
  14141. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14142. const ContentReader &content_reader) {
  14143. ASSERT_TRUE(req.is_multipart_form_data());
  14144. std::vector<FormData> items;
  14145. content_reader(
  14146. [&](const FormData &file) {
  14147. items.push_back(file);
  14148. return true;
  14149. },
  14150. [&](const char *data, size_t data_length) {
  14151. items.back().content.append(data, data_length);
  14152. return true;
  14153. });
  14154. ASSERT_TRUE(items.size() == 2);
  14155. EXPECT_EQ(items[0].name, "name3");
  14156. EXPECT_EQ(items[0].content, rand1);
  14157. EXPECT_EQ(items[0].filename, "filename3");
  14158. EXPECT_EQ(items[0].content_type, "");
  14159. EXPECT_EQ(items[1].name, "name4");
  14160. EXPECT_EQ(items[1].content, rand2);
  14161. EXPECT_EQ(items[1].filename, "filename4");
  14162. EXPECT_EQ(items[1].content_type, "");
  14163. });
  14164. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14165. const ContentReader &content_reader) {
  14166. ASSERT_TRUE(req.is_multipart_form_data());
  14167. std::vector<FormData> items;
  14168. content_reader(
  14169. [&](const FormData &file) {
  14170. items.push_back(file);
  14171. return true;
  14172. },
  14173. [&](const char *data, size_t data_length) {
  14174. items.back().content.append(data, data_length);
  14175. return true;
  14176. });
  14177. ASSERT_TRUE(items.size() == 4);
  14178. EXPECT_EQ(std::string(items[0].name), "name1");
  14179. EXPECT_EQ(items[0].content, "Testing123");
  14180. EXPECT_EQ(items[0].filename, "filename1");
  14181. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14182. EXPECT_EQ(items[1].name, "name2");
  14183. EXPECT_EQ(items[1].content, "Testing456");
  14184. EXPECT_EQ(items[1].filename, "");
  14185. EXPECT_EQ(items[1].content_type, "");
  14186. EXPECT_EQ(items[2].name, "name3");
  14187. EXPECT_EQ(items[2].content, rand1);
  14188. EXPECT_EQ(items[2].filename, "filename3");
  14189. EXPECT_EQ(items[2].content_type, "");
  14190. EXPECT_EQ(items[3].name, "name4");
  14191. EXPECT_EQ(items[3].content, rand2);
  14192. EXPECT_EQ(items[3].filename, "filename4");
  14193. EXPECT_EQ(items[3].content_type, "");
  14194. });
  14195. auto port = svr.bind_to_any_port("localhost");
  14196. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14197. auto se = detail::scope_exit([&] {
  14198. svr.stop();
  14199. t.join();
  14200. ASSERT_FALSE(svr.is_running());
  14201. });
  14202. svr.wait_until_ready();
  14203. {
  14204. SSLClient cli("localhost", port);
  14205. cli.enable_server_certificate_verification(false);
  14206. UploadFormDataItems items{
  14207. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14208. {"name2", "Testing456", "", ""}, // not a file
  14209. };
  14210. {
  14211. auto res = cli.Post("/post-none", {}, {}, {});
  14212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14213. ASSERT_EQ(StatusCode::OK_200, res->status);
  14214. }
  14215. FormDataProviderItems providers;
  14216. {
  14217. auto res =
  14218. cli.Post("/post-items", {}, items, providers); // empty providers
  14219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14220. ASSERT_EQ(StatusCode::OK_200, res->status);
  14221. }
  14222. providers.push_back({"name3",
  14223. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14224. // test the offset is given correctly at each step
  14225. if (!offset)
  14226. sink.os.write(rand1.data(), 30);
  14227. else if (offset == 30)
  14228. sink.os.write(rand1.data() + 30, 300);
  14229. else if (offset == 330)
  14230. sink.os.write(rand1.data() + 330, 670);
  14231. else if (offset == rand1.size())
  14232. sink.done();
  14233. return true;
  14234. },
  14235. "filename3",
  14236. {}});
  14237. providers.push_back({"name4",
  14238. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14239. // test the offset is given correctly at each step
  14240. if (!offset)
  14241. sink.os.write(rand2.data(), 2000);
  14242. else if (offset == 2000)
  14243. sink.os.write(rand2.data() + 2000, 1);
  14244. else if (offset == 2001)
  14245. sink.os.write(rand2.data() + 2001, 999);
  14246. else if (offset == rand2.size())
  14247. sink.done();
  14248. return true;
  14249. },
  14250. "filename4",
  14251. {}});
  14252. {
  14253. auto res = cli.Post("/post-providers", {}, {}, providers);
  14254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14255. ASSERT_EQ(StatusCode::OK_200, res->status);
  14256. }
  14257. {
  14258. auto res = cli.Post("/post-both", {}, items, providers);
  14259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14260. ASSERT_EQ(StatusCode::OK_200, res->status);
  14261. }
  14262. }
  14263. }
  14264. TEST(MultipartFormDataTest, BadHeader) {
  14265. Server svr;
  14266. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14267. res.set_content("ok", "text/plain");
  14268. });
  14269. thread t = thread([&] { svr.listen(HOST, PORT); });
  14270. auto se = detail::scope_exit([&] {
  14271. svr.stop();
  14272. t.join();
  14273. ASSERT_FALSE(svr.is_running());
  14274. });
  14275. svr.wait_until_ready();
  14276. const std::string body =
  14277. "This is the preamble. It is to be ignored, though it\r\n"
  14278. "is a handy place for composition agents to include an\r\n"
  14279. "explanatory note to non-MIME conformant readers.\r\n"
  14280. "\r\n"
  14281. "\r\n"
  14282. "--simple boundary\r\n"
  14283. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14284. ": BAD...\r\n"
  14285. "\r\n"
  14286. "value1\r\n"
  14287. "--simple boundary\r\n"
  14288. "Content-Disposition: form-data; name=\"field2\"; "
  14289. "filename=\"example.txt\"\r\n"
  14290. "\r\n"
  14291. "value2\r\n"
  14292. "--simple boundary--\r\n"
  14293. "This is the epilogue. It is also to be ignored.\r\n";
  14294. std::string content_type =
  14295. R"(multipart/form-data; boundary="simple boundary")";
  14296. Client cli(HOST, PORT);
  14297. auto res = cli.Post("/post", body, content_type.c_str());
  14298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14299. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14300. }
  14301. TEST(MultipartFormDataTest, WithPreamble) {
  14302. Server svr;
  14303. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14304. res.set_content("ok", "text/plain");
  14305. });
  14306. thread t = thread([&] { svr.listen(HOST, PORT); });
  14307. auto se = detail::scope_exit([&] {
  14308. svr.stop();
  14309. t.join();
  14310. ASSERT_FALSE(svr.is_running());
  14311. });
  14312. svr.wait_until_ready();
  14313. const std::string body =
  14314. "This is the preamble. It is to be ignored, though it\r\n"
  14315. "is a handy place for composition agents to include an\r\n"
  14316. "explanatory note to non-MIME conformant readers.\r\n"
  14317. "\r\n"
  14318. "\r\n"
  14319. "--simple boundary\r\n"
  14320. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14321. "\r\n"
  14322. "value1\r\n"
  14323. "--simple boundary\r\n"
  14324. "Content-Disposition: form-data; name=\"field2\"; "
  14325. "filename=\"example.txt\"\r\n"
  14326. "\r\n"
  14327. "value2\r\n"
  14328. "--simple boundary--\r\n"
  14329. "This is the epilogue. It is also to be ignored.\r\n";
  14330. std::string content_type =
  14331. R"(multipart/form-data; boundary="simple boundary")";
  14332. Client cli(HOST, PORT);
  14333. auto res = cli.Post("/post", body, content_type.c_str());
  14334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14335. EXPECT_EQ(StatusCode::OK_200, res->status);
  14336. }
  14337. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14339. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14340. const ContentReader &content_reader) {
  14341. if (req.is_multipart_form_data()) {
  14342. std::vector<FormData> items;
  14343. content_reader(
  14344. [&](const FormData &file) {
  14345. items.push_back(file);
  14346. return true;
  14347. },
  14348. [&](const char *data, size_t data_length) {
  14349. items.back().content.append(data, data_length);
  14350. return true;
  14351. });
  14352. EXPECT_TRUE(std::string(items[0].name) == "document");
  14353. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14354. EXPECT_TRUE(items[0].filename == "2MB_data");
  14355. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14356. EXPECT_TRUE(items[1].name == "hello");
  14357. EXPECT_TRUE(items[1].content == "world");
  14358. EXPECT_TRUE(items[1].filename == "");
  14359. EXPECT_TRUE(items[1].content_type == "");
  14360. } else {
  14361. std::string body;
  14362. content_reader([&](const char *data, size_t data_length) {
  14363. body.append(data, data_length);
  14364. return true;
  14365. });
  14366. }
  14367. });
  14368. auto port = svr.bind_to_any_port("localhost");
  14369. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14370. auto se = detail::scope_exit([&] {
  14371. svr.stop();
  14372. t.join();
  14373. ASSERT_FALSE(svr.is_running());
  14374. });
  14375. svr.wait_until_ready();
  14376. {
  14377. std::string data(1024 * 1024 * 2, '.');
  14378. std::stringstream buffer;
  14379. buffer << data;
  14380. SSLClient cli("localhost", port);
  14381. cli.enable_server_certificate_verification(false);
  14382. UploadFormDataItems items{
  14383. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14384. {"hello", "world", "", ""},
  14385. };
  14386. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14388. ASSERT_EQ(StatusCode::OK_200, res->status);
  14389. }
  14390. }
  14391. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14392. std::string data(1024 * 1024 * 2, '&');
  14393. std::stringstream buffer;
  14394. buffer << data;
  14395. Client cli("https://localhost:8080");
  14396. UploadFormDataItems items{
  14397. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14398. {"hello", "world", "", ""},
  14399. };
  14400. for (const char &c : " \t\r\n") {
  14401. auto res =
  14402. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14403. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14404. ASSERT_FALSE(res);
  14405. }
  14406. }
  14407. TEST(MultipartFormDataTest, PutFormData) {
  14408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14409. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14410. const ContentReader &content_reader) {
  14411. if (req.is_multipart_form_data()) {
  14412. std::vector<FormData> items;
  14413. content_reader(
  14414. [&](const FormData &file) {
  14415. items.push_back(file);
  14416. return true;
  14417. },
  14418. [&](const char *data, size_t data_length) {
  14419. items.back().content.append(data, data_length);
  14420. return true;
  14421. });
  14422. EXPECT_TRUE(std::string(items[0].name) == "document");
  14423. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14424. EXPECT_TRUE(items[0].filename == "2MB_data");
  14425. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14426. EXPECT_TRUE(items[1].name == "hello");
  14427. EXPECT_TRUE(items[1].content == "world");
  14428. EXPECT_TRUE(items[1].filename == "");
  14429. EXPECT_TRUE(items[1].content_type == "");
  14430. } else {
  14431. std::string body;
  14432. content_reader([&](const char *data, size_t data_length) {
  14433. body.append(data, data_length);
  14434. return true;
  14435. });
  14436. }
  14437. });
  14438. auto port = svr.bind_to_any_port("localhost");
  14439. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14440. auto se = detail::scope_exit([&] {
  14441. svr.stop();
  14442. t.join();
  14443. ASSERT_FALSE(svr.is_running());
  14444. });
  14445. svr.wait_until_ready();
  14446. {
  14447. std::string data(1024 * 1024 * 2, '&');
  14448. std::stringstream buffer;
  14449. buffer << data;
  14450. SSLClient cli("localhost", port);
  14451. cli.enable_server_certificate_verification(false);
  14452. UploadFormDataItems items{
  14453. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14454. {"hello", "world", "", ""},
  14455. };
  14456. auto res = cli.Put("/put", items);
  14457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14458. ASSERT_EQ(StatusCode::OK_200, res->status);
  14459. }
  14460. }
  14461. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14463. svr.Put("/put_customboundary",
  14464. [&](const Request &req, const Response & /*res*/,
  14465. const ContentReader &content_reader) {
  14466. if (req.is_multipart_form_data()) {
  14467. std::vector<FormData> items;
  14468. content_reader(
  14469. [&](const FormData &file) {
  14470. items.push_back(file);
  14471. return true;
  14472. },
  14473. [&](const char *data, size_t data_length) {
  14474. items.back().content.append(data, data_length);
  14475. return true;
  14476. });
  14477. EXPECT_TRUE(std::string(items[0].name) == "document");
  14478. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14479. EXPECT_TRUE(items[0].filename == "2MB_data");
  14480. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14481. EXPECT_TRUE(items[1].name == "hello");
  14482. EXPECT_TRUE(items[1].content == "world");
  14483. EXPECT_TRUE(items[1].filename == "");
  14484. EXPECT_TRUE(items[1].content_type == "");
  14485. } else {
  14486. std::string body;
  14487. content_reader([&](const char *data, size_t data_length) {
  14488. body.append(data, data_length);
  14489. return true;
  14490. });
  14491. }
  14492. });
  14493. auto port = svr.bind_to_any_port("localhost");
  14494. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14495. auto se = detail::scope_exit([&] {
  14496. svr.stop();
  14497. t.join();
  14498. ASSERT_FALSE(svr.is_running());
  14499. });
  14500. svr.wait_until_ready();
  14501. {
  14502. std::string data(1024 * 1024 * 2, '&');
  14503. std::stringstream buffer;
  14504. buffer << data;
  14505. SSLClient cli("localhost", port);
  14506. cli.enable_server_certificate_verification(false);
  14507. UploadFormDataItems items{
  14508. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14509. {"hello", "world", "", ""},
  14510. };
  14511. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14513. ASSERT_EQ(StatusCode::OK_200, res->status);
  14514. }
  14515. }
  14516. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14517. std::string data(1024 * 1024 * 2, '&');
  14518. std::stringstream buffer;
  14519. buffer << data;
  14520. Client cli("https://localhost:8080");
  14521. cli.enable_server_certificate_verification(false);
  14522. UploadFormDataItems items{
  14523. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14524. {"hello", "world", "", ""},
  14525. };
  14526. for (const char &c : " \t\r\n") {
  14527. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14528. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14529. ASSERT_FALSE(res);
  14530. }
  14531. }
  14532. TEST(MultipartFormDataTest, AlternateFilename) {
  14533. auto handled = false;
  14534. Server svr;
  14535. svr.Post("/test", [&](const Request &req, Response &res) {
  14536. ASSERT_EQ(2u, req.form.files.size());
  14537. ASSERT_EQ(1u, req.form.fields.size());
  14538. // Test files
  14539. const auto &file1 = req.form.get_file("file1");
  14540. ASSERT_EQ("file1", file1.name);
  14541. ASSERT_EQ("A.txt", file1.filename);
  14542. ASSERT_EQ("text/plain", file1.content_type);
  14543. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14544. const auto &file2 = req.form.get_file("file2");
  14545. ASSERT_EQ("file2", file2.name);
  14546. ASSERT_EQ("a.html", file2.filename);
  14547. ASSERT_EQ("text/html", file2.content_type);
  14548. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14549. file2.content);
  14550. // Test text field
  14551. const auto &text = req.form.get_field("text");
  14552. ASSERT_EQ("text default", text);
  14553. res.set_content("ok", "text/plain");
  14554. handled = true;
  14555. });
  14556. thread t = thread([&] { svr.listen(HOST, PORT); });
  14557. auto se = detail::scope_exit([&] {
  14558. svr.stop();
  14559. t.join();
  14560. ASSERT_FALSE(svr.is_running());
  14561. ASSERT_TRUE(handled);
  14562. });
  14563. svr.wait_until_ready();
  14564. auto req = "POST /test HTTP/1.1\r\n"
  14565. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14566. "Content-Length: 399\r\n"
  14567. "\r\n"
  14568. "----------\r\n"
  14569. "Content-Disposition: form-data; name=\"text\"\r\n"
  14570. "\r\n"
  14571. "text default\r\n"
  14572. "----------\r\n"
  14573. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14574. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14575. "Content-Type: text/plain\r\n"
  14576. "\r\n"
  14577. "Content of a.txt.\r\n"
  14578. "\r\n"
  14579. "----------\r\n"
  14580. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14581. "\"a.html\"\r\n"
  14582. "Content-Type: text/html\r\n"
  14583. "\r\n"
  14584. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14585. "\r\n"
  14586. "------------\r\n";
  14587. ASSERT_TRUE(send_request(1, req));
  14588. }
  14589. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14590. auto handled = false;
  14591. Server svr;
  14592. svr.Post("/test", [&](const Request &req, Response &res) {
  14593. // Case-insensitive "utf-8''" prefix with a long value
  14594. const auto &file = req.form.get_file("file1");
  14595. ASSERT_EQ("file1", file.name);
  14596. // 8000 chars exercises both the Content-Disposition parser and the
  14597. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14598. // Prior to the fix, std::regex_match on this header would cause O(N)
  14599. // stack recursion in libstdc++, leading to SIGSEGV.
  14600. std::string expected_filename(8000, 'A');
  14601. ASSERT_EQ(expected_filename, file.filename);
  14602. res.set_content("ok", "text/plain");
  14603. handled = true;
  14604. });
  14605. thread t = thread([&] { svr.listen(HOST, PORT); });
  14606. auto se = detail::scope_exit([&] {
  14607. svr.stop();
  14608. t.join();
  14609. ASSERT_FALSE(svr.is_running());
  14610. ASSERT_TRUE(handled);
  14611. });
  14612. svr.wait_until_ready();
  14613. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14614. // Regression test for GHSA-qq6v-r583-3h69
  14615. std::string long_filename(8000, 'A');
  14616. std::string body = "----------\r\n"
  14617. "Content-Disposition: form-data; name=\"file1\"; "
  14618. "filename*=\"Utf-8''" +
  14619. long_filename +
  14620. "\"\r\n"
  14621. "\r\n"
  14622. "hello\r\n"
  14623. "------------\r\n";
  14624. auto req = "POST /test HTTP/1.1\r\n"
  14625. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14626. "Content-Length: " +
  14627. std::to_string(body.size()) + "\r\n\r\n" + body;
  14628. ASSERT_TRUE(send_request(1, req));
  14629. }
  14630. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14631. auto handled = false;
  14632. Server svr;
  14633. svr.Post("/test", [&](const Request &req, Response &) {
  14634. ASSERT_EQ(2u, req.form.fields.size());
  14635. const auto &text1 = req.form.get_field("text1");
  14636. ASSERT_EQ("text1", text1);
  14637. const auto &text2 = req.form.get_field("text2");
  14638. ASSERT_EQ("text2", text2);
  14639. handled = true;
  14640. });
  14641. thread t = thread([&] { svr.listen(HOST, PORT); });
  14642. auto se = detail::scope_exit([&] {
  14643. svr.stop();
  14644. t.join();
  14645. ASSERT_FALSE(svr.is_running());
  14646. ASSERT_TRUE(handled);
  14647. });
  14648. svr.wait_until_ready();
  14649. auto req = "POST /test HTTP/1.1\r\n"
  14650. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14651. "Content-Length: 146\r\n"
  14652. "\r\n----------\r\n"
  14653. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14654. "\r\n"
  14655. "text1"
  14656. "\r\n----------\r\n"
  14657. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14658. "\r\n"
  14659. "text2"
  14660. "\r\n------------";
  14661. std::string response;
  14662. ASSERT_TRUE(send_request(1, req, &response));
  14663. ASSERT_EQ("200", response.substr(9, 3));
  14664. }
  14665. TEST(MultipartFormDataTest, ContentLength) {
  14666. auto handled = false;
  14667. Server svr;
  14668. svr.Post("/test", [&](const Request &req, Response &) {
  14669. ASSERT_EQ(2u, req.form.fields.size());
  14670. const auto &text1 = req.form.get_field("text1");
  14671. ASSERT_EQ("text1", text1);
  14672. const auto &text2 = req.form.get_field("text2");
  14673. ASSERT_EQ("text2", text2);
  14674. handled = true;
  14675. });
  14676. thread t = thread([&] { svr.listen(HOST, PORT); });
  14677. auto se = detail::scope_exit([&] {
  14678. svr.stop();
  14679. t.join();
  14680. ASSERT_FALSE(svr.is_running());
  14681. ASSERT_TRUE(handled);
  14682. });
  14683. svr.wait_until_ready();
  14684. auto req = "POST /test HTTP/1.1\r\n"
  14685. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14686. "Content-Length: 167\r\n"
  14687. "\r\n----------\r\n"
  14688. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14689. "Content-Length: 5\r\n"
  14690. "\r\n"
  14691. "text1"
  14692. "\r\n----------\r\n"
  14693. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14694. "\r\n"
  14695. "text2"
  14696. "\r\n------------\r\n";
  14697. std::string response;
  14698. ASSERT_TRUE(send_request(1, req, &response));
  14699. ASSERT_EQ("200", response.substr(9, 3));
  14700. }
  14701. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14702. auto handled = false;
  14703. Server svr;
  14704. svr.Post("/test", [&](const Request &req, Response &) {
  14705. ASSERT_EQ(2u, req.form.fields.size());
  14706. const auto &text1 = req.form.get_field("text1");
  14707. ASSERT_EQ("text1", text1);
  14708. // TODO: Add header access for text fields if needed
  14709. const auto &text2 = req.form.get_field("text2");
  14710. ASSERT_EQ("text2", text2);
  14711. // TODO: Header access for text fields needs to be implemented
  14712. // auto &headers = it->second.headers;
  14713. // ASSERT_EQ(3U, headers.size());
  14714. // auto custom_header = headers.find("x-whatever");
  14715. // ASSERT_TRUE(custom_header != headers.end());
  14716. // ASSERT_NE("customvalue", custom_header->second);
  14717. // ASSERT_EQ("CustomValue", custom_header->second);
  14718. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14719. handled = true;
  14720. });
  14721. thread t = thread([&] { svr.listen(HOST, PORT); });
  14722. auto se = detail::scope_exit([&] {
  14723. svr.stop();
  14724. t.join();
  14725. ASSERT_FALSE(svr.is_running());
  14726. ASSERT_TRUE(handled);
  14727. });
  14728. svr.wait_until_ready();
  14729. auto req = "POST /test HTTP/1.1\r\n"
  14730. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14731. "Content-Length: 232\r\n"
  14732. "\r\n----------\r\n"
  14733. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14734. "Content-Length: 5\r\n"
  14735. "X-Test: 1\r\n"
  14736. "\r\n"
  14737. "text1"
  14738. "\r\n----------\r\n"
  14739. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14740. "Content-Type: text/plain\r\n"
  14741. "X-Whatever: CustomValue\r\n"
  14742. "\r\n"
  14743. "text2"
  14744. "\r\n------------\r\n"
  14745. "That should be disregarded. Not even read";
  14746. std::string response;
  14747. ASSERT_TRUE(send_request(1, req, &response));
  14748. ASSERT_EQ("200", response.substr(9, 3));
  14749. }
  14750. TEST(MultipartFormDataTest, LargeHeader) {
  14751. auto handled = false;
  14752. Server svr;
  14753. svr.Post("/test", [&](const Request &req, Response &) {
  14754. ASSERT_EQ(1u, req.form.fields.size());
  14755. const auto &text = req.form.get_field("name1");
  14756. ASSERT_EQ("text1", text);
  14757. handled = true;
  14758. });
  14759. thread t = thread([&] { svr.listen(HOST, PORT); });
  14760. auto se = detail::scope_exit([&] {
  14761. svr.stop();
  14762. t.join();
  14763. ASSERT_FALSE(svr.is_running());
  14764. ASSERT_TRUE(handled);
  14765. });
  14766. svr.wait_until_ready();
  14767. auto boundary = std::string("cpp-httplib-multipart-data");
  14768. std::string content = "--" + boundary +
  14769. "\r\n"
  14770. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14771. "\r\n"
  14772. "text1\r\n"
  14773. "--" +
  14774. boundary + "--\r\n";
  14775. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14776. "Content-Type: multipart/form-data;boundary=" +
  14777. boundary +
  14778. "\r\n"
  14779. "Content-Length: " +
  14780. std::to_string(content.size()) +
  14781. "\r\n"
  14782. "Dummy-Header: ";
  14783. std::string header_suffix = "\r\n"
  14784. "\r\n";
  14785. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14786. size_t header_dummy_size =
  14787. read_buff_size -
  14788. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14789. auto header_dummy = std::string(header_dummy_size, '@');
  14790. auto req = header_prefix + header_dummy + header_suffix + content;
  14791. std::string response;
  14792. ASSERT_TRUE(send_request(1, req, &response));
  14793. ASSERT_EQ("200", response.substr(9, 3));
  14794. }
  14795. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14796. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14797. // (not chunked Transfer-Encoding) after the streaming refactor.
  14798. auto handled = false;
  14799. Server svr;
  14800. svr.Post("/upload", [&](const Request &req, Response &res) {
  14801. auto cl_it = req.headers.find("Content-Length");
  14802. EXPECT_TRUE(cl_it != req.headers.end());
  14803. auto te_it = req.headers.find("Transfer-Encoding");
  14804. EXPECT_TRUE(te_it == req.headers.end());
  14805. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14806. res.set_content("ok", "text/plain");
  14807. handled = true;
  14808. });
  14809. auto port = svr.bind_to_any_port(HOST);
  14810. auto t = thread([&] { svr.listen_after_bind(); });
  14811. auto se = detail::scope_exit([&] {
  14812. svr.stop();
  14813. t.join();
  14814. ASSERT_FALSE(svr.is_running());
  14815. ASSERT_TRUE(handled);
  14816. });
  14817. svr.wait_until_ready();
  14818. UploadFormDataItems items = {
  14819. {"field1", "hello", "", "text/plain"},
  14820. {"file1", "world", "test.txt", "application/octet-stream"},
  14821. };
  14822. Client cli(HOST, port);
  14823. auto res = cli.Post("/upload", {}, items);
  14824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14825. EXPECT_EQ(StatusCode::OK_200, res->status);
  14826. }
  14827. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14828. // Verify that make_multipart_content_provider coalesces many small segments
  14829. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14830. constexpr size_t kItemCount = 1000;
  14831. UploadFormDataItems items;
  14832. items.reserve(kItemCount);
  14833. for (size_t i = 0; i < kItemCount; i++) {
  14834. items.push_back(
  14835. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14836. }
  14837. const std::string boundary = "----test-boundary";
  14838. auto content_length = detail::get_multipart_content_length(items, boundary);
  14839. auto provider = detail::make_multipart_content_provider(items, boundary);
  14840. // Drive the provider the same way write_content_with_progress does
  14841. size_t write_count = 0;
  14842. size_t total_bytes = 0;
  14843. DataSink sink;
  14844. size_t offset = 0;
  14845. sink.write = [&](const char *d, size_t l) -> bool {
  14846. (void)d;
  14847. write_count++;
  14848. total_bytes += l;
  14849. offset += l;
  14850. return true;
  14851. };
  14852. sink.is_writable = []() -> bool { return true; };
  14853. while (offset < content_length) {
  14854. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14855. }
  14856. EXPECT_EQ(content_length, total_bytes);
  14857. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14858. // With buffering into 64KB blocks, write_count should be much smaller.
  14859. auto segment_count = 3 * kItemCount + 1;
  14860. EXPECT_LT(write_count, segment_count / 10);
  14861. }
  14862. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14863. // Integration test: send many UploadFormDataItems and verify the server
  14864. // receives all of them correctly (#2410).
  14865. constexpr size_t kItemCount = 500;
  14866. auto handled = false;
  14867. Server svr;
  14868. svr.Post("/upload", [&](const Request &req, Response &res) {
  14869. EXPECT_EQ(kItemCount, req.form.fields.size());
  14870. for (size_t i = 0; i < kItemCount; i++) {
  14871. auto key = "field" + std::to_string(i);
  14872. auto val = "value" + std::to_string(i);
  14873. auto it = req.form.fields.find(key);
  14874. if (it != req.form.fields.end()) {
  14875. EXPECT_EQ(val, it->second.content);
  14876. } else {
  14877. ADD_FAILURE() << "Missing field: " << key;
  14878. }
  14879. }
  14880. res.set_content("ok", "text/plain");
  14881. handled = true;
  14882. });
  14883. auto port = svr.bind_to_any_port(HOST);
  14884. auto t = thread([&] { svr.listen_after_bind(); });
  14885. auto se = detail::scope_exit([&] {
  14886. svr.stop();
  14887. t.join();
  14888. ASSERT_FALSE(svr.is_running());
  14889. ASSERT_TRUE(handled);
  14890. });
  14891. svr.wait_until_ready();
  14892. UploadFormDataItems items;
  14893. items.reserve(kItemCount);
  14894. for (size_t i = 0; i < kItemCount; i++) {
  14895. items.push_back(
  14896. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14897. }
  14898. Client cli(HOST, port);
  14899. auto res = cli.Post("/upload", items);
  14900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14901. EXPECT_EQ(StatusCode::OK_200, res->status);
  14902. }
  14903. TEST(MultipartFormDataTest, MakeFileProvider) {
  14904. // Verify make_file_provider sends a file's contents correctly.
  14905. const std::string file_content(4096, 'Z');
  14906. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14907. {
  14908. std::ofstream ofs(tmp_path, std::ios::binary);
  14909. ofs.write(file_content.data(),
  14910. static_cast<std::streamsize>(file_content.size()));
  14911. }
  14912. auto handled = false;
  14913. Server svr;
  14914. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14915. const ContentReader &content_reader) {
  14916. ASSERT_TRUE(req.is_multipart_form_data());
  14917. std::vector<FormData> items;
  14918. content_reader(
  14919. [&](const FormData &file) {
  14920. items.push_back(file);
  14921. return true;
  14922. },
  14923. [&](const char *data, size_t data_length) {
  14924. items.back().content.append(data, data_length);
  14925. return true;
  14926. });
  14927. ASSERT_EQ(1u, items.size());
  14928. EXPECT_EQ("myfile", items[0].name);
  14929. EXPECT_EQ("data.bin", items[0].filename);
  14930. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14931. EXPECT_EQ(file_content, items[0].content);
  14932. handled = true;
  14933. });
  14934. auto port = svr.bind_to_any_port(HOST);
  14935. auto t = thread([&] { svr.listen_after_bind(); });
  14936. auto se = detail::scope_exit([&] {
  14937. svr.stop();
  14938. t.join();
  14939. ASSERT_FALSE(svr.is_running());
  14940. ASSERT_TRUE(handled);
  14941. std::remove(tmp_path.c_str());
  14942. });
  14943. svr.wait_until_ready();
  14944. FormDataProviderItems providers;
  14945. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14946. "application/octet-stream"));
  14947. Client cli(HOST, port);
  14948. auto res = cli.Post("/upload", {}, {}, providers);
  14949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14950. EXPECT_EQ(StatusCode::OK_200, res->status);
  14951. }
  14952. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14953. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14954. // (100) headers is rejected with a 400 Bad Request response.
  14955. Server svr;
  14956. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14957. res.set_content("ok", "text/plain");
  14958. });
  14959. thread t = thread([&] { svr.listen(HOST, PORT); });
  14960. auto se = detail::scope_exit([&] {
  14961. svr.stop();
  14962. t.join();
  14963. ASSERT_FALSE(svr.is_running());
  14964. });
  14965. svr.wait_until_ready();
  14966. // Build a multipart part with 101 custom headers (exceeding
  14967. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14968. std::stringstream body;
  14969. body << "--simpleboundary\r\n"
  14970. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14971. for (int i = 0; i < 101; i++) {
  14972. body << "X-Custom-Header-" << i << ": value\r\n";
  14973. }
  14974. body << "\r\n"
  14975. << "value1\r\n"
  14976. << "--simpleboundary--\r\n";
  14977. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14978. Client cli(HOST, PORT);
  14979. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14981. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14982. }
  14983. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14984. // A body that never contains the declared boundary must not be accumulated
  14985. // while the parser waits for it. Buffering it would also make every read
  14986. // rescan everything seen so far, which is quadratic in the body size.
  14987. Server svr;
  14988. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14989. res.set_content("ok", "text/plain");
  14990. });
  14991. auto port = svr.bind_to_any_port(HOST);
  14992. thread t = 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. Client cli(HOST, port);
  15000. cli.set_read_timeout(60, 0);
  15001. cli.set_write_timeout(60, 0);
  15002. // '-' is the worst case: it matches the first character of the boundary, so
  15003. // every position has to be checked against it.
  15004. auto post_dashes = [&](size_t size) {
  15005. const std::string body(size, '-');
  15006. auto start = std::chrono::steady_clock::now();
  15007. auto res =
  15008. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15009. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15010. std::chrono::steady_clock::now() - start)
  15011. .count();
  15012. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15013. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15014. return ms;
  15015. };
  15016. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15017. // Windows.
  15018. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15019. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15020. // Comparing the two sizes rather than checking an absolute duration keeps
  15021. // this meaningful across build types and CI load, both of which move the
  15022. // absolute numbers by more than an order of magnitude. Four times the bytes
  15023. // costs about four times the time when parsing is linear, and about sixteen
  15024. // times when the body is buffered and rescanned.
  15025. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15026. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15027. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15028. << "ms, which suggests the body is being buffered and rescanned";
  15029. }
  15030. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15031. // A boundary can only be followed by CRLF or by "--", so anything else is
  15032. // malformed no matter what comes next. The parser must say so right away
  15033. // instead of buffering the rest of the declared body.
  15034. Server svr;
  15035. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15036. res.set_content("ok", "text/plain");
  15037. });
  15038. auto port = svr.bind_to_any_port(HOST);
  15039. thread t = thread([&] { svr.listen_after_bind(); });
  15040. auto se = detail::scope_exit([&] {
  15041. svr.stop();
  15042. t.join();
  15043. ASSERT_FALSE(svr.is_running());
  15044. });
  15045. svr.wait_until_ready();
  15046. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15047. // buffers instead of failing would still be waiting for the remaining bytes.
  15048. const std::string body = "--zzzz\r\n"
  15049. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15050. "\r\n"
  15051. "text1"
  15052. "\r\n--zzzzXX";
  15053. const std::string req = "POST /post HTTP/1.1\r\n"
  15054. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15055. "Content-Length: 1048576\r\n"
  15056. "\r\n" +
  15057. body;
  15058. std::string response;
  15059. ASSERT_TRUE(send_request(3, req, &response, port));
  15060. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15061. EXPECT_EQ("400", response.substr(9, 3));
  15062. }
  15063. // Posts a multipart body split into two writes, so that the server sees the
  15064. // split at whatever offset the caller chose, and expects the single "text1"
  15065. // field to come through.
  15066. static void expect_split_multipart_ok(const std::string &body1,
  15067. const std::string &body2) {
  15068. auto handled = false;
  15069. Server svr;
  15070. svr.Post("/post", [&](const Request &req, Response &) {
  15071. EXPECT_EQ(1u, req.form.fields.size());
  15072. EXPECT_EQ("text1", req.form.get_field("text1"));
  15073. handled = true;
  15074. });
  15075. auto port = svr.bind_to_any_port(HOST);
  15076. thread t = thread([&] { svr.listen_after_bind(); });
  15077. auto se = detail::scope_exit([&] {
  15078. svr.stop();
  15079. t.join();
  15080. ASSERT_FALSE(svr.is_running());
  15081. ASSERT_TRUE(handled);
  15082. });
  15083. svr.wait_until_ready();
  15084. // "Connection: close" makes the server close once it has answered, so the
  15085. // response drain ends immediately instead of idling until the read timeout.
  15086. const std::string head =
  15087. "POST /post HTTP/1.1\r\n"
  15088. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15089. "Connection: close\r\n"
  15090. "Content-Length: " +
  15091. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15092. std::string response;
  15093. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15094. ASSERT_GE(response.size(), 12u) << "no response";
  15095. EXPECT_EQ("200", response.substr(9, 3));
  15096. }
  15097. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15098. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15099. // ignored, including when it does not arrive in the same read as the
  15100. // close-delimiter itself.
  15101. expect_split_multipart_ok("--zzzz\r\n"
  15102. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15103. "\r\n"
  15104. "text1"
  15105. "\r\n--zzzz--",
  15106. "\r\nthis epilogue must be ignored\r\n");
  15107. }
  15108. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15109. // The initial boundary may be preceded by a preamble of any length and may
  15110. // straddle a read boundary. Discarding data while waiting for it must not
  15111. // throw away a partial boundary sitting at the end of the buffer.
  15112. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15113. "zz\r\n"
  15114. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15115. "\r\n"
  15116. "text1"
  15117. "\r\n--zzzz--\r\n");
  15118. }
  15119. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15120. // The received boundary was only checked for being non-empty, so it could be
  15121. // as long as a header is allowed to be. The parser scans the body for
  15122. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15123. // costs a nearly full comparison at nearly every position, making the
  15124. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15125. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15126. Server svr;
  15127. svr.Post("/post", [](const Request &req, Response &res) {
  15128. EXPECT_EQ(1u, req.form.fields.size());
  15129. EXPECT_EQ("text1", req.form.get_field("text1"));
  15130. res.set_content("ok", "text/plain");
  15131. });
  15132. auto port = svr.bind_to_any_port(HOST);
  15133. thread t = thread([&] { svr.listen_after_bind(); });
  15134. auto se = detail::scope_exit([&] {
  15135. svr.stop();
  15136. t.join();
  15137. ASSERT_FALSE(svr.is_running());
  15138. });
  15139. svr.wait_until_ready();
  15140. Client cli(HOST, port);
  15141. auto post_with_boundary_of_length = [&](size_t len) {
  15142. const std::string boundary(len, 'a');
  15143. const std::string body =
  15144. "--" + boundary +
  15145. "\r\n"
  15146. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15147. "\r\n"
  15148. "text1"
  15149. "\r\n--" +
  15150. boundary + "--\r\n";
  15151. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15152. };
  15153. auto res = post_with_boundary_of_length(70);
  15154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15155. EXPECT_EQ(StatusCode::OK_200, res->status);
  15156. res = post_with_boundary_of_length(71);
  15157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15158. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15159. }
  15160. TEST(MakeFileBodyTest, Basic) {
  15161. const std::string file_content(4096, 'Z');
  15162. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15163. {
  15164. std::ofstream ofs(tmp_path, std::ios::binary);
  15165. ofs.write(file_content.data(),
  15166. static_cast<std::streamsize>(file_content.size()));
  15167. }
  15168. auto handled = false;
  15169. Server svr;
  15170. svr.Post("/upload", [&](const Request &req, Response &res) {
  15171. EXPECT_EQ(file_content, req.body);
  15172. handled = true;
  15173. res.status = StatusCode::OK_200;
  15174. });
  15175. auto port = svr.bind_to_any_port(HOST);
  15176. auto t = thread([&] { svr.listen_after_bind(); });
  15177. auto se = detail::scope_exit([&] {
  15178. svr.stop();
  15179. t.join();
  15180. ASSERT_FALSE(svr.is_running());
  15181. ASSERT_TRUE(handled);
  15182. std::remove(tmp_path.c_str());
  15183. });
  15184. svr.wait_until_ready();
  15185. auto fb = make_file_body(tmp_path);
  15186. ASSERT_GT(fb.first, 0u);
  15187. Client cli(HOST, port);
  15188. auto res =
  15189. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15191. EXPECT_EQ(StatusCode::OK_200, res->status);
  15192. }
  15193. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15194. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15195. {
  15196. std::ofstream ofs(path, std::ios::binary);
  15197. const std::string content(100, 'A');
  15198. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15199. }
  15200. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15201. auto body = make_file_body(path);
  15202. ASSERT_EQ(100u, body.first);
  15203. ASSERT_TRUE(static_cast<bool>(body.second));
  15204. // Rewritten shorter after its length was measured - and, on a server, after
  15205. // that length has already gone out as Content-Length.
  15206. {
  15207. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15208. const std::string content(10, 'A');
  15209. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15210. }
  15211. std::string written;
  15212. DataSink sink;
  15213. sink.write = [&](const char *d, size_t l) {
  15214. written.append(d, l);
  15215. return true;
  15216. };
  15217. // The provider has to report failure. write_content_with_progress() advances
  15218. // its offset only by what was written, so a provider that returns true
  15219. // without completing the length it promised is called again straight away,
  15220. // and again.
  15221. EXPECT_FALSE(body.second(0, body.first, sink));
  15222. EXPECT_EQ(std::string(10, 'A'), written);
  15223. }
  15224. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15225. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15226. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15227. {
  15228. std::ofstream ofs(path, std::ios::binary);
  15229. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15230. }
  15231. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15232. auto body = make_file_body(path);
  15233. ASSERT_EQ(content.size(), body.first);
  15234. ASSERT_TRUE(static_cast<bool>(body.second));
  15235. std::string written;
  15236. DataSink sink;
  15237. sink.write = [&](const char *d, size_t l) {
  15238. written.append(d, l);
  15239. return true;
  15240. };
  15241. EXPECT_TRUE(body.second(0, body.first, sink));
  15242. EXPECT_EQ(content, written);
  15243. }
  15244. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15245. static constexpr unsigned int number_of_tasks{1000000};
  15246. std::atomic_uint count{0};
  15247. std::unique_ptr<TaskQueue> task_queue{
  15248. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15249. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15250. auto queued = task_queue->enqueue(
  15251. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15252. EXPECT_TRUE(queued);
  15253. }
  15254. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15255. task_queue->shutdown();
  15256. #else
  15257. EXPECT_NO_THROW(task_queue->shutdown());
  15258. #endif
  15259. EXPECT_EQ(number_of_tasks, count.load());
  15260. }
  15261. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15262. static constexpr unsigned int number_of_tasks{1000000};
  15263. static constexpr unsigned int qlimit{2};
  15264. unsigned int queued_count{0};
  15265. std::atomic_uint count{0};
  15266. std::unique_ptr<TaskQueue> task_queue{
  15267. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15268. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15269. if (task_queue->enqueue(
  15270. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15271. queued_count++;
  15272. }
  15273. }
  15274. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15275. task_queue->shutdown();
  15276. #else
  15277. EXPECT_NO_THROW(task_queue->shutdown());
  15278. #endif
  15279. EXPECT_EQ(queued_count, count.load());
  15280. EXPECT_TRUE(queued_count <= number_of_tasks);
  15281. EXPECT_TRUE(queued_count >= qlimit);
  15282. }
  15283. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15284. // Use a short idle timeout so a dynamic thread spawns, times out and
  15285. // exits during the test, and the pool keeps working afterwards.
  15286. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15287. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15288. /*idle_timeout_sec=*/1}};
  15289. std::atomic_uint count{0};
  15290. std::condition_variable cv;
  15291. std::mutex mtx;
  15292. bool release = false;
  15293. // Block the base thread so the second task spawns a dynamic thread.
  15294. EXPECT_TRUE(task_queue->enqueue([&] {
  15295. std::unique_lock<std::mutex> lock(mtx);
  15296. while (!release) {
  15297. cv.wait(lock);
  15298. }
  15299. count++;
  15300. }));
  15301. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15302. // Let the dynamic thread finish its task and exceed the idle timeout.
  15303. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15304. {
  15305. std::unique_lock<std::mutex> lock(mtx);
  15306. release = true;
  15307. }
  15308. cv.notify_all();
  15309. // The pool must still accept and run tasks after the dynamic thread exited.
  15310. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15311. task_queue->shutdown();
  15312. EXPECT_EQ(3u, count.load());
  15313. }
  15314. TEST(TaskQueueTest, MaxQueuedRequests) {
  15315. static constexpr unsigned int qlimit{3};
  15316. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15317. std::condition_variable sem_cv;
  15318. std::mutex sem_mtx;
  15319. int credits = 0;
  15320. bool queued;
  15321. /* Fill up the queue with tasks that will block until we give them credits to
  15322. * complete. */
  15323. for (unsigned int n = 0; n <= qlimit;) {
  15324. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15325. std::unique_lock<std::mutex> lock(sem_mtx);
  15326. while (credits <= 0) {
  15327. sem_cv.wait(lock);
  15328. }
  15329. /* Consume the credit and signal the test code if they are all gone. */
  15330. if (--credits == 0) { sem_cv.notify_one(); }
  15331. });
  15332. if (n < qlimit) {
  15333. /* The first qlimit enqueues must succeed. */
  15334. EXPECT_TRUE(queued);
  15335. } else {
  15336. /* The last one will succeed only when the worker thread
  15337. * starts and dequeues the first blocking task. Although
  15338. * not necessary for the correctness of this test, we sleep for
  15339. * a short while to avoid busy waiting. */
  15340. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15341. }
  15342. if (queued) { n++; }
  15343. }
  15344. /* Further enqueues must fail since the queue is full. */
  15345. for (auto i = 0; i < 4; i++) {
  15346. queued = task_queue->enqueue([] {});
  15347. EXPECT_FALSE(queued);
  15348. }
  15349. /* Give the credits to allow the previous tasks to complete. */
  15350. {
  15351. std::unique_lock<std::mutex> lock(sem_mtx);
  15352. credits += qlimit + 1;
  15353. }
  15354. sem_cv.notify_all();
  15355. /* Wait for all the credits to be consumed. */
  15356. {
  15357. std::unique_lock<std::mutex> lock(sem_mtx);
  15358. while (credits > 0) {
  15359. sem_cv.wait(lock);
  15360. }
  15361. }
  15362. /* Check that we are able again to enqueue at least qlimit tasks. */
  15363. for (unsigned int i = 0; i < qlimit; i++) {
  15364. queued = task_queue->enqueue([] {});
  15365. EXPECT_TRUE(queued);
  15366. }
  15367. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15368. task_queue->shutdown();
  15369. #else
  15370. EXPECT_NO_THROW(task_queue->shutdown());
  15371. #endif
  15372. }
  15373. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15374. Server svr;
  15375. std::string method;
  15376. std::string body;
  15377. auto has_content_length = false;
  15378. auto has_transfer_encoding = false;
  15379. std::atomic<int> bad_requests{0};
  15380. // Leftover body bytes get parsed as a malformed request and answered with
  15381. // 400
  15382. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15383. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15384. });
  15385. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15386. res.set_redirect("/down", StatusCode::SeeOther_303);
  15387. });
  15388. svr.Get("/down", [&](const Request &req, Response &res) {
  15389. method = req.method;
  15390. body = req.body;
  15391. has_content_length = req.has_header("Content-Length");
  15392. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15393. res.set_content("ok", "text/plain");
  15394. });
  15395. auto port = svr.bind_to_any_port(HOST);
  15396. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15397. auto se = detail::scope_exit([&] {
  15398. svr.stop();
  15399. thread.join();
  15400. ASSERT_FALSE(svr.is_running());
  15401. });
  15402. svr.wait_until_ready();
  15403. const std::string payload = "SECRET-BODY";
  15404. auto check = [&](Client &cli, const Result &res) {
  15405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15406. EXPECT_EQ(StatusCode::OK_200, res->status);
  15407. EXPECT_EQ("ok", res->body);
  15408. EXPECT_EQ("GET", method);
  15409. EXPECT_TRUE(body.empty());
  15410. EXPECT_FALSE(has_content_length);
  15411. EXPECT_FALSE(has_transfer_encoding);
  15412. // Nothing of the original body may be left on the connection
  15413. auto res2 = cli.Get("/down");
  15414. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15415. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15416. EXPECT_EQ("ok", res2->body);
  15417. EXPECT_EQ(0, bad_requests);
  15418. };
  15419. // With content length
  15420. {
  15421. Client cli(HOST, port);
  15422. cli.set_keep_alive(true);
  15423. cli.set_follow_location(true);
  15424. auto res = cli.Post(
  15425. "/up", payload.size(),
  15426. [&](size_t offset, size_t length, DataSink &sink) {
  15427. return sink.write(payload.data() + offset, length);
  15428. },
  15429. "text/plain");
  15430. check(cli, res);
  15431. }
  15432. // Without content length (chunked)
  15433. {
  15434. Client cli(HOST, port);
  15435. cli.set_keep_alive(true);
  15436. cli.set_follow_location(true);
  15437. auto res = cli.Post(
  15438. "/up",
  15439. [&](size_t /*offset*/, DataSink &sink) {
  15440. sink.write(payload.data(), payload.size());
  15441. sink.done();
  15442. return true;
  15443. },
  15444. "text/plain");
  15445. check(cli, res);
  15446. }
  15447. }
  15448. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15449. Server svr;
  15450. std::string target;
  15451. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15452. // Echo the still-encoded name back in the Location
  15453. const std::string prefix = "/start/";
  15454. res.status = StatusCode::Found_302;
  15455. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15456. });
  15457. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15458. target = req.target;
  15459. res.set_content("ok", "text/plain");
  15460. });
  15461. auto port = svr.bind_to_any_port(HOST);
  15462. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15463. auto se = detail::scope_exit([&] {
  15464. svr.stop();
  15465. thread.join();
  15466. ASSERT_FALSE(svr.is_running());
  15467. });
  15468. svr.wait_until_ready();
  15469. // Decoding the Location path would turn the first four into a path
  15470. // separator, a query delimiter, a fragment delimiter and a different
  15471. // percent-encoded octet. The rest must keep reaching the server as they are.
  15472. const std::vector<std::string> names = {
  15473. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15474. };
  15475. for (auto path_encode : {true, false}) {
  15476. Client cli(HOST, port);
  15477. cli.set_follow_location(true);
  15478. cli.set_path_encode(path_encode);
  15479. for (const auto &name : names) {
  15480. target.clear();
  15481. auto res = cli.Get("/start/" + name);
  15482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15483. EXPECT_EQ(StatusCode::OK_200, res->status);
  15484. EXPECT_EQ("/dest/" + name, target);
  15485. }
  15486. }
  15487. }
  15488. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15489. Server svr;
  15490. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15491. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15492. });
  15493. svr.Get("/hello", [](const Request &req, Response &res) {
  15494. res.set_content(req.get_param_value("key"), "text/plain");
  15495. });
  15496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15497. auto se = detail::scope_exit([&] {
  15498. svr.stop();
  15499. thread.join();
  15500. ASSERT_FALSE(svr.is_running());
  15501. });
  15502. svr.wait_until_ready();
  15503. {
  15504. Client cli(HOST, PORT);
  15505. cli.set_follow_location(true);
  15506. auto res = cli.Get("/");
  15507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15508. EXPECT_EQ(StatusCode::OK_200, res->status);
  15509. EXPECT_EQ("val&key2=val2", res->body);
  15510. }
  15511. }
  15512. #endif
  15513. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15514. Server svr;
  15515. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15516. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15517. });
  15518. svr.Get("/hello", [](const Request &req, Response &res) {
  15519. res.set_content(req.get_param_value("key"), "text/plain");
  15520. });
  15521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15522. auto se = detail::scope_exit([&] {
  15523. svr.stop();
  15524. thread.join();
  15525. ASSERT_FALSE(svr.is_running());
  15526. });
  15527. svr.wait_until_ready();
  15528. {
  15529. Client cli(HOST, PORT);
  15530. cli.set_follow_location(true);
  15531. auto res = cli.Get("/");
  15532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15533. EXPECT_EQ(StatusCode::OK_200, res->status);
  15534. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15535. }
  15536. }
  15537. TEST(RedirectTest, RedirectWithPlusInPath) {
  15538. Server svr;
  15539. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15540. res.set_redirect("/a+b");
  15541. });
  15542. // Route pattern uses regex; escape + as \\+
  15543. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15544. res.set_content(req.path, "text/plain");
  15545. });
  15546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15547. auto se = detail::scope_exit([&] {
  15548. svr.stop();
  15549. thread.join();
  15550. ASSERT_FALSE(svr.is_running());
  15551. });
  15552. svr.wait_until_ready();
  15553. {
  15554. Client cli(HOST, PORT);
  15555. cli.set_follow_location(true);
  15556. auto res = cli.Get("/");
  15557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15558. EXPECT_EQ(StatusCode::OK_200, res->status);
  15559. EXPECT_EQ("/a+b", res->body);
  15560. }
  15561. }
  15562. TEST(RedirectTest, ResolveRelativeLocation) {
  15563. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15564. const std::vector<std::pair<std::string, std::string>> cases = {
  15565. {"g", "/b/c/g"},
  15566. {"./g", "/b/c/g"},
  15567. {"g/", "/b/c/g/"},
  15568. {"?y", "/b/c/d;p?y"},
  15569. {"g?y", "/b/c/g?y"},
  15570. {"#s", "/b/c/d;p?q#s"},
  15571. {"g#s", "/b/c/g#s"},
  15572. {"g?y#s", "/b/c/g?y#s"},
  15573. {";x", "/b/c/;x"},
  15574. {"g;x", "/b/c/g;x"},
  15575. {".", "/b/c/"},
  15576. {"./", "/b/c/"},
  15577. {"..", "/b/"},
  15578. {"../", "/b/"},
  15579. {"../g", "/b/g"},
  15580. {"../..", "/"},
  15581. {"../../", "/"},
  15582. {"../../g", "/g"},
  15583. {"../../../g", "/g"},
  15584. {"g.", "/b/c/g."},
  15585. {".g", "/b/c/.g"},
  15586. {"g..", "/b/c/g.."},
  15587. {"..g", "/b/c/..g"},
  15588. {"./../g", "/b/g"},
  15589. {"./g/.", "/b/c/g/"},
  15590. {"g/./h", "/b/c/g/h"},
  15591. {"g/../h", "/b/c/h"},
  15592. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15593. {"g;x=1/../y", "/b/c/y"},
  15594. {"g?y/./x", "/b/c/g?y/./x"},
  15595. {"g#s/../x", "/b/c/g#s/../x"},
  15596. // Not relative-path references, so left for parse_url.
  15597. {"/g", "/g"},
  15598. {"//g", "//g"},
  15599. {"http://g/x", "http://g/x"},
  15600. {"g:h", "g:h"},
  15601. };
  15602. for (const auto &c : cases) {
  15603. EXPECT_EQ(c.second,
  15604. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15605. << c.first;
  15606. }
  15607. }
  15608. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15609. Server svr;
  15610. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15611. res.set_redirect(req.get_param_value("to"));
  15612. });
  15613. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15614. res.set_content(req.target, "text/plain");
  15615. });
  15616. svr.Get("/other", [](const Request &req, Response &res) {
  15617. res.set_content(req.target, "text/plain");
  15618. });
  15619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15620. auto se = detail::scope_exit([&] {
  15621. svr.stop();
  15622. thread.join();
  15623. ASSERT_FALSE(svr.is_running());
  15624. });
  15625. svr.wait_until_ready();
  15626. const std::vector<std::pair<std::string, std::string>> cases = {
  15627. {"next", "/dir/next"},
  15628. {"./next?x=1", "/dir/next?x=1"},
  15629. {"../other", "/other"},
  15630. };
  15631. for (const auto &c : cases) {
  15632. Client cli(HOST, PORT);
  15633. cli.set_follow_location(true);
  15634. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15635. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15636. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15637. EXPECT_EQ(c.second, res->body) << c.first;
  15638. }
  15639. }
  15640. #ifdef CPPHTTPLIB_SSL_ENABLED
  15641. TEST(RedirectTest, Issue2185_Online) {
  15642. SSLClient client("github.com");
  15643. client.set_follow_location(true);
  15644. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15645. "Coollab-Windows.zip");
  15646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15647. EXPECT_EQ(StatusCode::OK_200, res->status);
  15648. EXPECT_EQ(9920427U, res->body.size());
  15649. }
  15650. #endif
  15651. TEST(VulnerabilityTest, CRLFInjection) {
  15652. Server svr;
  15653. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15654. res.set_content("Hello 1", "text/plain");
  15655. });
  15656. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15657. res.set_content("Hello 2", "text/plain");
  15658. });
  15659. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15660. res.set_content("Hello 3", "text/plain");
  15661. });
  15662. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15663. res.set_content("Hello 4", "text/plain");
  15664. });
  15665. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15666. for (const auto &x : req.headers) {
  15667. auto key = x.first;
  15668. EXPECT_STRNE("evil", key.c_str());
  15669. }
  15670. });
  15671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15672. auto se = detail::scope_exit([&] {
  15673. svr.stop();
  15674. thread.join();
  15675. ASSERT_FALSE(svr.is_running());
  15676. });
  15677. svr.wait_until_ready();
  15678. {
  15679. Client cli(HOST, PORT);
  15680. cli.Post("/test1", "A=B",
  15681. "application/x-www-form-urlencoded\r\nevil: hello1");
  15682. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15683. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15684. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15685. }
  15686. }
  15687. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15688. auto server_thread = std::thread([] {
  15689. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15690. default_socket_options(srv);
  15691. sockaddr_in addr{};
  15692. addr.sin_family = AF_INET;
  15693. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15694. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15695. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15696. ::listen(srv, 1);
  15697. sockaddr_in cli_addr{};
  15698. socklen_t cli_len = sizeof(cli_addr);
  15699. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15700. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15701. std::string buf_all;
  15702. char buf[2048];
  15703. ssize_t n;
  15704. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15705. buf_all.append(buf, static_cast<size_t>(n));
  15706. size_t pos;
  15707. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15708. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15709. auto e = request_block.find("\r\n");
  15710. if (e != std::string::npos) {
  15711. auto request_line = request_block.substr(0, e);
  15712. std::string msg =
  15713. "CRLF injection detected in request line: '" + request_line + "'";
  15714. EXPECT_FALSE(true) << msg;
  15715. }
  15716. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15717. ::send(cli,
  15718. #ifdef _WIN32
  15719. static_cast<const char *>(resp.c_str()),
  15720. static_cast<int>(resp.size()),
  15721. #else
  15722. resp.c_str(), resp.size(),
  15723. #endif
  15724. 0);
  15725. buf_all.erase(0, pos + 4);
  15726. }
  15727. }
  15728. detail::close_socket(cli);
  15729. detail::close_socket(srv);
  15730. });
  15731. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15732. auto cli = Client("127.0.0.1", PORT + 1);
  15733. auto headers = Headers{
  15734. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15735. {"Connection", "keep-alive"}};
  15736. auto res = cli.Get("/hi", headers);
  15737. EXPECT_FALSE(res);
  15738. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15739. server_thread.join();
  15740. }
  15741. // A request rejected before any byte reaches the socket must fail right away
  15742. // instead of waiting for a response the server will never send.
  15743. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15744. // The kernel completes the TCP handshake from the listen backlog, so the
  15745. // client connects, but nothing ever reads, responds or closes.
  15746. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15747. default_socket_options(srv);
  15748. sockaddr_in addr{};
  15749. addr.sin_family = AF_INET;
  15750. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15751. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15752. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15753. ASSERT_EQ(0, ::listen(srv, 8));
  15754. auto cli = Client("127.0.0.1", PORT + 1);
  15755. cli.set_read_timeout(10, 0);
  15756. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15757. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15758. std::chrono::steady_clock::now() - start)
  15759. .count();
  15760. };
  15761. {
  15762. Request req;
  15763. req.method = "GE T";
  15764. req.path = "/";
  15765. auto start = std::chrono::steady_clock::now();
  15766. auto res = cli.send(req);
  15767. EXPECT_FALSE(res);
  15768. EXPECT_EQ(Error::Write, res.error());
  15769. EXPECT_LT(elapsed_ms(start), 1000);
  15770. }
  15771. {
  15772. auto start = std::chrono::steady_clock::now();
  15773. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15774. EXPECT_FALSE(res);
  15775. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15776. EXPECT_LT(elapsed_ms(start), 1000);
  15777. }
  15778. EXPECT_FALSE(cli.is_socket_open());
  15779. detail::close_socket(srv);
  15780. }
  15781. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15782. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15783. default_socket_options(srv);
  15784. sockaddr_in addr{};
  15785. addr.sin_family = AF_INET;
  15786. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15788. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15789. ASSERT_EQ(0, ::listen(srv, 1));
  15790. std::string received;
  15791. auto server_thread = std::thread([&] {
  15792. auto sock = ::accept(srv, nullptr, nullptr);
  15793. if (sock == INVALID_SOCKET) { return; }
  15794. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15795. char buf[2048];
  15796. ssize_t n;
  15797. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15798. received.append(buf, static_cast<size_t>(n));
  15799. }
  15800. detail::close_socket(sock);
  15801. });
  15802. {
  15803. auto cli = Client("127.0.0.1", PORT + 1);
  15804. // "Z" sorts after the default headers, so writing straight to the socket
  15805. // would have sent the request line and those headers before the rejection.
  15806. auto handle =
  15807. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15808. EXPECT_FALSE(handle.is_valid());
  15809. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15810. }
  15811. server_thread.join();
  15812. detail::close_socket(srv);
  15813. EXPECT_TRUE(received.empty()) << received;
  15814. }
  15815. TEST(PathParamsTest, StaticMatch) {
  15816. const auto pattern = "/users/all";
  15817. detail::PathParamsMatcher matcher(pattern);
  15818. Request request;
  15819. request.path = "/users/all";
  15820. ASSERT_TRUE(matcher.match(request));
  15821. std::unordered_map<std::string, std::string> expected_params = {};
  15822. EXPECT_EQ(request.path_params, expected_params);
  15823. }
  15824. TEST(PathParamsTest, StaticMismatch) {
  15825. const auto pattern = "/users/all";
  15826. detail::PathParamsMatcher matcher(pattern);
  15827. Request request;
  15828. request.path = "/users/1";
  15829. ASSERT_FALSE(matcher.match(request));
  15830. }
  15831. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15832. const auto pattern = "/users/:id/subscriptions";
  15833. detail::PathParamsMatcher matcher(pattern);
  15834. Request request;
  15835. request.path = "/users/42/subscriptions";
  15836. ASSERT_TRUE(matcher.match(request));
  15837. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15838. EXPECT_EQ(request.path_params, expected_params);
  15839. }
  15840. TEST(PathParamsTest, SingleParamInTheEnd) {
  15841. const auto pattern = "/users/:id";
  15842. detail::PathParamsMatcher matcher(pattern);
  15843. Request request;
  15844. request.path = "/users/24";
  15845. ASSERT_TRUE(matcher.match(request));
  15846. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15847. EXPECT_EQ(request.path_params, expected_params);
  15848. }
  15849. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15850. const auto pattern = "/users/:id/";
  15851. detail::PathParamsMatcher matcher(pattern);
  15852. Request request;
  15853. request.path = "/users/42/";
  15854. ASSERT_TRUE(matcher.match(request));
  15855. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15856. EXPECT_EQ(request.path_params, expected_params);
  15857. }
  15858. TEST(PathParamsTest, EmptyParam) {
  15859. const auto pattern = "/users/:id/";
  15860. detail::PathParamsMatcher matcher(pattern);
  15861. Request request;
  15862. request.path = "/users//";
  15863. ASSERT_TRUE(matcher.match(request));
  15864. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15865. EXPECT_EQ(request.path_params, expected_params);
  15866. }
  15867. TEST(PathParamsTest, FragmentMismatch) {
  15868. const auto pattern = "/users/:id/";
  15869. detail::PathParamsMatcher matcher(pattern);
  15870. Request request;
  15871. request.path = "/admins/24/";
  15872. ASSERT_FALSE(matcher.match(request));
  15873. }
  15874. TEST(PathParamsTest, ExtraFragments) {
  15875. const auto pattern = "/users/:id";
  15876. detail::PathParamsMatcher matcher(pattern);
  15877. Request request;
  15878. request.path = "/users/42/subscriptions";
  15879. ASSERT_FALSE(matcher.match(request));
  15880. }
  15881. TEST(PathParamsTest, MissingTrailingParam) {
  15882. const auto pattern = "/users/:id";
  15883. detail::PathParamsMatcher matcher(pattern);
  15884. Request request;
  15885. request.path = "/users";
  15886. ASSERT_FALSE(matcher.match(request));
  15887. }
  15888. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15889. const auto pattern = "/users/:id/subscriptions";
  15890. detail::PathParamsMatcher matcher(pattern);
  15891. Request request;
  15892. request.path = "/users/subscriptions";
  15893. ASSERT_FALSE(matcher.match(request));
  15894. }
  15895. TEST(PathParamsTest, MultipleParams) {
  15896. const auto pattern = "/users/:userid/subscriptions/:subid";
  15897. detail::PathParamsMatcher matcher(pattern);
  15898. Request request;
  15899. request.path = "/users/42/subscriptions/2";
  15900. ASSERT_TRUE(matcher.match(request));
  15901. std::unordered_map<std::string, std::string> expected_params = {
  15902. {"userid", "42"}, {"subid", "2"}};
  15903. EXPECT_EQ(request.path_params, expected_params);
  15904. }
  15905. TEST(PathParamsTest, SequenceOfParams) {
  15906. const auto pattern = "/values/:x/:y/:z";
  15907. detail::PathParamsMatcher matcher(pattern);
  15908. Request request;
  15909. request.path = "/values/1/2/3";
  15910. ASSERT_TRUE(matcher.match(request));
  15911. std::unordered_map<std::string, std::string> expected_params = {
  15912. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15913. EXPECT_EQ(request.path_params, expected_params);
  15914. }
  15915. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15916. const auto pattern = "/prefix:suffix";
  15917. detail::PathParamsMatcher matcher(pattern);
  15918. Request request;
  15919. request.path = "/prefix:suffix";
  15920. ASSERT_TRUE(matcher.match(request));
  15921. const std::unordered_map<std::string, std::string> expected_params = {};
  15922. EXPECT_EQ(request.path_params, expected_params);
  15923. }
  15924. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15925. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15926. // calling thread's stack on a long enough path for a quantified pattern;
  15927. // RegexMatcher must refuse to run regex matching on paths beyond
  15928. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15929. detail::RegexMatcher matcher("/files/(.*)");
  15930. Request within_limit;
  15931. within_limit.path = "/files/" + std::string(10, 'A');
  15932. EXPECT_TRUE(matcher.match(within_limit));
  15933. Request over_limit;
  15934. over_limit.path =
  15935. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15936. EXPECT_FALSE(matcher.match(over_limit));
  15937. }
  15938. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15939. Server svr;
  15940. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15941. res.set_content("ok", "text/plain");
  15942. });
  15943. auto port = svr.bind_to_any_port(HOST);
  15944. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15945. auto se = detail::scope_exit([&] {
  15946. svr.stop();
  15947. thread.join();
  15948. ASSERT_FALSE(svr.is_running());
  15949. });
  15950. svr.wait_until_ready();
  15951. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15952. // request URI limit; this used to be able to crash the process.
  15953. std::string path =
  15954. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15955. std::string req = "GET " + path +
  15956. " HTTP/1.1\r\n"
  15957. "Host: " +
  15958. std::string(HOST) + ":" + std::to_string(port) +
  15959. "\r\n"
  15960. "Connection: close\r\n"
  15961. "\r\n";
  15962. std::string response;
  15963. ASSERT_TRUE(send_request(5, req, &response, port));
  15964. EXPECT_NE(std::string::npos, response.find("404"));
  15965. }
  15966. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15967. Server svr;
  15968. auto handler = [](const Request & /*req*/, Response &res) {
  15969. res.set_content("hit", "text/plain");
  15970. };
  15971. // No regex metacharacter, so this one is compared literally
  15972. svr.Get("/literal/route", handler);
  15973. // '.' is a regex metacharacter, so this one must keep regex semantics
  15974. svr.Get("/a.c", handler);
  15975. auto port = svr.bind_to_any_port(HOST);
  15976. std::thread t([&]() { svr.listen_after_bind(); });
  15977. auto se = detail::scope_exit([&] {
  15978. svr.stop();
  15979. t.join();
  15980. ASSERT_FALSE(svr.is_running());
  15981. });
  15982. svr.wait_until_ready();
  15983. Client cli(HOST, port);
  15984. struct {
  15985. const char *path;
  15986. int status;
  15987. } cases[] = {
  15988. {"/literal/route", StatusCode::OK_200},
  15989. {"/literal/routes", StatusCode::NotFound_404},
  15990. {"/literal/rout", StatusCode::NotFound_404},
  15991. {"/abc", StatusCode::OK_200},
  15992. {"/a.c", StatusCode::OK_200},
  15993. };
  15994. for (const auto &x : cases) {
  15995. auto res = cli.Get(x.path);
  15996. ASSERT_TRUE(res) << x.path;
  15997. EXPECT_EQ(x.status, res->status) << x.path;
  15998. }
  15999. }
  16000. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16001. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16002. // from exhausting the stack, so it must only constrain routes that actually
  16003. // run a regular expression. A literal route is matched by comparison and
  16004. // stays usable at any length.
  16005. Server svr;
  16006. const std::string pattern =
  16007. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16008. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16009. res.set_content("hit", "text/plain");
  16010. });
  16011. auto port = svr.bind_to_any_port(HOST);
  16012. std::thread t([&]() { svr.listen_after_bind(); });
  16013. auto se = detail::scope_exit([&] {
  16014. svr.stop();
  16015. t.join();
  16016. ASSERT_FALSE(svr.is_running());
  16017. });
  16018. svr.wait_until_ready();
  16019. Client cli(HOST, port);
  16020. auto res = cli.Get(pattern);
  16021. ASSERT_TRUE(res);
  16022. EXPECT_EQ(StatusCode::OK_200, res->status);
  16023. }
  16024. TEST(ParseUrlTest, VariousPatterns) {
  16025. {
  16026. detail::UrlComponents uc;
  16027. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16028. EXPECT_EQ("http", uc.scheme);
  16029. EXPECT_EQ("example.com", uc.host);
  16030. EXPECT_EQ("8080", uc.port);
  16031. EXPECT_EQ("/path", uc.path);
  16032. EXPECT_EQ("?q=1", uc.query);
  16033. }
  16034. {
  16035. detail::UrlComponents uc;
  16036. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16037. EXPECT_EQ("https", uc.scheme);
  16038. EXPECT_EQ("example.com", uc.host);
  16039. EXPECT_TRUE(uc.port.empty());
  16040. EXPECT_EQ("/path", uc.path);
  16041. }
  16042. {
  16043. detail::UrlComponents uc;
  16044. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16045. EXPECT_EQ("::1", uc.host);
  16046. EXPECT_EQ("8080", uc.port);
  16047. EXPECT_EQ("/path", uc.path);
  16048. }
  16049. {
  16050. detail::UrlComponents uc;
  16051. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16052. }
  16053. {
  16054. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16055. // the path while the connection still targets the bracketed host.
  16056. detail::UrlComponents uc;
  16057. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16058. }
  16059. {
  16060. detail::UrlComponents uc;
  16061. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16062. }
  16063. {
  16064. detail::UrlComponents uc;
  16065. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16066. EXPECT_EQ("::1", uc.host);
  16067. EXPECT_TRUE(uc.port.empty());
  16068. EXPECT_EQ("/path", uc.path);
  16069. }
  16070. {
  16071. detail::UrlComponents uc;
  16072. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16073. EXPECT_TRUE(uc.scheme.empty());
  16074. EXPECT_EQ("example.com", uc.host);
  16075. EXPECT_EQ("/path", uc.path);
  16076. EXPECT_EQ("?q=1", uc.query);
  16077. }
  16078. {
  16079. detail::UrlComponents uc;
  16080. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16081. EXPECT_TRUE(uc.host.empty());
  16082. EXPECT_EQ("/path", uc.path);
  16083. EXPECT_EQ("?q=1", uc.query);
  16084. }
  16085. {
  16086. detail::UrlComponents uc;
  16087. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16088. EXPECT_EQ("example.com", uc.host);
  16089. EXPECT_EQ("8080", uc.port);
  16090. }
  16091. {
  16092. // Unix socket path — must not be parsed as host
  16093. detail::UrlComponents uc;
  16094. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16095. EXPECT_TRUE(uc.host.empty());
  16096. }
  16097. {
  16098. detail::UrlComponents uc;
  16099. ASSERT_TRUE(detail::parse_url("", uc));
  16100. EXPECT_TRUE(uc.host.empty());
  16101. EXPECT_TRUE(uc.path.empty());
  16102. }
  16103. {
  16104. detail::UrlComponents uc;
  16105. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16106. }
  16107. {
  16108. detail::UrlComponents uc;
  16109. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16110. }
  16111. {
  16112. // Accepted by parse_url; callers restrict to http/https
  16113. detail::UrlComponents uc;
  16114. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16115. EXPECT_EQ("ftp", uc.scheme);
  16116. }
  16117. {
  16118. detail::UrlComponents uc;
  16119. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16120. }
  16121. {
  16122. detail::UrlComponents uc;
  16123. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16124. }
  16125. }
  16126. TEST(ParseUrlTest, FragmentHandling) {
  16127. {
  16128. detail::UrlComponents uc;
  16129. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16130. EXPECT_EQ("/path", uc.path);
  16131. EXPECT_TRUE(uc.query.empty());
  16132. }
  16133. {
  16134. detail::UrlComponents uc;
  16135. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16136. EXPECT_TRUE(uc.path.empty());
  16137. EXPECT_TRUE(uc.query.empty());
  16138. }
  16139. }
  16140. TEST(ParseUrlTest, UserinfoHandling) {
  16141. // Userinfo with @ but no colon — host includes @
  16142. detail::UrlComponents uc;
  16143. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16144. EXPECT_EQ("user@host.com", uc.host);
  16145. EXPECT_EQ("/path", uc.path);
  16146. }
  16147. TEST(ParseUrlTest, IPv6EdgeCases) {
  16148. {
  16149. detail::UrlComponents uc;
  16150. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16151. EXPECT_TRUE(uc.scheme.empty());
  16152. EXPECT_EQ("::1", uc.host);
  16153. EXPECT_EQ("8080", uc.port);
  16154. }
  16155. {
  16156. // Zone ID '%25' is not in [a-fA-F0-9:]
  16157. detail::UrlComponents uc;
  16158. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16159. }
  16160. }
  16161. TEST(ParseUrlTest, SchemeEdgeCases) {
  16162. {
  16163. detail::UrlComponents uc;
  16164. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16165. }
  16166. {
  16167. detail::UrlComponents uc;
  16168. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16169. }
  16170. {
  16171. detail::UrlComponents uc;
  16172. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16173. }
  16174. }
  16175. TEST(ParseUrlTest, PortEdgeCases) {
  16176. {
  16177. detail::UrlComponents uc;
  16178. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16179. EXPECT_TRUE(uc.port.empty());
  16180. EXPECT_EQ("/path", uc.path);
  16181. }
  16182. {
  16183. // parse_url accepts any port string; validation is done by parse_port
  16184. detail::UrlComponents uc;
  16185. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16186. EXPECT_EQ("abc", uc.port);
  16187. }
  16188. }
  16189. TEST(ParseUrlTest, WebSocketPatterns) {
  16190. {
  16191. detail::UrlComponents uc;
  16192. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16193. EXPECT_EQ("ws", uc.scheme);
  16194. EXPECT_EQ("echo.example.com", uc.host);
  16195. EXPECT_EQ("8080", uc.port);
  16196. EXPECT_EQ("/ws", uc.path);
  16197. }
  16198. {
  16199. detail::UrlComponents uc;
  16200. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16201. EXPECT_EQ("wss", uc.scheme);
  16202. EXPECT_EQ("echo.example.com", uc.host);
  16203. EXPECT_TRUE(uc.port.empty());
  16204. EXPECT_EQ("/ws", uc.path);
  16205. }
  16206. }
  16207. TEST(ParseUrlTest, QueryOnly) {
  16208. detail::UrlComponents uc;
  16209. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16210. EXPECT_TRUE(uc.host.empty());
  16211. EXPECT_TRUE(uc.path.empty());
  16212. EXPECT_EQ("?q=1&r=2", uc.query);
  16213. }
  16214. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16215. detail::UrlComponents uc;
  16216. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16217. EXPECT_TRUE(uc.scheme.empty());
  16218. EXPECT_EQ("example.com", uc.host);
  16219. EXPECT_EQ("443", uc.port);
  16220. EXPECT_EQ("/path", uc.path);
  16221. }
  16222. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16223. // If ipv6 regex working, regex match codepath is taken.
  16224. // else port will default to 80 in Client impl
  16225. int clientImplMagicPort = 80;
  16226. int port = 4321;
  16227. // above ports must be different to avoid false negative
  16228. EXPECT_NE(clientImplMagicPort, port);
  16229. std::string ipV6TestURL = "http://[ff06::c3]";
  16230. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16231. CLIENT_PRIVATE_KEY_FILE);
  16232. EXPECT_EQ(cli.port(), port);
  16233. }
  16234. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16235. auto file_path = "./www/dir/index.html";
  16236. auto dir_path = "./www/dir";
  16237. detail::FileStat stat_file(file_path);
  16238. EXPECT_TRUE(stat_file.is_file());
  16239. EXPECT_FALSE(stat_file.is_dir());
  16240. detail::FileStat stat_dir(dir_path);
  16241. EXPECT_FALSE(stat_dir.is_file());
  16242. EXPECT_TRUE(stat_dir.is_dir());
  16243. }
  16244. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16245. // IPv4 with default HTTP port (80)
  16246. EXPECT_EQ("example.com",
  16247. detail::make_host_and_port_string("example.com", 80, false));
  16248. // IPv4 with default HTTPS port (443)
  16249. EXPECT_EQ("example.com",
  16250. detail::make_host_and_port_string("example.com", 443, true));
  16251. // IPv4 with non-default HTTP port
  16252. EXPECT_EQ("example.com:8080",
  16253. detail::make_host_and_port_string("example.com", 8080, false));
  16254. // IPv4 with non-default HTTPS port
  16255. EXPECT_EQ("example.com:8443",
  16256. detail::make_host_and_port_string("example.com", 8443, true));
  16257. // IPv6 with default HTTP port (80)
  16258. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16259. // IPv6 with default HTTPS port (443)
  16260. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16261. // IPv6 with non-default HTTP port
  16262. EXPECT_EQ("[::1]:8080",
  16263. detail::make_host_and_port_string("::1", 8080, false));
  16264. // IPv6 with non-default HTTPS port
  16265. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16266. // IPv6 full address with default port
  16267. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16268. detail::make_host_and_port_string(
  16269. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16270. // IPv6 full address with non-default port
  16271. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16272. detail::make_host_and_port_string(
  16273. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16274. // IPv6 localhost with non-default port
  16275. EXPECT_EQ("[::1]:3000",
  16276. detail::make_host_and_port_string("::1", 3000, false));
  16277. // IPv6 with zone ID (link-local address) with default port
  16278. EXPECT_EQ("[fe80::1%eth0]",
  16279. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16280. // IPv6 with zone ID (link-local address) with non-default port
  16281. EXPECT_EQ("[fe80::1%eth0]:8080",
  16282. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16283. // Edge case: Port 443 with is_ssl=false (should add port)
  16284. EXPECT_EQ("example.com:443",
  16285. detail::make_host_and_port_string("example.com", 443, false));
  16286. // Edge case: Port 80 with is_ssl=true (should add port)
  16287. EXPECT_EQ("example.com:80",
  16288. detail::make_host_and_port_string("example.com", 80, true));
  16289. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16290. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16291. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16292. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16293. // Security fix: Already bracketed IPv6 should not get double brackets
  16294. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16295. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16296. EXPECT_EQ("[::1]:8080",
  16297. detail::make_host_and_port_string("[::1]", 8080, false));
  16298. EXPECT_EQ("[2001:db8::1]:8080",
  16299. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16300. EXPECT_EQ("[fe80::1%eth0]",
  16301. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16302. EXPECT_EQ("[fe80::1%eth0]:8080",
  16303. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16304. // Edge case: Empty host (should return as-is)
  16305. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16306. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16307. // This is a known limitation but shouldn't crash
  16308. EXPECT_EQ("[host:name]",
  16309. detail::make_host_and_port_string("host:name", 80, false));
  16310. // Port number edge cases (no validation, but should not crash)
  16311. EXPECT_EQ("example.com:0",
  16312. detail::make_host_and_port_string("example.com", 0, false));
  16313. EXPECT_EQ("example.com:-1",
  16314. detail::make_host_and_port_string("example.com", -1, false));
  16315. EXPECT_EQ("example.com:65535",
  16316. detail::make_host_and_port_string("example.com", 65535, false));
  16317. EXPECT_EQ("example.com:65536",
  16318. detail::make_host_and_port_string("example.com", 65536, false));
  16319. }
  16320. #ifdef CPPHTTPLIB_SSL_ENABLED
  16321. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16322. httplib::SSLClient cli("roblox.com", 443);
  16323. cli.set_follow_location(true);
  16324. auto res = cli.Get("/");
  16325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16326. EXPECT_EQ(StatusCode::OK_200, res->status);
  16327. }
  16328. #endif
  16329. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16330. Server svr;
  16331. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16332. EXPECT_EQ(res.status, 400);
  16333. });
  16334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16335. auto se = detail::scope_exit([&] {
  16336. svr.stop();
  16337. thread.join();
  16338. ASSERT_FALSE(svr.is_running());
  16339. });
  16340. svr.wait_until_ready();
  16341. Client cli(HOST, PORT);
  16342. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16343. }
  16344. TEST(InvalidHeaderCharsTest, is_field_name) {
  16345. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16346. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16347. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16348. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16349. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16350. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16351. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16352. EXPECT_FALSE(detail::fields::is_field_name(""));
  16353. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16354. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16355. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16356. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16357. }
  16358. TEST(InvalidHeaderCharsTest, is_field_value) {
  16359. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16360. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16361. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16362. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16363. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16364. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16365. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16366. EXPECT_TRUE(detail::fields::is_field_value(""));
  16367. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16368. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16369. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16370. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16371. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16372. }
  16373. TEST(InvalidHeaderCharsTest, OnServer) {
  16374. Server svr;
  16375. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16376. std::string header = "Not Set";
  16377. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16378. res.set_header(header, "value");
  16379. res.set_content("Page Content Page Content", "text/plain");
  16380. });
  16381. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16382. std::string header = "Not Set";
  16383. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16384. res.set_header("X-Test", header);
  16385. res.set_content("Page Content Page Content", "text/plain");
  16386. });
  16387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16388. auto se = detail::scope_exit([&] {
  16389. svr.stop();
  16390. thread.join();
  16391. ASSERT_FALSE(svr.is_running());
  16392. });
  16393. svr.wait_until_ready();
  16394. Client cli(HOST, PORT);
  16395. {
  16396. auto res = cli.Get(
  16397. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16399. EXPECT_EQ("Page Content Page Content", res->body);
  16400. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16401. }
  16402. {
  16403. auto res = cli.Get(
  16404. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16406. EXPECT_EQ("Page Content Page Content", res->body);
  16407. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16408. }
  16409. }
  16410. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16411. auto handled = false;
  16412. Server svr;
  16413. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16414. thread t = thread([&] { svr.listen(HOST, PORT); });
  16415. auto se = detail::scope_exit([&] {
  16416. svr.stop();
  16417. t.join();
  16418. ASSERT_FALSE(svr.is_running());
  16419. ASSERT_FALSE(handled);
  16420. });
  16421. svr.wait_until_ready();
  16422. auto req = "POST /test HTTP/1.1\r\n"
  16423. "Content-Length: x\r\n"
  16424. "\r\n";
  16425. std::string response;
  16426. ASSERT_TRUE(send_request(1, req, &response));
  16427. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16428. response.substr(0, response.find("\r\n")));
  16429. }
  16430. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16431. // case-insensitive, and a server that receives a 100-continue expectation in
  16432. // an HTTP/1.0 request MUST ignore it.
  16433. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16434. std::string response;
  16435. ASSERT_TRUE(send_request(1, req, &response, port));
  16436. *got_100 = response.find("100 Continue") != std::string::npos;
  16437. }
  16438. class ExpectTokenTest : public ::testing::Test {
  16439. protected:
  16440. void SetUp() override {
  16441. svr_.Post("/p", [](const Request &, Response &res) {
  16442. res.set_content("ok", "text/plain");
  16443. });
  16444. port_ = svr_.bind_to_any_port(HOST);
  16445. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16446. svr_.wait_until_ready();
  16447. }
  16448. void TearDown() override {
  16449. svr_.stop();
  16450. if (thread_.joinable()) { thread_.join(); }
  16451. }
  16452. std::string request(const char *version, const char *expect_value) const {
  16453. return std::string("POST /p ") + version +
  16454. "\r\n"
  16455. "Host: localhost\r\n"
  16456. "Content-Length: 2\r\n"
  16457. "Connection: close\r\n"
  16458. "Expect: " +
  16459. expect_value +
  16460. "\r\n"
  16461. "\r\n"
  16462. "hi";
  16463. }
  16464. Server svr_;
  16465. int port_ = 0;
  16466. thread thread_;
  16467. };
  16468. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16469. bool got_100 = false;
  16470. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16471. EXPECT_TRUE(got_100);
  16472. }
  16473. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16474. bool got_100 = true;
  16475. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16476. EXPECT_FALSE(got_100);
  16477. }
  16478. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16479. bool got_100 = false;
  16480. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16481. EXPECT_TRUE(got_100);
  16482. }
  16483. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16484. bool got_100 = false;
  16485. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16486. EXPECT_TRUE(got_100);
  16487. }
  16488. // `100 Continue` is sent only when the server starts reading the body, so a
  16489. // request rejected before that never invites the client to send it. The
  16490. // requests below carry the expectation but withhold the body, as a client
  16491. // waiting for `100 Continue` would.
  16492. // A POST that expects `100 Continue` and withholds its two-byte body.
  16493. static std::string expect_headers_only(const std::string &path) {
  16494. return "POST " + path +
  16495. " HTTP/1.1\r\n"
  16496. "Host: localhost\r\n"
  16497. "Content-Length: 2\r\n"
  16498. "Expect: 100-continue\r\n"
  16499. "\r\n";
  16500. }
  16501. class ExpectLazyContinueTest : public ::testing::Test {
  16502. protected:
  16503. void SetUp() override {
  16504. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16505. if (req.path == "/pre-routing") {
  16506. res.status = StatusCode::Unauthorized_401;
  16507. return Server::HandlerResponse::Handled;
  16508. }
  16509. return Server::HandlerResponse::Unhandled;
  16510. });
  16511. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16512. if (req.matched_route == "/pre-request") {
  16513. res.status = StatusCode::Forbidden_403;
  16514. return Server::HandlerResponse::Handled;
  16515. }
  16516. return Server::HandlerResponse::Unhandled;
  16517. });
  16518. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16519. res.set_content("ok", "text/plain");
  16520. });
  16521. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16522. res.set_content("ok", "text/plain");
  16523. });
  16524. svr_.Post("/reader-used", [](const Request &, Response &res,
  16525. const ContentReader &content_reader) {
  16526. std::string body;
  16527. content_reader([&](const char *data, size_t len) {
  16528. body.append(data, len);
  16529. return true;
  16530. });
  16531. res.set_content(body, "text/plain");
  16532. });
  16533. svr_.Post("/reader-unused",
  16534. [](const Request &, Response &res, const ContentReader &) {
  16535. res.set_content("ignored", "text/plain");
  16536. });
  16537. port_ = svr_.bind_to_any_port(HOST);
  16538. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16539. svr_.wait_until_ready();
  16540. }
  16541. void TearDown() override {
  16542. svr_.stop();
  16543. if (thread_.joinable()) { thread_.join(); }
  16544. }
  16545. // Sends `req` and reads until the server closes the connection. Returns
  16546. // false if the read had to wait for the client-side timeout instead.
  16547. bool send_until_closed(const std::string &req, std::string *resp) const {
  16548. auto start = std::chrono::steady_clock::now();
  16549. if (!send_request(3, req, resp, port_)) { return false; }
  16550. auto elapsed = std::chrono::steady_clock::now() - start;
  16551. return elapsed < std::chrono::seconds(2);
  16552. }
  16553. // The final response comes without `100 Continue`, and the server closes
  16554. // the connection since the body may or may not follow.
  16555. void expect_final_without_interim(const std::string &path,
  16556. const char *status_line) const {
  16557. std::string resp;
  16558. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16559. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16560. EXPECT_EQ(0u, resp.find(status_line));
  16561. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16562. }
  16563. Server svr_;
  16564. int port_ = 0;
  16565. thread thread_;
  16566. };
  16567. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16568. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16569. }
  16570. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16571. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16572. }
  16573. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16574. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16575. }
  16576. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16577. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16578. }
  16579. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16580. // The body follows once `100 Continue` has had time to arrive.
  16581. auto req = expect_headers_only("/reader-used");
  16582. req.insert(req.size() - 2, "Connection: close\r\n");
  16583. std::string resp;
  16584. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16585. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16586. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16587. EXPECT_NE(std::string::npos, resp.find("hi"));
  16588. }
  16589. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16590. // Large enough for the client to add `Expect: 100-continue` itself.
  16591. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16592. std::atomic<bool> body_sent{false};
  16593. Client cli(HOST, port_);
  16594. auto res = cli.Post(
  16595. "/pre-request", length,
  16596. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16597. body_sent = true;
  16598. std::string chunk(len, 'x');
  16599. sink.write(chunk.data(), chunk.size());
  16600. return true;
  16601. },
  16602. "application/octet-stream");
  16603. ASSERT_TRUE(res);
  16604. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16605. EXPECT_FALSE(body_sent);
  16606. }
  16607. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16608. Server svr;
  16609. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16610. return StatusCode::ExpectationFailed_417;
  16611. });
  16612. svr.Post("/p", [](const Request &, Response &res) {
  16613. res.set_content("ok", "text/plain");
  16614. });
  16615. auto port = svr.bind_to_any_port(HOST);
  16616. thread t = thread([&] { svr.listen_after_bind(); });
  16617. auto se = detail::scope_exit([&] {
  16618. svr.stop();
  16619. t.join();
  16620. });
  16621. svr.wait_until_ready();
  16622. std::string resp;
  16623. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16624. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16625. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16626. // Exactly one response: the route handler must not run after the 417.
  16627. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16628. }
  16629. #ifndef _WIN32
  16630. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16631. static constexpr char reject[] = "Unauthorized";
  16632. static constexpr char accept[] = "Upload accepted";
  16633. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16634. Server svr;
  16635. svr.set_expect_100_continue_handler(
  16636. [](const Request & /*req*/, Response &res) {
  16637. res.status = StatusCode::Unauthorized_401;
  16638. res.set_content(reject, "text/plain");
  16639. return res.status;
  16640. });
  16641. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16642. res.set_content(accept, "text/plain");
  16643. });
  16644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16645. auto se = detail::scope_exit([&] {
  16646. svr.stop();
  16647. thread.join();
  16648. ASSERT_FALSE(svr.is_running());
  16649. });
  16650. svr.wait_until_ready();
  16651. {
  16652. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16653. curl_easy_init(), &curl_easy_cleanup};
  16654. ASSERT_NE(curl, nullptr);
  16655. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16656. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16657. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16658. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16659. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16660. &curl_slist_free_all};
  16661. ASSERT_NE(list, nullptr);
  16662. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16663. struct read_data {
  16664. size_t read_size;
  16665. size_t total_size;
  16666. } data = {0, total_size};
  16667. using read_callback_t =
  16668. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16669. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16670. void *userdata) -> size_t {
  16671. read_data *d = (read_data *)userdata;
  16672. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16673. std::fill_n(ptr, size * nmemb, 'A');
  16674. d->read_size += size * nmemb;
  16675. return size * nmemb;
  16676. };
  16677. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16678. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16679. std::vector<char> buffer;
  16680. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16681. using write_callback_t =
  16682. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16683. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16684. void *userdata) -> size_t {
  16685. std::vector<char> *buf = (std::vector<char> *)userdata;
  16686. buf->reserve(buf->size() + size * nmemb + 1);
  16687. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16688. return size * nmemb;
  16689. };
  16690. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16691. {
  16692. const auto res = curl_easy_perform(curl.get());
  16693. ASSERT_EQ(res, CURLE_OK);
  16694. }
  16695. {
  16696. auto response_code = long{};
  16697. const auto res =
  16698. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16699. ASSERT_EQ(res, CURLE_OK);
  16700. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16701. }
  16702. {
  16703. auto dl = curl_off_t{};
  16704. const auto res =
  16705. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16706. ASSERT_EQ(res, CURLE_OK);
  16707. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16708. }
  16709. {
  16710. buffer.push_back('\0');
  16711. ASSERT_STRCASEEQ(buffer.data(), reject);
  16712. }
  16713. }
  16714. }
  16715. #endif
  16716. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16717. // Regression test for #2458.
  16718. //
  16719. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16720. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16721. // ticket can make the client socket spuriously readable during the
  16722. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16723. // the client withholds the body and then blocks reading a response that never
  16724. // comes, failing with `Failed to read connection`.
  16725. //
  16726. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16727. // within the timeout. This raw OpenSSL server deliberately never sends
  16728. // `100 Continue`; the client must still deliver the body and receive 200.
  16729. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16730. signal(SIGPIPE, SIG_IGN);
  16731. const auto port = PORT + 4;
  16732. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16733. ASSERT_NE(srv, INVALID_SOCKET);
  16734. int opt = 1;
  16735. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16736. sockaddr_in addr{};
  16737. addr.sin_family = AF_INET;
  16738. addr.sin_port = htons(static_cast<uint16_t>(port));
  16739. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16740. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16741. ASSERT_EQ(0, ::listen(srv, 1));
  16742. std::atomic<size_t> server_body_bytes{0};
  16743. auto server_thread = std::thread([&] {
  16744. sockaddr_in cli_addr{};
  16745. socklen_t cli_len = sizeof(cli_addr);
  16746. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16747. if (cli == INVALID_SOCKET) { return; }
  16748. // Bound the lifetime of the server side so a buggy client (which never
  16749. // sends the body) cannot make this thread block forever on join.
  16750. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16751. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16752. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16753. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16754. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16755. SSL *ssl = SSL_new(ctx);
  16756. SSL_set_fd(ssl, static_cast<int>(cli));
  16757. if (SSL_accept(ssl) > 0) {
  16758. // Read the request headers. Reading here also flushes the TLS 1.3
  16759. // session tickets to the client. Deliberately do NOT send
  16760. // `100 Continue`.
  16761. std::string buf;
  16762. char tmp[1024];
  16763. while (buf.find("\r\n\r\n") == std::string::npos) {
  16764. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16765. if (n <= 0) { break; }
  16766. buf.append(tmp, static_cast<size_t>(n));
  16767. }
  16768. // A correct client sends the body now; count what arrives.
  16769. auto pos = buf.find("\r\n\r\n");
  16770. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16771. while (body < 4096) {
  16772. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16773. if (n <= 0) { break; }
  16774. body += static_cast<size_t>(n);
  16775. }
  16776. server_body_bytes = body;
  16777. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16778. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16779. SSL_shutdown(ssl);
  16780. }
  16781. SSL_free(ssl);
  16782. detail::close_socket(cli);
  16783. SSL_CTX_free(ctx);
  16784. });
  16785. auto se = detail::scope_exit([&] {
  16786. server_thread.join();
  16787. detail::close_socket(srv);
  16788. });
  16789. SSLClient cli("127.0.0.1", port);
  16790. cli.enable_server_certificate_verification(false);
  16791. cli.set_connection_timeout(5, 0);
  16792. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16793. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16794. std::string body(4096, 'A');
  16795. auto res = cli.Put("/api/test", body, "application/json");
  16796. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16797. EXPECT_EQ(StatusCode::OK_200, res->status);
  16798. EXPECT_EQ(body.size(), server_body_bytes.load());
  16799. }
  16800. #endif
  16801. template <typename S, typename C>
  16802. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16803. svr.Get("/stream", [&](const Request &, Response &res) {
  16804. auto data = new std::string("01234567890123456789");
  16805. res.set_content_provider(
  16806. data->size(), "text/plain",
  16807. [&, data](size_t offset, size_t length, DataSink &sink) {
  16808. const size_t DATA_CHUNK_SIZE = 4;
  16809. const auto &d = *data;
  16810. std::this_thread::sleep_for(std::chrono::seconds(1));
  16811. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16812. return true;
  16813. },
  16814. [data](bool success) {
  16815. EXPECT_FALSE(success);
  16816. delete data;
  16817. });
  16818. });
  16819. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16820. auto i = new size_t(0);
  16821. res.set_content_provider(
  16822. "text/plain",
  16823. [i](size_t, DataSink &sink) {
  16824. if (*i < 5) {
  16825. std::this_thread::sleep_for(std::chrono::seconds(1));
  16826. sink.write("abcd", 4);
  16827. (*i)++;
  16828. } else {
  16829. sink.done();
  16830. }
  16831. return true;
  16832. },
  16833. [i](bool success) {
  16834. EXPECT_FALSE(success);
  16835. delete i;
  16836. });
  16837. });
  16838. svr.Get("/chunked", [&](const Request &, Response &res) {
  16839. auto i = new size_t(0);
  16840. res.set_chunked_content_provider(
  16841. "text/plain",
  16842. [i](size_t, DataSink &sink) {
  16843. if (*i < 5) {
  16844. std::this_thread::sleep_for(std::chrono::seconds(1));
  16845. sink.os << "abcd";
  16846. (*i)++;
  16847. } else {
  16848. sink.done();
  16849. }
  16850. return true;
  16851. },
  16852. [i](bool success) {
  16853. EXPECT_FALSE(success);
  16854. delete i;
  16855. });
  16856. });
  16857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16858. auto se = detail::scope_exit([&] {
  16859. svr.stop();
  16860. listen_thread.join();
  16861. ASSERT_FALSE(svr.is_running());
  16862. });
  16863. svr.wait_until_ready();
  16864. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16865. {
  16866. auto start = std::chrono::steady_clock::now();
  16867. auto res = cli.Get("/stream");
  16868. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16869. std::chrono::steady_clock::now() - start)
  16870. .count();
  16871. ASSERT_FALSE(res);
  16872. EXPECT_EQ(Error::Read, res.error());
  16873. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16874. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16875. }
  16876. {
  16877. auto start = std::chrono::steady_clock::now();
  16878. auto res = cli.Get("/stream_without_length");
  16879. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16880. std::chrono::steady_clock::now() - start)
  16881. .count();
  16882. ASSERT_FALSE(res);
  16883. EXPECT_EQ(Error::Read, res.error());
  16884. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16885. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16886. }
  16887. {
  16888. auto start = std::chrono::steady_clock::now();
  16889. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16890. EXPECT_EQ("abcd", string(data, data_length));
  16891. return true;
  16892. });
  16893. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16894. std::chrono::steady_clock::now() - start)
  16895. .count();
  16896. ASSERT_FALSE(res);
  16897. EXPECT_EQ(Error::Read, res.error());
  16898. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16899. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16900. }
  16901. }
  16902. TEST(MaxTimeoutTest, ContentStream) {
  16903. time_t timeout = 2000;
  16904. time_t threshold = 200;
  16905. Server svr;
  16906. Client cli("localhost", PORT);
  16907. max_timeout_test(svr, cli, timeout, threshold);
  16908. }
  16909. #ifdef CPPHTTPLIB_SSL_ENABLED
  16910. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16911. time_t timeout = 2000;
  16912. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16914. SSLClient cli("localhost", PORT);
  16915. cli.enable_server_certificate_verification(false);
  16916. max_timeout_test(svr, cli, timeout, threshold);
  16917. }
  16918. #endif
  16919. class EventDispatcher {
  16920. public:
  16921. EventDispatcher() {}
  16922. bool wait_event(DataSink *sink) {
  16923. unique_lock<mutex> lk(m_);
  16924. int id = id_;
  16925. // Wait with timeout to prevent hanging if client disconnects
  16926. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16927. [&] { return cid_ == id; })) {
  16928. return false; // Timeout occurred
  16929. }
  16930. sink->write(message_.data(), message_.size());
  16931. return true;
  16932. }
  16933. void send_event(const string &message) {
  16934. lock_guard<mutex> lk(m_);
  16935. cid_ = id_++;
  16936. message_ = message;
  16937. cv_.notify_all();
  16938. }
  16939. private:
  16940. mutex m_;
  16941. condition_variable cv_;
  16942. atomic_int id_{0};
  16943. atomic_int cid_{-1};
  16944. string message_;
  16945. };
  16946. TEST(ClientInThreadTest, Issue2068) {
  16947. EventDispatcher ed;
  16948. Server svr;
  16949. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16950. res.set_chunked_content_provider("text/event-stream",
  16951. [&](size_t /*offset*/, DataSink &sink) {
  16952. return ed.wait_event(&sink);
  16953. });
  16954. });
  16955. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16956. svr.wait_until_ready();
  16957. thread event_thread([&] {
  16958. int id = 0;
  16959. while (svr.is_running()) {
  16960. this_thread::sleep_for(chrono::milliseconds(500));
  16961. std::stringstream ss;
  16962. ss << "data: " << id << "\n\n";
  16963. ed.send_event(ss.str());
  16964. id++;
  16965. }
  16966. });
  16967. auto se = detail::scope_exit([&] {
  16968. svr.stop();
  16969. listen_thread.join();
  16970. event_thread.join();
  16971. ASSERT_FALSE(svr.is_running());
  16972. });
  16973. {
  16974. auto client = detail::make_unique<Client>(HOST, PORT);
  16975. client->set_read_timeout(std::chrono::minutes(10));
  16976. std::atomic<bool> stop{false};
  16977. std::thread t([&] {
  16978. client->Get("/event1",
  16979. [&](const char *, size_t) -> bool { return !stop; });
  16980. });
  16981. std::this_thread::sleep_for(std::chrono::seconds(2));
  16982. stop = true;
  16983. client->stop();
  16984. t.join();
  16985. // Reset client after thread has finished
  16986. client.reset();
  16987. }
  16988. }
  16989. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16990. auto handled = false;
  16991. Server svr;
  16992. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16993. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16994. auto se = detail::scope_exit([&] {
  16995. svr.stop();
  16996. t.join();
  16997. ASSERT_FALSE(svr.is_running());
  16998. ASSERT_FALSE(handled);
  16999. });
  17000. svr.wait_until_ready();
  17001. // Two Content-Length headers with different values — must be rejected
  17002. auto req = "POST /test HTTP/1.1\r\n"
  17003. "Content-Length: 5\r\n"
  17004. "Content-Length: 10\r\n"
  17005. "\r\n"
  17006. "hello";
  17007. std::string response;
  17008. ASSERT_TRUE(send_request(1, req, &response));
  17009. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17010. response.substr(0, response.find("\r\n")));
  17011. }
  17012. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17013. auto handled = false;
  17014. Server svr;
  17015. svr.Post("/test", [&](const Request &, Response &res) {
  17016. handled = true;
  17017. res.set_content("ok", "text/plain");
  17018. });
  17019. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17020. auto se = detail::scope_exit([&] {
  17021. svr.stop();
  17022. t.join();
  17023. ASSERT_FALSE(svr.is_running());
  17024. ASSERT_TRUE(handled);
  17025. });
  17026. svr.wait_until_ready();
  17027. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17028. auto req = "POST /test HTTP/1.1\r\n"
  17029. "Content-Length: 5\r\n"
  17030. "Content-Length: 5\r\n"
  17031. "\r\n"
  17032. "hello";
  17033. std::string response;
  17034. ASSERT_TRUE(send_request(1, req, &response));
  17035. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17036. }
  17037. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17038. Server svr;
  17039. svr.Get("/test", [](const Request &, Response &res) {
  17040. res.set_content("ok", "text/plain");
  17041. });
  17042. auto port = svr.bind_to_any_port(HOST);
  17043. thread t = thread([&] { svr.listen_after_bind(); });
  17044. auto se = detail::scope_exit([&] {
  17045. svr.stop();
  17046. t.join();
  17047. ASSERT_FALSE(svr.is_running());
  17048. });
  17049. svr.wait_until_ready();
  17050. auto status_line = [&](const std::string &host_lines) {
  17051. std::string res;
  17052. send_request(
  17053. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17054. &res, port);
  17055. return res.substr(0, res.find("\r\n"));
  17056. };
  17057. const char *accepted[] = {
  17058. "Host: localhost\r\n",
  17059. "Host: a.example:8080\r\n",
  17060. "Host: my_service\r\n",
  17061. "Host: [::1]:8080\r\n",
  17062. "Host: [fe80::1%25eth0]\r\n",
  17063. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17064. };
  17065. for (auto host_lines : accepted) {
  17066. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17067. }
  17068. const char *rejected[] = {
  17069. "Host: a.example\r\nHost: b.example\r\n",
  17070. "Host: a.example\r\nHost: a.example\r\n",
  17071. "Host: a@b.example\r\n",
  17072. "Host: a.example/b\r\n",
  17073. "Host: a.example\\b\r\n",
  17074. "Host: a.example?b\r\n",
  17075. "Host: a.example#b\r\n",
  17076. "Host: a.example b.example\r\n",
  17077. };
  17078. for (auto host_lines : rejected) {
  17079. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17080. << host_lines;
  17081. }
  17082. }
  17083. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17084. Server svr;
  17085. svr.Get("/", [](const Request &req, Response &res) {
  17086. EXPECT_EQ(2U, req.trailers.size());
  17087. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17088. // Denied
  17089. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17090. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17091. // Accepted
  17092. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17093. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17094. EXPECT_TRUE(req.has_trailer("X-World"));
  17095. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17096. res.set_content("ok", "text/plain");
  17097. });
  17098. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17099. auto se = detail::scope_exit([&] {
  17100. svr.stop();
  17101. t.join();
  17102. ASSERT_FALSE(svr.is_running());
  17103. });
  17104. svr.wait_until_ready();
  17105. const std::string req = "GET / HTTP/1.1\r\n"
  17106. "Transfer-Encoding: chunked\r\n"
  17107. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17108. "\r\n"
  17109. "0\r\n"
  17110. "Content-Length: 10\r\n"
  17111. "Host: internal.local\r\n"
  17112. "Content-Type: malicious/content\r\n"
  17113. "Cookie: any\r\n"
  17114. "Set-Cookie: any\r\n"
  17115. "X-Forwarded-For: attacker.com\r\n"
  17116. "X-Real-Ip: 1.1.1.1\r\n"
  17117. "X-Hello: hello\r\n"
  17118. "X-World: world\r\n"
  17119. "\r\n";
  17120. std::string res;
  17121. ASSERT_TRUE(send_request(1, req, &res));
  17122. }
  17123. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17124. // several field lines, and the combined value is what has to be parsed. A
  17125. // Trailer field split across lines therefore declares every name it lists;
  17126. // reading only the first line silently drops the trailers the later lines
  17127. // declare. The prohibited-trailer filter still applies to every line.
  17128. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17129. Server svr;
  17130. size_t observed_trailer_count = 0;
  17131. std::string observed_hello;
  17132. std::string observed_world;
  17133. bool observed_content_length = true;
  17134. svr.Get("/", [&](const Request &req, Response &res) {
  17135. observed_trailer_count = req.trailers.size();
  17136. observed_hello = req.get_trailer_value("X-Hello");
  17137. observed_world = req.get_trailer_value("X-World");
  17138. observed_content_length = req.has_trailer("Content-Length");
  17139. res.set_content("ok", "text/plain");
  17140. });
  17141. auto port = svr.bind_to_any_port(HOST);
  17142. thread t = thread([&]() { svr.listen_after_bind(); });
  17143. auto se = detail::scope_exit([&] {
  17144. svr.stop();
  17145. t.join();
  17146. ASSERT_FALSE(svr.is_running());
  17147. });
  17148. svr.wait_until_ready();
  17149. const std::string req = "GET / HTTP/1.1\r\n"
  17150. "Transfer-Encoding: chunked\r\n"
  17151. "Trailer: X-Hello\r\n"
  17152. "Trailer: X-World, Content-Length\r\n"
  17153. "\r\n"
  17154. "0\r\n"
  17155. "X-Hello: hello\r\n"
  17156. "X-World: world\r\n"
  17157. "Content-Length: 10\r\n"
  17158. "\r\n";
  17159. std::string res;
  17160. ASSERT_TRUE(send_request(1, req, &res, port));
  17161. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17162. // Accepted: both field lines contribute to the declared set
  17163. EXPECT_EQ(2U, observed_trailer_count);
  17164. EXPECT_EQ(observed_hello, "hello");
  17165. EXPECT_EQ(observed_world, "world");
  17166. // Denied: a prohibited name stays prohibited on a later field line
  17167. EXPECT_FALSE(observed_content_length);
  17168. }
  17169. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17170. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17171. // unbounded run of fields that are never declared, because the counter would
  17172. // only advance for declared fields.
  17173. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17174. Server svr;
  17175. bool handler_called = false;
  17176. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17177. handler_called = true;
  17178. res.set_content("ok", "text/plain");
  17179. });
  17180. auto port = svr.bind_to_any_port(HOST);
  17181. thread t = thread([&]() { svr.listen_after_bind(); });
  17182. auto se = detail::scope_exit([&] {
  17183. svr.stop();
  17184. t.join();
  17185. ASSERT_FALSE(svr.is_running());
  17186. });
  17187. svr.wait_until_ready();
  17188. // Declare nothing, then send far more undeclared trailer fields than the
  17189. // header-count limit. Parsing must stop and reject the request rather than
  17190. // read every line.
  17191. std::string req = "GET / HTTP/1.1\r\n"
  17192. "Transfer-Encoding: chunked\r\n"
  17193. "\r\n"
  17194. "0\r\n";
  17195. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17196. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17197. }
  17198. req += "\r\n";
  17199. std::string res;
  17200. ASSERT_TRUE(send_request(1, req, &res, port));
  17201. // The request is rejected before the handler runs.
  17202. EXPECT_FALSE(handler_called);
  17203. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17204. }
  17205. // The set of declared trailer names is capped so a peer cannot grow it without
  17206. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17207. // declared past the cap is not honored, even if the field is actually sent.
  17208. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17209. Server svr;
  17210. // One name inside the cap and one past it, so the test tracks the cap rather
  17211. // than a fixed count.
  17212. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17213. const std::string within_cap_name = "X-T-0";
  17214. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17215. bool observed_within_cap = false;
  17216. bool observed_past_cap = false;
  17217. svr.Get("/", [&](const Request &req, Response &res) {
  17218. observed_within_cap = req.has_trailer(within_cap_name);
  17219. observed_past_cap = req.has_trailer(past_cap_name);
  17220. res.set_content("ok", "text/plain");
  17221. });
  17222. auto port = svr.bind_to_any_port(HOST);
  17223. thread t = thread([&]() { svr.listen_after_bind(); });
  17224. auto se = detail::scope_exit([&] {
  17225. svr.stop();
  17226. t.join();
  17227. ASSERT_FALSE(svr.is_running());
  17228. });
  17229. svr.wait_until_ready();
  17230. // Declare more trailer names than the cap in a single Trailer field, then
  17231. // actually send the first (within the cap) and the last (past it).
  17232. std::string trailer_decl = "Trailer: ";
  17233. for (int i = 0; i < declared_count; i++) {
  17234. if (i != 0) { trailer_decl += ", "; }
  17235. trailer_decl += "X-T-" + std::to_string(i);
  17236. }
  17237. trailer_decl += "\r\n";
  17238. const std::string req = "GET / HTTP/1.1\r\n"
  17239. "Transfer-Encoding: chunked\r\n" +
  17240. trailer_decl +
  17241. "\r\n"
  17242. "0\r\n" +
  17243. within_cap_name + ": a\r\n" + past_cap_name +
  17244. ": b\r\n"
  17245. "\r\n";
  17246. std::string res;
  17247. ASSERT_TRUE(send_request(1, req, &res, port));
  17248. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17249. // A name within the cap is honored; one declared past the cap is dropped.
  17250. EXPECT_TRUE(observed_within_cap);
  17251. EXPECT_FALSE(observed_past_cap);
  17252. }
  17253. // A direct client that is not listed in trusted_proxies must not be able to
  17254. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17255. // the peer address on the actual TCP connection determines whether the
  17256. // header is honored.
  17257. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17258. Server svr;
  17259. // Deliberately does NOT include the loopback address the test client
  17260. // actually connects from, so the direct connection is not a trusted proxy.
  17261. svr.set_trusted_proxies({"203.0.113.66"});
  17262. std::string observed_remote_addr;
  17263. svr.Get("/ip", [&](const Request &req, Response &res) {
  17264. observed_remote_addr = req.remote_addr;
  17265. res.set_content("ok", "text/plain");
  17266. });
  17267. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17268. auto se = detail::scope_exit([&] {
  17269. svr.stop();
  17270. t.join();
  17271. ASSERT_FALSE(svr.is_running());
  17272. });
  17273. svr.wait_until_ready();
  17274. Client cli(HOST, PORT);
  17275. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17277. EXPECT_EQ(StatusCode::OK_200, res->status);
  17278. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17279. // ignored entirely and the real connection-level address retained.
  17280. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17281. observed_remote_addr == "127.0.0.1");
  17282. }
  17283. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17284. Server svr;
  17285. std::string observed_remote_addr;
  17286. std::string observed_xff;
  17287. svr.Get("/ip", [&](const Request &req, Response &res) {
  17288. observed_remote_addr = req.remote_addr;
  17289. observed_xff = req.get_header_value("X-Forwarded-For");
  17290. res.set_content("ok", "text/plain");
  17291. });
  17292. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. t.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. });
  17298. svr.wait_until_ready();
  17299. Client cli(HOST, PORT);
  17300. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17302. EXPECT_EQ(StatusCode::OK_200, res->status);
  17303. EXPECT_EQ(observed_xff, "203.0.113.66");
  17304. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17305. observed_remote_addr == "127.0.0.1");
  17306. }
  17307. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17308. Server svr;
  17309. svr.set_trusted_proxies({"203.0.113.66"});
  17310. std::string observed_remote_addr;
  17311. std::string observed_xff;
  17312. svr.Get("/ip", [&](const Request &req, Response &res) {
  17313. observed_remote_addr = req.remote_addr;
  17314. observed_xff = req.get_header_value("X-Forwarded-For");
  17315. res.set_content("ok", "text/plain");
  17316. });
  17317. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17318. auto se = detail::scope_exit([&] {
  17319. svr.stop();
  17320. t.join();
  17321. ASSERT_FALSE(svr.is_running());
  17322. });
  17323. svr.wait_until_ready();
  17324. Client cli(HOST, PORT);
  17325. auto res = cli.Get("/ip");
  17326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17327. EXPECT_EQ(StatusCode::OK_200, res->status);
  17328. EXPECT_EQ(observed_xff, "");
  17329. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17330. observed_remote_addr == "127.0.0.1");
  17331. }
  17332. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17333. Server svr;
  17334. // Include the loopback address the test client actually connects from, so
  17335. // the direct connection itself is recognized as the trusted proxy hop.
  17336. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17337. std::string observed_remote_addr;
  17338. std::string observed_xff;
  17339. svr.Get("/ip", [&](const Request &req, Response &res) {
  17340. observed_remote_addr = req.remote_addr;
  17341. observed_xff = req.get_header_value("X-Forwarded-For");
  17342. res.set_content("ok", "text/plain");
  17343. });
  17344. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17345. auto se = detail::scope_exit([&] {
  17346. svr.stop();
  17347. t.join();
  17348. ASSERT_FALSE(svr.is_running());
  17349. });
  17350. svr.wait_until_ready();
  17351. Client cli(HOST, PORT);
  17352. auto res = cli.Get(
  17353. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17355. EXPECT_EQ(StatusCode::OK_200, res->status);
  17356. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17357. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17358. }
  17359. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17360. Server svr;
  17361. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17362. std::string observed_remote_addr;
  17363. std::string observed_xff;
  17364. svr.Get("/ip", [&](const Request &req, Response &res) {
  17365. observed_remote_addr = req.remote_addr;
  17366. observed_xff = req.get_header_value("X-Forwarded-For");
  17367. res.set_content("ok", "text/plain");
  17368. });
  17369. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17370. auto se = detail::scope_exit([&] {
  17371. svr.stop();
  17372. t.join();
  17373. ASSERT_FALSE(svr.is_running());
  17374. });
  17375. svr.wait_until_ready();
  17376. Client cli(HOST, PORT);
  17377. auto res = cli.Get(
  17378. "/ip",
  17379. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17381. EXPECT_EQ(StatusCode::OK_200, res->status);
  17382. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17383. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17384. }
  17385. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17386. Server svr;
  17387. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17388. std::string observed_remote_addr;
  17389. std::string observed_xff;
  17390. svr.Get("/ip", [&](const Request &req, Response &res) {
  17391. observed_remote_addr = req.remote_addr;
  17392. observed_xff = req.get_header_value("X-Forwarded-For");
  17393. res.set_content("ok", "text/plain");
  17394. });
  17395. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17396. auto se = detail::scope_exit([&] {
  17397. svr.stop();
  17398. t.join();
  17399. ASSERT_FALSE(svr.is_running());
  17400. });
  17401. svr.wait_until_ready();
  17402. Client cli(HOST, PORT);
  17403. auto res = cli.Get(
  17404. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17406. EXPECT_EQ(StatusCode::OK_200, res->status);
  17407. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17408. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17409. // and must not be selected.
  17410. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17411. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17412. }
  17413. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17414. Server svr;
  17415. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17416. std::string observed_remote_addr;
  17417. svr.Get("/ip", [&](const Request &req, Response &res) {
  17418. observed_remote_addr = req.remote_addr;
  17419. res.set_content("ok", "text/plain");
  17420. });
  17421. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17422. auto se = detail::scope_exit([&] {
  17423. svr.stop();
  17424. t.join();
  17425. ASSERT_FALSE(svr.is_running());
  17426. });
  17427. svr.wait_until_ready();
  17428. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17429. // a forged address and the trusted proxy's own address; the forged value must
  17430. // not win over the address the trusted proxy actually recorded.
  17431. Client cli(HOST, PORT);
  17432. auto res = cli.Get(
  17433. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17435. EXPECT_EQ(StatusCode::OK_200, res->status);
  17436. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17437. }
  17438. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17439. Server svr;
  17440. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17441. std::string observed_remote_addr;
  17442. std::string observed_xff;
  17443. svr.Get("/ip", [&](const Request &req, Response &res) {
  17444. observed_remote_addr = req.remote_addr;
  17445. observed_xff = req.get_header_value("X-Forwarded-For");
  17446. res.set_content("ok", "text/plain");
  17447. });
  17448. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17449. auto se = detail::scope_exit([&] {
  17450. svr.stop();
  17451. t.join();
  17452. ASSERT_FALSE(svr.is_running());
  17453. });
  17454. svr.wait_until_ready();
  17455. Client cli(HOST, PORT);
  17456. auto res = cli.Get(
  17457. "/ip",
  17458. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17460. EXPECT_EQ(StatusCode::OK_200, res->status);
  17461. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17462. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17463. }
  17464. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17465. Server svr;
  17466. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17467. std::string observed_remote_addr;
  17468. std::string observed_xff;
  17469. svr.Get("/ip", [&](const Request &req, Response &res) {
  17470. observed_remote_addr = req.remote_addr;
  17471. observed_xff = req.get_header_value("X-Forwarded-For");
  17472. res.set_content("ok", "text/plain");
  17473. });
  17474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17475. auto se = detail::scope_exit([&] {
  17476. svr.stop();
  17477. t.join();
  17478. ASSERT_FALSE(svr.is_running());
  17479. });
  17480. svr.wait_until_ready();
  17481. std::string raw_req =
  17482. "GET /ip HTTP/1.1\r\n"
  17483. "Host: localhost\r\n"
  17484. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17485. "Connection: close\r\n"
  17486. "\r\n";
  17487. std::string out;
  17488. ASSERT_TRUE(send_request(5, raw_req, &out));
  17489. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17490. // Header parser trims surrounding whitespace of the header value
  17491. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17492. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17493. }
  17494. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17495. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17496. // their own X-Forwarded-For as a separate field line rather than extending the
  17497. // one the client sent, so every occurrence has to be taken into account.
  17498. // Reading only the first one hands back the address the client chose.
  17499. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17500. Server svr;
  17501. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17502. std::string observed_remote_addr;
  17503. size_t observed_xff_count = 0;
  17504. svr.Get("/ip", [&](const Request &req, Response &res) {
  17505. observed_remote_addr = req.remote_addr;
  17506. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17507. res.set_content("ok", "text/plain");
  17508. });
  17509. auto port = svr.bind_to_any_port(HOST);
  17510. thread t = thread([&]() { svr.listen_after_bind(); });
  17511. auto se = detail::scope_exit([&] {
  17512. svr.stop();
  17513. t.join();
  17514. ASSERT_FALSE(svr.is_running());
  17515. });
  17516. svr.wait_until_ready();
  17517. // The client supplies the first field line; the trusted proxy appends the
  17518. // address it observed as a second one.
  17519. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17520. "Host: localhost\r\n"
  17521. "X-Forwarded-For: 1.2.3.4\r\n"
  17522. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17523. "Connection: close\r\n"
  17524. "\r\n";
  17525. std::string out;
  17526. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17527. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17528. EXPECT_EQ(observed_xff_count, 2U);
  17529. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17530. // The same chain spread over one field line per hop derives the same client
  17531. // address, i.e. the split and the comma-joined representations agree.
  17532. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17533. "Host: localhost\r\n"
  17534. "X-Forwarded-For: 1.2.3.4\r\n"
  17535. "X-Forwarded-For: 198.51.100.23\r\n"
  17536. "X-Forwarded-For: 192.0.2.45\r\n"
  17537. "Connection: close\r\n"
  17538. "\r\n";
  17539. out.clear();
  17540. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17541. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17542. EXPECT_EQ(observed_xff_count, 3U);
  17543. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17544. }
  17545. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17546. // crash the server (it used to call front() on an empty vector inside
  17547. // get_client_ip). The connection-level remote address must be retained instead.
  17548. static void run_malformed_xff_test(const std::string &xff_value) {
  17549. Server svr;
  17550. svr.set_trusted_proxies({"192.0.2.45"});
  17551. std::string observed_remote_addr;
  17552. svr.Get("/ip", [&](const Request &req, Response &res) {
  17553. observed_remote_addr = req.remote_addr;
  17554. res.set_content("ok", "text/plain");
  17555. });
  17556. int port = 0;
  17557. thread t = thread([&]() {
  17558. port = svr.bind_to_any_port(HOST);
  17559. svr.listen_after_bind();
  17560. });
  17561. auto se = detail::scope_exit([&] {
  17562. svr.stop();
  17563. t.join();
  17564. ASSERT_FALSE(svr.is_running());
  17565. });
  17566. svr.wait_until_ready();
  17567. Client cli(HOST, port);
  17568. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17570. EXPECT_EQ(StatusCode::OK_200, res->status);
  17571. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17572. observed_remote_addr == "127.0.0.1");
  17573. }
  17574. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17575. run_malformed_xff_test("");
  17576. }
  17577. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17578. run_malformed_xff_test(",");
  17579. }
  17580. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17581. run_malformed_xff_test(", , ,");
  17582. }
  17583. // The same rule applies to Accept: a request whose acceptable types are spread
  17584. // over several field lines must be negotiated against all of them.
  17585. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17586. // case-insensitive connection options. Comparing the whole field value against
  17587. // one option misses a client that sends several of them, and misses every
  17588. // casing but the one written in the comparison.
  17589. //
  17590. // Sends req, reads the response, then reuses the same socket for a second
  17591. // request to find out whether the server kept the connection.
  17592. static void probe_connection_reuse(int port, const std::string &req,
  17593. bool *announced_close, bool *reusable) {
  17594. auto error = Error::Success;
  17595. auto sock = detail::create_client_socket(
  17596. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17597. /*connection_timeout_sec=*/5, 0,
  17598. /*read_timeout_sec=*/1, 0,
  17599. /*write_timeout_sec=*/5, 0, std::string(), error);
  17600. ASSERT_NE(sock, INVALID_SOCKET);
  17601. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17602. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17603. "Host: localhost\r\n"
  17604. "Connection: close\r\n"
  17605. "\r\n";
  17606. std::string first_response;
  17607. std::string second_response;
  17608. detail::process_client_socket(
  17609. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17610. [&](Stream &strm) {
  17611. if (strm.write(req.data(), req.size()) !=
  17612. static_cast<ssize_t>(req.size())) {
  17613. return false;
  17614. }
  17615. char buf[512];
  17616. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17617. // Headers plus the two-byte body of the handler below
  17618. while (reader.getline()) {
  17619. first_response += reader.ptr();
  17620. if (first_response.find("ok") != std::string::npos) { break; }
  17621. }
  17622. if (strm.write(second.data(), second.size()) !=
  17623. static_cast<ssize_t>(second.size())) {
  17624. return true;
  17625. }
  17626. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17627. while (reader2.getline()) {
  17628. second_response += reader2.ptr();
  17629. if (second_response.find("ok") != std::string::npos) { break; }
  17630. }
  17631. return true;
  17632. });
  17633. *announced_close =
  17634. first_response.find("Connection: close") != std::string::npos;
  17635. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17636. }
  17637. class ConnectionTokenTest : public ::testing::Test {
  17638. protected:
  17639. void SetUp() override {
  17640. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17641. res.set_content("ok", "text/plain");
  17642. });
  17643. port_ = svr_.bind_to_any_port(HOST);
  17644. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17645. svr_.wait_until_ready();
  17646. }
  17647. void TearDown() override {
  17648. svr_.stop();
  17649. if (thread_.joinable()) { thread_.join(); }
  17650. }
  17651. Server svr_;
  17652. int port_ = 0;
  17653. thread thread_;
  17654. };
  17655. // "close" alongside another option still closes the connection, and the
  17656. // response says so rather than leaving the peer to discover it.
  17657. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17658. bool announced_close = false;
  17659. bool reusable = true;
  17660. probe_connection_reuse(port_,
  17661. "GET /keepalive HTTP/1.1\r\n"
  17662. "Host: localhost\r\n"
  17663. "Connection: keep-alive, close\r\n"
  17664. "\r\n",
  17665. &announced_close, &reusable);
  17666. EXPECT_TRUE(announced_close);
  17667. EXPECT_FALSE(reusable);
  17668. }
  17669. // "close" split over two field lines is the same list, so it is honored too.
  17670. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17671. bool announced_close = false;
  17672. bool reusable = true;
  17673. probe_connection_reuse(port_,
  17674. "GET /keepalive HTTP/1.1\r\n"
  17675. "Host: localhost\r\n"
  17676. "Connection: keep-alive\r\n"
  17677. "Connection: close\r\n"
  17678. "\r\n",
  17679. &announced_close, &reusable);
  17680. EXPECT_TRUE(announced_close);
  17681. EXPECT_FALSE(reusable);
  17682. }
  17683. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17684. // keep-alive in the spelling everyone actually sends keeps its connection.
  17685. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17686. bool announced_close = false;
  17687. bool reusable = false;
  17688. probe_connection_reuse(port_,
  17689. "GET /keepalive HTTP/1.0\r\n"
  17690. "Host: localhost\r\n"
  17691. "Connection: keep-alive\r\n"
  17692. "\r\n",
  17693. &announced_close, &reusable);
  17694. EXPECT_FALSE(announced_close);
  17695. EXPECT_TRUE(reusable);
  17696. }
  17697. // A token the value merely contains is not the token itself.
  17698. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17699. bool announced_close = false;
  17700. bool reusable = false;
  17701. probe_connection_reuse(port_,
  17702. "GET /keepalive HTTP/1.1\r\n"
  17703. "Host: localhost\r\n"
  17704. "Connection: notclose\r\n"
  17705. "\r\n",
  17706. &announced_close, &reusable);
  17707. EXPECT_FALSE(announced_close);
  17708. EXPECT_TRUE(reusable);
  17709. }
  17710. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17711. Server svr;
  17712. std::vector<std::string> observed_types;
  17713. svr.Get("/", [&](const Request &req, Response &res) {
  17714. observed_types = req.accept_content_types;
  17715. res.set_content("ok", "text/plain");
  17716. });
  17717. auto port = svr.bind_to_any_port(HOST);
  17718. thread t = thread([&]() { svr.listen_after_bind(); });
  17719. auto se = detail::scope_exit([&] {
  17720. svr.stop();
  17721. t.join();
  17722. ASSERT_FALSE(svr.is_running());
  17723. });
  17724. svr.wait_until_ready();
  17725. Client cli(HOST, port);
  17726. Headers headers;
  17727. headers.emplace("Accept", "text/plain;q=0.5");
  17728. headers.emplace("Accept", "application/json");
  17729. auto res = cli.Get("/", headers);
  17730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17731. EXPECT_EQ(StatusCode::OK_200, res->status);
  17732. // Sorted by q-value, so the second field line's type comes first
  17733. ASSERT_EQ(2U, observed_types.size());
  17734. EXPECT_EQ("application/json", observed_types[0]);
  17735. EXPECT_EQ("text/plain", observed_types[1]);
  17736. }
  17737. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17738. // empty field line must not contribute a bare comma to the combined value.
  17739. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17740. Server svr;
  17741. std::vector<std::string> observed_types;
  17742. svr.Get("/", [&](const Request &req, Response &res) {
  17743. observed_types = req.accept_content_types;
  17744. res.set_content("ok", "text/plain");
  17745. });
  17746. auto port = svr.bind_to_any_port(HOST);
  17747. thread t = thread([&]() { svr.listen_after_bind(); });
  17748. auto se = detail::scope_exit([&] {
  17749. svr.stop();
  17750. t.join();
  17751. ASSERT_FALSE(svr.is_running());
  17752. });
  17753. svr.wait_until_ready();
  17754. // Empty first field line, then a real one
  17755. std::string raw_req = "GET / HTTP/1.1\r\n"
  17756. "Host: localhost\r\n"
  17757. "Accept:\r\n"
  17758. "Accept: application/json\r\n"
  17759. "Connection: close\r\n"
  17760. "\r\n";
  17761. std::string out;
  17762. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17763. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17764. ASSERT_EQ(1U, observed_types.size());
  17765. EXPECT_EQ("application/json", observed_types[0]);
  17766. }
  17767. // The skip in get_combined_header_value() is what keeps an empty field line
  17768. // from contributing a bare comma. Only a trailing empty field line exercises
  17769. // it: a leading one is already covered by the "combined is still empty" check,
  17770. // and parse_accept_header() now ignores the empty element either way, so the
  17771. // request-level test above can no longer tell the two apart.
  17772. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17773. Headers headers;
  17774. headers.emplace("Accept", "text/html");
  17775. headers.emplace("Accept", "");
  17776. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17777. headers.clear();
  17778. headers.emplace("Accept", "");
  17779. headers.emplace("Accept", "application/json");
  17780. EXPECT_EQ("application/json",
  17781. detail::get_combined_header_value(headers, "Accept"));
  17782. }
  17783. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17784. // An encoding offered on a later Accept-Encoding field line is still offered.
  17785. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17786. Server svr;
  17787. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17788. res.set_content(std::string(1024, 'x'), "text/plain");
  17789. });
  17790. auto port = svr.bind_to_any_port(HOST);
  17791. thread t = thread([&]() { svr.listen_after_bind(); });
  17792. auto se = detail::scope_exit([&] {
  17793. svr.stop();
  17794. t.join();
  17795. ASSERT_FALSE(svr.is_running());
  17796. });
  17797. svr.wait_until_ready();
  17798. Client cli(HOST, port);
  17799. cli.set_decompress(false);
  17800. Headers headers;
  17801. headers.emplace("Accept-Encoding", "identity");
  17802. headers.emplace("Accept-Encoding", "gzip");
  17803. auto res = cli.Get("/", headers);
  17804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17805. EXPECT_EQ(StatusCode::OK_200, res->status);
  17806. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17807. }
  17808. #endif
  17809. #ifndef _WIN32
  17810. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17811. Server svr;
  17812. svr.Post("/post", [&](const Request &req, Response &res) {
  17813. res.set_content(req.body, "text/plain");
  17814. });
  17815. svr.Put("/put", [&](const Request &req, Response &res) {
  17816. res.set_content(req.body, "text/plain");
  17817. });
  17818. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17819. res.set_content(req.body, "text/plain");
  17820. });
  17821. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17822. res.set_content(req.body, "text/plain");
  17823. });
  17824. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17825. auto se = detail::scope_exit([&] {
  17826. svr.stop();
  17827. t.join();
  17828. ASSERT_FALSE(svr.is_running());
  17829. });
  17830. svr.wait_until_ready();
  17831. std::string resp;
  17832. // POST without Content-Length
  17833. ASSERT_TRUE(send_request(5,
  17834. "POST /post HTTP/1.1\r\n"
  17835. "Host: localhost\r\n"
  17836. "Connection: close\r\n"
  17837. "\r\n",
  17838. &resp));
  17839. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17840. // PUT without Content-Length
  17841. resp.clear();
  17842. ASSERT_TRUE(send_request(5,
  17843. "PUT /put HTTP/1.1\r\n"
  17844. "Host: localhost\r\n"
  17845. "Connection: close\r\n"
  17846. "\r\n",
  17847. &resp));
  17848. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17849. // PATCH without Content-Length
  17850. resp.clear();
  17851. ASSERT_TRUE(send_request(5,
  17852. "PATCH /patch HTTP/1.1\r\n"
  17853. "Host: localhost\r\n"
  17854. "Connection: close\r\n"
  17855. "\r\n",
  17856. &resp));
  17857. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17858. // DELETE without Content-Length
  17859. resp.clear();
  17860. ASSERT_TRUE(send_request(5,
  17861. "DELETE /delete HTTP/1.1\r\n"
  17862. "Host: localhost\r\n"
  17863. "Connection: close\r\n"
  17864. "\r\n",
  17865. &resp));
  17866. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17867. }
  17868. #endif
  17869. //==============================================================================
  17870. // open_stream() Tests
  17871. //==============================================================================
  17872. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17873. std::string result;
  17874. char buf[8192];
  17875. ssize_t n;
  17876. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17877. result.append(buf, static_cast<size_t>(n));
  17878. }
  17879. return result;
  17880. }
  17881. // Mock stream for unit tests
  17882. class MockStream : public Stream {
  17883. public:
  17884. std::string data;
  17885. size_t pos = 0;
  17886. ssize_t error_after = -1; // -1 = no error
  17887. explicit MockStream(const std::string &d, ssize_t err = -1)
  17888. : data(d), error_after(err) {}
  17889. bool is_readable() const override { return true; }
  17890. bool wait_readable() const override { return true; }
  17891. bool wait_writable() const override { return true; }
  17892. ssize_t read(char *ptr, size_t size) override {
  17893. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17894. if (pos >= data.size()) return 0;
  17895. size_t limit =
  17896. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17897. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17898. std::memcpy(ptr, data.data() + pos, to_read);
  17899. pos += to_read;
  17900. return static_cast<ssize_t>(to_read);
  17901. }
  17902. ssize_t write(const char *, size_t) override { return -1; }
  17903. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17904. ip = "127.0.0.1";
  17905. port = 0;
  17906. }
  17907. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17908. ip = "127.0.0.1";
  17909. port = 0;
  17910. }
  17911. socket_t socket() const override { return INVALID_SOCKET; }
  17912. time_t duration() const override { return 0; }
  17913. };
  17914. TEST(StreamHandleTest, Basic) {
  17915. ClientImpl::StreamHandle handle;
  17916. EXPECT_FALSE(handle.is_valid());
  17917. handle.response = detail::make_unique<Response>();
  17918. handle.error = Error::Connection;
  17919. EXPECT_FALSE(handle.is_valid());
  17920. handle.error = Error::Success;
  17921. EXPECT_TRUE(handle.is_valid());
  17922. }
  17923. TEST(BodyReaderTest, Basic) {
  17924. MockStream stream("Hello, World!");
  17925. detail::BodyReader reader;
  17926. reader.stream = &stream;
  17927. reader.content_length = 13;
  17928. char buf[32];
  17929. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17930. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17931. EXPECT_TRUE(reader.eof);
  17932. }
  17933. TEST(BodyReaderTest, NoStream) {
  17934. detail::BodyReader reader;
  17935. char buf[32];
  17936. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17937. EXPECT_EQ(Error::Connection, reader.last_error);
  17938. }
  17939. TEST(BodyReaderTest, Error) {
  17940. MockStream stream("Hello, World!", 5);
  17941. detail::BodyReader reader;
  17942. reader.stream = &stream;
  17943. reader.content_length = 13;
  17944. char buf[32];
  17945. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17946. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17947. EXPECT_EQ(Error::Read, reader.last_error);
  17948. }
  17949. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17950. // Mock-based StreamHandle tests relying on private internals are removed.
  17951. class OpenStreamTest : public ::testing::Test {
  17952. protected:
  17953. void SetUp() override {
  17954. svr_.Get("/hello", [](const Request &, Response &res) {
  17955. res.set_content("Hello World!", "text/plain");
  17956. });
  17957. svr_.Get("/large", [](const Request &, Response &res) {
  17958. res.set_content(std::string(10000, 'X'), "text/plain");
  17959. });
  17960. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17961. res.set_content("Hello World!", "image/jpeg");
  17962. res.set_header("Content-Encoding", "UTF-8");
  17963. });
  17964. svr_.Get("/chunked", [](const Request &, Response &res) {
  17965. res.set_chunked_content_provider("text/plain",
  17966. [](size_t offset, DataSink &sink) {
  17967. if (offset < 15) {
  17968. sink.write("chunk", 5);
  17969. return true;
  17970. }
  17971. sink.done();
  17972. return true;
  17973. });
  17974. });
  17975. svr_.Get("/compressible", [](const Request &, Response &res) {
  17976. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17977. DataSink &sink) {
  17978. if (offset < 100 * 1024) {
  17979. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17980. sink.write(chunk.data(), chunk.size());
  17981. return true;
  17982. }
  17983. sink.done();
  17984. return true;
  17985. });
  17986. });
  17987. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17988. [](const Request & /*req*/, Response &res) {
  17989. auto i = new int(0);
  17990. res.set_header("Trailer", "Content-Length, X-Allowed");
  17991. res.set_chunked_content_provider(
  17992. "text/plain",
  17993. [i](size_t /*offset*/, DataSink &sink) {
  17994. switch (*i) {
  17995. case 0: sink.os << "123"; break;
  17996. case 1: sink.os << "456"; break;
  17997. case 2: sink.os << "789"; break;
  17998. case 3: {
  17999. sink.done_with_trailer(
  18000. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18001. } break;
  18002. }
  18003. (*i)++;
  18004. return true;
  18005. },
  18006. [i](bool success) {
  18007. EXPECT_TRUE(success);
  18008. delete i;
  18009. });
  18010. });
  18011. // Echo headers endpoint for header-related tests
  18012. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18013. std::string body;
  18014. for (const auto &h : req.headers) {
  18015. body.append(h.first);
  18016. body.push_back(':');
  18017. body.append(h.second);
  18018. body.push_back('\n');
  18019. }
  18020. res.set_content(body, "text/plain");
  18021. });
  18022. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18023. std::string body;
  18024. for (const auto &h : req.headers) {
  18025. body.append(h.first);
  18026. body.push_back(':');
  18027. body.append(h.second);
  18028. body.push_back('\n');
  18029. }
  18030. res.set_content(body, "text/plain");
  18031. });
  18032. port_ = svr_.bind_to_any_port("127.0.0.1");
  18033. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18034. svr_.wait_until_ready();
  18035. }
  18036. void TearDown() override {
  18037. svr_.stop();
  18038. if (thread_.joinable()) thread_.join();
  18039. }
  18040. Server svr_;
  18041. std::thread thread_;
  18042. int port_ = 0;
  18043. };
  18044. TEST_F(OpenStreamTest, Basic) {
  18045. Client cli("127.0.0.1", port_);
  18046. auto handle = cli.open_stream("GET", "/hello");
  18047. EXPECT_TRUE(handle.is_valid());
  18048. EXPECT_EQ("Hello World!", read_all(handle));
  18049. }
  18050. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18051. Client cli("127.0.0.1", port_);
  18052. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18053. ASSERT_TRUE(handle.is_valid());
  18054. EXPECT_EQ("Hello World!", read_all(handle));
  18055. }
  18056. TEST_F(OpenStreamTest, SmallBuffer) {
  18057. Client cli("127.0.0.1", port_);
  18058. auto handle = cli.open_stream("GET", "/hello");
  18059. std::string result;
  18060. char buf[4];
  18061. ssize_t n;
  18062. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18063. result.append(buf, static_cast<size_t>(n));
  18064. EXPECT_EQ("Hello World!", result);
  18065. }
  18066. TEST_F(OpenStreamTest, DefaultHeaders) {
  18067. Client cli("127.0.0.1", port_);
  18068. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18069. {
  18070. auto handle = cli.open_stream("GET", "/echo-headers");
  18071. ASSERT_TRUE(handle.is_valid());
  18072. auto body = read_all(handle);
  18073. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18074. std::string::npos);
  18075. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18076. std::string::npos);
  18077. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18078. }
  18079. // open_stream POST with body and no explicit content_type should NOT add
  18080. // text/plain Content-Type (behavior differs from non-streaming path), but
  18081. // should include Content-Length
  18082. {
  18083. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18084. ASSERT_TRUE(handle.is_valid());
  18085. auto body = read_all(handle);
  18086. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18087. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18088. }
  18089. // open_stream POST with explicit Content-Type should preserve it
  18090. {
  18091. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18092. {{"Content-Type", "application/custom"}},
  18093. "{}", "application/custom");
  18094. ASSERT_TRUE(handle.is_valid());
  18095. auto body = read_all(handle);
  18096. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18097. }
  18098. // User-specified User-Agent must not be overwritten for stream API
  18099. {
  18100. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18101. {{"User-Agent", "MyAgent/1.2"}});
  18102. ASSERT_TRUE(handle.is_valid());
  18103. auto body = read_all(handle);
  18104. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18105. }
  18106. }
  18107. TEST_F(OpenStreamTest, Large) {
  18108. Client cli("127.0.0.1", port_);
  18109. auto handle = cli.open_stream("GET", "/large");
  18110. EXPECT_EQ(10000u, read_all(handle).size());
  18111. }
  18112. TEST_F(OpenStreamTest, ConnectionError) {
  18113. Client cli("127.0.0.1", 9999);
  18114. auto handle = cli.open_stream("GET", "/hello");
  18115. EXPECT_FALSE(handle.is_valid());
  18116. }
  18117. TEST_F(OpenStreamTest, Chunked) {
  18118. Client cli("127.0.0.1", port_);
  18119. auto handle = cli.open_stream("GET", "/chunked");
  18120. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18121. "Transfer-Encoding") == "chunked");
  18122. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18123. }
  18124. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18125. Client cli("127.0.0.1", port_);
  18126. auto handle =
  18127. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18128. ASSERT_TRUE(handle.is_valid());
  18129. // Consume body to allow trailers to be received/parsed
  18130. auto body = read_all(handle);
  18131. // Explicitly parse trailers (ensure trailers are available for assertion)
  18132. handle.parse_trailers_if_needed();
  18133. EXPECT_EQ(std::string("123456789"), body);
  18134. // The response should include a Trailer header declaring both names
  18135. ASSERT_TRUE(handle.response);
  18136. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18137. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18138. handle.response->get_header_value("Trailer"));
  18139. // Prohibited trailer must not be present
  18140. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18141. // Allowed trailer should be present
  18142. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18143. EXPECT_EQ(std::string("yes"),
  18144. handle.response->get_trailer_value("X-Allowed"));
  18145. // Verify trailers are NOT present as regular headers
  18146. EXPECT_EQ(std::string(""),
  18147. handle.response->get_header_value("Content-Length"));
  18148. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18149. }
  18150. static std::thread serve_single_response(std::promise<int> &port_promise,
  18151. const std::string &response) {
  18152. return std::thread([&port_promise, response] {
  18153. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18154. default_socket_options(srv);
  18155. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18156. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18157. sockaddr_in addr{};
  18158. addr.sin_family = AF_INET;
  18159. addr.sin_port = htons(0); // Let OS assign a free port
  18160. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18161. int opt = 1;
  18162. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18163. #ifdef _WIN32
  18164. reinterpret_cast<const char *>(&opt),
  18165. #else
  18166. &opt,
  18167. #endif
  18168. sizeof(opt));
  18169. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18170. ::listen(srv, 1) != 0) {
  18171. port_promise.set_value(-1);
  18172. detail::close_socket(srv);
  18173. return;
  18174. }
  18175. socklen_t addr_len = sizeof(addr);
  18176. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18177. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18178. sockaddr_in cli_addr{};
  18179. socklen_t cli_len = sizeof(cli_addr);
  18180. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18181. if (cli != INVALID_SOCKET) {
  18182. // Read the complete HTTP request (until the blank line that terminates
  18183. // headers) before sending the response. If the server closes the socket
  18184. // while the client's request data is still unread in the kernel receive
  18185. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18186. // connection on both sides: it discards the client's receive buffer
  18187. // (which already holds our response) and causes any in-progress write on
  18188. // the client to fail with ECONNRESET. Reading all request data first
  18189. // ensures close() emits a graceful FIN.
  18190. {
  18191. char rbuf[256];
  18192. std::string req;
  18193. while (req.find("\r\n\r\n") == std::string::npos) {
  18194. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18195. if (n <= 0) { break; }
  18196. req.append(rbuf, static_cast<size_t>(n));
  18197. }
  18198. }
  18199. ::send(cli,
  18200. #ifdef _WIN32
  18201. static_cast<const char *>(response.c_str()),
  18202. static_cast<int>(response.size()),
  18203. #else
  18204. response.c_str(), response.size(),
  18205. #endif
  18206. 0);
  18207. detail::close_socket(cli);
  18208. }
  18209. detail::close_socket(srv);
  18210. });
  18211. }
  18212. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18213. #ifndef _WIN32
  18214. signal(SIGPIPE, SIG_IGN);
  18215. #endif
  18216. std::promise<int> port_promise;
  18217. auto port_future = port_promise.get_future();
  18218. auto server_thread =
  18219. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18220. "Content-Type: text/plain\r\n"
  18221. "Content-Length: not-a-number\r\n"
  18222. "Connection: close\r\n"
  18223. "\r\n"
  18224. "hello");
  18225. auto port = port_future.get();
  18226. ASSERT_GT(port, 0);
  18227. Client cli("127.0.0.1", port);
  18228. auto handle = cli.open_stream("GET", "/");
  18229. EXPECT_FALSE(handle.is_valid());
  18230. server_thread.join();
  18231. }
  18232. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18233. #ifndef _WIN32
  18234. signal(SIGPIPE, SIG_IGN);
  18235. #endif
  18236. std::promise<int> port_promise;
  18237. auto port_future = port_promise.get_future();
  18238. auto server_thread = serve_single_response(
  18239. port_promise, "HTTP/1.1 200 OK\r\n"
  18240. "Content-Type: text/plain\r\n"
  18241. "Content-Length: 99999999999999999999999999\r\n"
  18242. "Connection: close\r\n"
  18243. "\r\n"
  18244. "hello");
  18245. auto port = port_future.get();
  18246. ASSERT_GT(port, 0);
  18247. // Historically std::stoull would throw std::out_of_range here and crash
  18248. // the process, then parsing silently clamped to a bogus framing length and
  18249. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18250. // so the stream fails to open, matching the not-a-number case above. The
  18251. // process still must NOT terminate.
  18252. Client cli("127.0.0.1", port);
  18253. auto handle = cli.open_stream("GET", "/");
  18254. EXPECT_FALSE(handle.is_valid());
  18255. server_thread.join();
  18256. }
  18257. // Serves `response` to the single request `fn` makes with a fresh client.
  18258. template <typename Fn>
  18259. static void with_single_response(const std::string &response, Fn fn) {
  18260. #ifndef _WIN32
  18261. signal(SIGPIPE, SIG_IGN);
  18262. #endif
  18263. std::promise<int> port_promise;
  18264. auto port_future = port_promise.get_future();
  18265. auto server_thread = serve_single_response(port_promise, response);
  18266. auto se = detail::scope_exit([&] { server_thread.join(); });
  18267. auto port = port_future.get();
  18268. ASSERT_GT(port, 0);
  18269. Client cli("127.0.0.1", port);
  18270. fn(cli);
  18271. }
  18272. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18273. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18274. // the chunked coding and drop Content-Length, so a front-end that trusts
  18275. // Content-Length would disagree about where the body ends (response
  18276. // smuggling). The client must reject such a response.
  18277. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18278. for (const char *te : {"chunked", "gzip, chunked"}) {
  18279. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18280. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18281. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18282. "5\r\nhello\r\n0\r\n\r\n";
  18283. with_single_response(response, [&](Client &cli) {
  18284. auto res = cli.Get("/");
  18285. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18286. EXPECT_EQ(Error::Read, res.error()) << te;
  18287. });
  18288. with_single_response(response, [&](Client &cli) {
  18289. auto handle = cli.open_stream("GET", "/");
  18290. EXPECT_FALSE(handle.is_valid()) << te;
  18291. EXPECT_EQ(Error::Read, handle.error) << te;
  18292. });
  18293. }
  18294. }
  18295. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18296. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18297. // closing the connection (unlike a request, which must be rejected).
  18298. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18299. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18300. "Transfer-Encoding: chunked\r\n"
  18301. "Connection: close\r\n"
  18302. "\r\n"
  18303. "5\r\nhello\r\n0\r\n\r\n",
  18304. "HTTP/1.1 200 OK\r\n"
  18305. "Transfer-Encoding: gzip\r\n"
  18306. "Connection: close\r\n"
  18307. "\r\n"
  18308. "hello"}) {
  18309. with_single_response(response, [&](Client &cli) {
  18310. auto res = cli.Get("/");
  18311. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18312. EXPECT_EQ("hello", res->body);
  18313. });
  18314. with_single_response(response, [&](Client &cli) {
  18315. auto handle = cli.open_stream("GET", "/");
  18316. ASSERT_TRUE(handle.is_valid()) << response;
  18317. EXPECT_EQ("hello", read_all(handle));
  18318. });
  18319. }
  18320. }
  18321. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18322. // framing headers describe nothing to read and must not be rejected.
  18323. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18324. const std::string framing = "Content-Length: 5\r\n"
  18325. "Transfer-Encoding: chunked\r\n"
  18326. "Connection: close\r\n"
  18327. "\r\n";
  18328. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18329. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18330. });
  18331. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18332. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18333. });
  18334. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18335. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18336. with_single_response(response, [&](Client &cli) {
  18337. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18338. });
  18339. with_single_response(response, [&](Client &cli) {
  18340. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18341. });
  18342. }
  18343. }
  18344. // A payload max length of 0 means no limit, however the body is framed.
  18345. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18346. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18347. "Transfer-Encoding: chunked\r\n"
  18348. "\r\n"
  18349. "5\r\nhello\r\n0\r\n\r\n",
  18350. "HTTP/1.1 200 OK\r\n"
  18351. "Connection: close\r\n"
  18352. "\r\n"
  18353. "hello"}) {
  18354. with_single_response(response, [&](Client &cli) {
  18355. cli.set_payload_max_length(0);
  18356. auto res = cli.Get("/");
  18357. ASSERT_TRUE(res) << response;
  18358. EXPECT_EQ("hello", res->body) << response;
  18359. });
  18360. }
  18361. }
  18362. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18363. Server svr;
  18364. svr.set_payload_max_length(0);
  18365. svr.Post("/echo", [](const Request &req, Response &res) {
  18366. res.set_content(req.body, "text/plain");
  18367. });
  18368. auto port = svr.bind_to_any_port(HOST);
  18369. thread t = thread([&] { svr.listen_after_bind(); });
  18370. auto se = detail::scope_exit([&] {
  18371. svr.stop();
  18372. t.join();
  18373. ASSERT_FALSE(svr.is_running());
  18374. });
  18375. svr.wait_until_ready();
  18376. Client cli(HOST, port);
  18377. auto res = cli.Post(
  18378. "/echo",
  18379. [](size_t /*offset*/, DataSink &sink) {
  18380. sink.write("hello", 5);
  18381. sink.done();
  18382. return true;
  18383. },
  18384. "text/plain");
  18385. ASSERT_TRUE(res);
  18386. EXPECT_EQ(StatusCode::OK_200, res->status);
  18387. EXPECT_EQ("hello", res->body);
  18388. }
  18389. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18390. TEST_F(OpenStreamTest, Gzip) {
  18391. Client cli("127.0.0.1", port_);
  18392. auto handle = cli.open_stream("GET", "/compressible", {},
  18393. {{"Accept-Encoding", "gzip"}});
  18394. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18395. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18396. }
  18397. #endif
  18398. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18399. TEST_F(OpenStreamTest, Brotli) {
  18400. Client cli("127.0.0.1", port_);
  18401. auto handle =
  18402. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18403. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18404. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18405. }
  18406. #endif
  18407. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18408. TEST_F(OpenStreamTest, Zstd) {
  18409. Client cli("127.0.0.1", port_);
  18410. auto handle = cli.open_stream("GET", "/compressible", {},
  18411. {{"Accept-Encoding", "zstd"}});
  18412. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18413. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18414. }
  18415. #endif
  18416. #ifdef CPPHTTPLIB_SSL_ENABLED
  18417. class SSLOpenStreamTest : public ::testing::Test {
  18418. protected:
  18419. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18420. void SetUp() override {
  18421. svr_.Get("/hello", [](const Request &, Response &res) {
  18422. res.set_content("Hello SSL World!", "text/plain");
  18423. });
  18424. svr_.Get("/chunked", [](const Request &, Response &res) {
  18425. res.set_chunked_content_provider("text/plain",
  18426. [](size_t offset, DataSink &sink) {
  18427. if (offset < 15) {
  18428. sink.write("chunk", 5);
  18429. return true;
  18430. }
  18431. sink.done();
  18432. return true;
  18433. });
  18434. });
  18435. svr_.Post("/echo", [](const Request &req, Response &res) {
  18436. res.set_content(req.body, req.get_header_value("Content-Type"));
  18437. });
  18438. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18439. std::string body = req.body;
  18440. res.set_chunked_content_provider(
  18441. "text/plain", [body](size_t offset, DataSink &sink) {
  18442. if (offset < body.size()) {
  18443. sink.write(body.data() + offset, body.size() - offset);
  18444. }
  18445. sink.done();
  18446. return true;
  18447. });
  18448. });
  18449. port_ = svr_.bind_to_any_port("127.0.0.1");
  18450. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18451. svr_.wait_until_ready();
  18452. }
  18453. void TearDown() override {
  18454. svr_.stop();
  18455. if (thread_.joinable()) thread_.join();
  18456. }
  18457. SSLServer svr_;
  18458. std::thread thread_;
  18459. int port_ = 0;
  18460. };
  18461. TEST_F(SSLOpenStreamTest, Basic) {
  18462. SSLClient cli("127.0.0.1", port_);
  18463. cli.enable_server_certificate_verification(false);
  18464. auto handle = cli.open_stream("GET", "/hello");
  18465. ASSERT_TRUE(handle.is_valid());
  18466. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18467. }
  18468. TEST_F(SSLOpenStreamTest, Chunked) {
  18469. SSLClient cli("127.0.0.1", port_);
  18470. cli.enable_server_certificate_verification(false);
  18471. auto handle = cli.open_stream("GET", "/chunked");
  18472. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18473. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18474. "Transfer-Encoding") == "chunked");
  18475. auto body = read_all(handle);
  18476. EXPECT_EQ("chunkchunkchunk", body);
  18477. }
  18478. TEST_F(SSLOpenStreamTest, Post) {
  18479. SSLClient cli("127.0.0.1", port_);
  18480. cli.enable_server_certificate_verification(false);
  18481. auto handle =
  18482. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18483. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18484. EXPECT_EQ(200, handle.response->status);
  18485. auto body = read_all(handle);
  18486. EXPECT_EQ("Hello SSL POST", body);
  18487. }
  18488. TEST_F(SSLOpenStreamTest, PostChunked) {
  18489. SSLClient cli("127.0.0.1", port_);
  18490. cli.enable_server_certificate_verification(false);
  18491. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18492. "Chunked SSL Data", "text/plain");
  18493. ASSERT_TRUE(handle.is_valid());
  18494. EXPECT_EQ(200, handle.response->status);
  18495. auto body = read_all(handle);
  18496. EXPECT_EQ("Chunked SSL Data", body);
  18497. }
  18498. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18499. // Content-Length is terminated by the server closing the connection. When the
  18500. // SSL peer sends a close_notify after the body, the client must treat it as a
  18501. // clean EOF and return a successful response rather than an error.
  18502. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18503. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18504. ASSERT_TRUE(svr.is_valid());
  18505. svr.set_keep_alive_max_count(1);
  18506. const std::string expected_body = "Hello from connection-close response!";
  18507. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18508. res.set_content_provider("text/plain",
  18509. [&](size_t offset, DataSink &sink) -> bool {
  18510. if (offset < expected_body.size()) {
  18511. sink.write(expected_body.data() + offset,
  18512. expected_body.size() - offset);
  18513. }
  18514. sink.done();
  18515. return true;
  18516. });
  18517. });
  18518. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18519. auto se = detail::scope_exit([&] {
  18520. svr.stop();
  18521. listen_thread.join();
  18522. ASSERT_FALSE(svr.is_running());
  18523. });
  18524. svr.wait_until_ready();
  18525. SSLClient cli(HOST, PORT);
  18526. cli.enable_server_certificate_verification(false);
  18527. auto res = cli.Get("/no-content-length");
  18528. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18529. EXPECT_EQ(StatusCode::OK_200, res->status);
  18530. EXPECT_EQ(expected_body, res->body);
  18531. }
  18532. #endif // CPPHTTPLIB_SSL_ENABLED
  18533. //==============================================================================
  18534. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18535. // results for various scenarios.
  18536. //==============================================================================
  18537. TEST(ParityTest, GetVsOpenStream) {
  18538. Server svr;
  18539. const std::string path = "/parity";
  18540. const std::string content = "Parity test content: hello world";
  18541. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18542. res.set_content(content, "text/plain");
  18543. });
  18544. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18545. auto se = detail::scope_exit([&] {
  18546. svr.stop();
  18547. t.join();
  18548. ASSERT_FALSE(svr.is_running());
  18549. });
  18550. svr.wait_until_ready();
  18551. Client cli(HOST, PORT);
  18552. // Non-stream path
  18553. auto r1 = cli.Get(path);
  18554. ASSERT_TRUE(r1);
  18555. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18556. // Stream path
  18557. auto h = cli.open_stream("GET", path);
  18558. ASSERT_TRUE(h.is_valid());
  18559. EXPECT_EQ(r1->body, read_all(h));
  18560. }
  18561. // Helper to compress data with provided compressor type T
  18562. template <typename Compressor>
  18563. static std::string compress_payload_for_parity(const std::string &in) {
  18564. std::string out;
  18565. Compressor compressor;
  18566. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18567. [&](const char *data, size_t n) {
  18568. out.append(data, n);
  18569. return true;
  18570. });
  18571. EXPECT_TRUE(ok);
  18572. return out;
  18573. }
  18574. // Helper function for compression parity tests
  18575. template <typename Compressor>
  18576. static void test_compression_parity(const std::string &original,
  18577. const std::string &path,
  18578. const std::string &encoding) {
  18579. const std::string compressed =
  18580. compress_payload_for_parity<Compressor>(original);
  18581. Server svr;
  18582. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18583. res.set_content(compressed, "application/octet-stream");
  18584. res.set_header("Content-Encoding", encoding);
  18585. });
  18586. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18587. auto se = detail::scope_exit([&] {
  18588. svr.stop();
  18589. t.join();
  18590. ASSERT_FALSE(svr.is_running());
  18591. });
  18592. svr.wait_until_ready();
  18593. Client cli(HOST, PORT);
  18594. // Non-streaming
  18595. {
  18596. auto res = cli.Get(path);
  18597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18598. EXPECT_EQ(StatusCode::OK_200, res->status);
  18599. EXPECT_EQ(original, res->body);
  18600. }
  18601. // Streaming
  18602. {
  18603. auto h = cli.open_stream("GET", path);
  18604. ASSERT_TRUE(h.is_valid());
  18605. EXPECT_EQ(original, read_all(h));
  18606. }
  18607. }
  18608. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18609. TEST(ParityTest, Gzip) {
  18610. test_compression_parity<detail::gzip_compressor>(
  18611. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18612. }
  18613. #endif
  18614. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18615. TEST(ParityTest, Brotli) {
  18616. test_compression_parity<detail::brotli_compressor>(
  18617. "Hello, brotli parity test payload", "/parity-br", "br");
  18618. }
  18619. #endif
  18620. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18621. TEST(ParityTest, Zstd) {
  18622. test_compression_parity<detail::zstd_compressor>(
  18623. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18624. }
  18625. #endif
  18626. //==============================================================================
  18627. // New Stream API Tests
  18628. //==============================================================================
  18629. inline std::string read_body(httplib::stream::Result &result) {
  18630. std::string body;
  18631. while (result.next()) {
  18632. body.append(result.data(), result.size());
  18633. }
  18634. return body;
  18635. }
  18636. TEST(ClientConnectionTest, Basic) {
  18637. httplib::ClientConnection conn;
  18638. EXPECT_FALSE(conn.is_open());
  18639. conn.sock = 1;
  18640. EXPECT_TRUE(conn.is_open());
  18641. httplib::ClientConnection conn2(std::move(conn));
  18642. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18643. conn2.sock = INVALID_SOCKET;
  18644. }
  18645. // Unified test server for all stream::* tests
  18646. class StreamApiTest : public ::testing::Test {
  18647. protected:
  18648. void SetUp() override {
  18649. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18650. res.set_content("Hello World!", "text/plain");
  18651. });
  18652. svr_.Get("/echo-params",
  18653. [](const httplib::Request &req, httplib::Response &res) {
  18654. std::string r;
  18655. for (const auto &p : req.params) {
  18656. if (!r.empty()) r += "&";
  18657. r += p.first + "=" + p.second;
  18658. }
  18659. res.set_content(r, "text/plain");
  18660. });
  18661. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18662. res.set_content(req.body, req.get_header_value("Content-Type"));
  18663. });
  18664. svr_.Post("/echo-headers",
  18665. [](const httplib::Request &req, httplib::Response &res) {
  18666. std::string r;
  18667. for (const auto &h : req.headers)
  18668. r += h.first + ": " + h.second + "\n";
  18669. res.set_content(r, "text/plain");
  18670. });
  18671. svr_.Post("/echo-params",
  18672. [](const httplib::Request &req, httplib::Response &res) {
  18673. std::string r = "params:";
  18674. for (const auto &p : req.params)
  18675. r += p.first + "=" + p.second + ";";
  18676. res.set_content(r + " body:" + req.body, "text/plain");
  18677. });
  18678. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18679. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18680. });
  18681. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18682. res.set_content("PUT:" + req.body, "text/plain");
  18683. });
  18684. svr_.Patch("/echo",
  18685. [](const httplib::Request &req, httplib::Response &res) {
  18686. res.set_content("PATCH:" + req.body, "text/plain");
  18687. });
  18688. svr_.Delete(
  18689. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18690. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18691. "text/plain");
  18692. });
  18693. svr_.Get("/head-test",
  18694. [](const httplib::Request &, httplib::Response &res) {
  18695. res.set_content("body for HEAD", "text/plain");
  18696. });
  18697. svr_.Options("/options",
  18698. [](const httplib::Request &, httplib::Response &res) {
  18699. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18700. });
  18701. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18702. svr_.wait_until_ready();
  18703. }
  18704. void TearDown() override {
  18705. svr_.stop();
  18706. if (thread_.joinable()) thread_.join();
  18707. }
  18708. httplib::Server svr_;
  18709. std::thread thread_;
  18710. };
  18711. // stream::Get tests
  18712. TEST_F(StreamApiTest, GetBasic) {
  18713. httplib::Client cli(HOST, PORT);
  18714. auto result = httplib::stream::Get(cli, "/hello");
  18715. ASSERT_TRUE(result.is_valid());
  18716. EXPECT_EQ(200, result.status());
  18717. EXPECT_EQ("Hello World!", read_body(result));
  18718. }
  18719. TEST_F(StreamApiTest, GetWithParams) {
  18720. httplib::Client cli(HOST, PORT);
  18721. httplib::Params params{{"foo", "bar"}};
  18722. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18723. ASSERT_TRUE(result.is_valid());
  18724. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18725. }
  18726. TEST_F(StreamApiTest, GetConnectionError) {
  18727. httplib::Client cli(HOST, 9999);
  18728. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18729. }
  18730. TEST_F(StreamApiTest, Get404) {
  18731. httplib::Client cli(HOST, PORT);
  18732. auto result = httplib::stream::Get(cli, "/nonexistent");
  18733. EXPECT_TRUE(result.is_valid());
  18734. EXPECT_EQ(404, result.status());
  18735. }
  18736. // stream::Post tests
  18737. TEST_F(StreamApiTest, PostBasic) {
  18738. httplib::Client cli(HOST, PORT);
  18739. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18740. "application/json");
  18741. ASSERT_TRUE(result.is_valid());
  18742. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18743. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18744. }
  18745. TEST_F(StreamApiTest, PostWithHeaders) {
  18746. httplib::Client cli(HOST, PORT);
  18747. httplib::Headers headers{{"X-Custom", "value"}};
  18748. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18749. "text/plain");
  18750. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18751. }
  18752. TEST_F(StreamApiTest, PostWithParams) {
  18753. httplib::Client cli(HOST, PORT);
  18754. httplib::Params params{{"k", "v"}};
  18755. auto result =
  18756. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18757. auto body = read_body(result);
  18758. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18759. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18760. }
  18761. TEST_F(StreamApiTest, PostLarge) {
  18762. httplib::Client cli(HOST, PORT);
  18763. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18764. size_t total = 0;
  18765. while (result.next()) {
  18766. total += result.size();
  18767. }
  18768. EXPECT_EQ(100u * 1024u, total);
  18769. }
  18770. // stream::Put/Patch tests
  18771. TEST_F(StreamApiTest, PutAndPatch) {
  18772. httplib::Client cli(HOST, PORT);
  18773. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18774. EXPECT_EQ("PUT:test", read_body(put));
  18775. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18776. EXPECT_EQ("PATCH:test", read_body(patch));
  18777. }
  18778. // stream::Delete tests
  18779. TEST_F(StreamApiTest, Delete) {
  18780. httplib::Client cli(HOST, PORT);
  18781. auto del1 = httplib::stream::Delete(cli, "/resource");
  18782. EXPECT_EQ("Deleted", read_body(del1));
  18783. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18784. EXPECT_EQ("Deleted:data", read_body(del2));
  18785. }
  18786. // stream::Head/Options tests
  18787. TEST_F(StreamApiTest, HeadAndOptions) {
  18788. httplib::Client cli(HOST, PORT);
  18789. auto head = httplib::stream::Head(cli, "/head-test");
  18790. EXPECT_TRUE(head.is_valid());
  18791. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18792. auto opts = httplib::stream::Options(cli, "/options");
  18793. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18794. }
  18795. // SSL stream::* tests
  18796. #ifdef CPPHTTPLIB_SSL_ENABLED
  18797. class SSLStreamApiTest : public ::testing::Test {
  18798. protected:
  18799. void SetUp() override {
  18800. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18801. res.set_content("Hello SSL!", "text/plain");
  18802. });
  18803. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18804. res.set_content(req.body, "text/plain");
  18805. });
  18806. port_ = svr_.bind_to_any_port("127.0.0.1");
  18807. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18808. svr_.wait_until_ready();
  18809. }
  18810. void TearDown() override {
  18811. svr_.stop();
  18812. if (thread_.joinable()) thread_.join();
  18813. }
  18814. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18815. std::thread thread_;
  18816. int port_ = 0;
  18817. };
  18818. TEST_F(SSLStreamApiTest, GetAndPost) {
  18819. httplib::SSLClient cli("127.0.0.1", port_);
  18820. cli.enable_server_certificate_verification(false);
  18821. auto get = httplib::stream::Get(cli, "/hello");
  18822. EXPECT_EQ("Hello SSL!", read_body(get));
  18823. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18824. EXPECT_EQ("test", read_body(post));
  18825. }
  18826. #endif
  18827. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18828. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18829. // BodyReader
  18830. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18831. // Test that read timeout during streaming is detected
  18832. // Use a large content-length response where server delays mid-stream
  18833. Server svr;
  18834. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18835. // Send a large response with delay in the middle
  18836. res.set_content_provider(
  18837. 1000, // content_length
  18838. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18839. if (offset < 100) {
  18840. // Send first 100 bytes immediately
  18841. std::string data(100, 'A');
  18842. sink.write(data.c_str(), data.size());
  18843. return true;
  18844. }
  18845. // Then delay longer than client timeout
  18846. std::this_thread::sleep_for(std::chrono::seconds(3));
  18847. std::string data(900, 'B');
  18848. sink.write(data.c_str(), data.size());
  18849. return true;
  18850. });
  18851. });
  18852. auto port = 8091;
  18853. std::thread t([&]() { svr.listen("localhost", port); });
  18854. svr.wait_until_ready();
  18855. Client cli("localhost", port);
  18856. cli.set_read_timeout(1, 0); // 1 second timeout
  18857. auto handle = cli.open_stream("GET", "/slow-stream");
  18858. ASSERT_TRUE(handle.is_valid());
  18859. char buf[256];
  18860. ssize_t total = 0;
  18861. ssize_t n;
  18862. bool got_error = false;
  18863. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18864. total += n;
  18865. }
  18866. if (n < 0) {
  18867. got_error = true;
  18868. // Should be timeout or read error
  18869. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18870. handle.get_read_error() == Error::Read)
  18871. << "Actual error: " << to_string(handle.get_read_error());
  18872. }
  18873. // Either we got an error, or we got less data than expected
  18874. EXPECT_TRUE(got_error || total < 1000)
  18875. << "Expected timeout but got all " << total << " bytes";
  18876. svr.stop();
  18877. t.join();
  18878. }
  18879. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18880. // Test connection closed detection via BodyReader
  18881. Server svr;
  18882. std::atomic<bool> close_now{false};
  18883. svr.Get("/will-close", [&](const Request &, Response &res) {
  18884. res.set_content_provider(
  18885. 10000, // Large content_length that we won't fully send
  18886. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18887. if (offset < 100) {
  18888. std::string data(100, 'X');
  18889. sink.write(data.c_str(), data.size());
  18890. return true;
  18891. }
  18892. // Wait for signal then abort
  18893. while (!close_now) {
  18894. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18895. }
  18896. return false; // Abort - server will close connection
  18897. });
  18898. });
  18899. auto port = 8092;
  18900. std::thread t([&]() { svr.listen("localhost", port); });
  18901. svr.wait_until_ready();
  18902. Client cli("localhost", port);
  18903. auto handle = cli.open_stream("GET", "/will-close");
  18904. ASSERT_TRUE(handle.is_valid());
  18905. char buf[256];
  18906. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18907. EXPECT_GT(n, 0) << "First read should succeed";
  18908. // Signal server to close
  18909. close_now = true;
  18910. // Keep reading until error or EOF
  18911. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18912. // Keep reading
  18913. }
  18914. // Should get an error since content_length wasn't satisfied
  18915. if (n < 0) {
  18916. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18917. handle.get_read_error() == Error::Read)
  18918. << "Actual error: " << to_string(handle.get_read_error());
  18919. }
  18920. svr.stop();
  18921. t.join();
  18922. }
  18923. #ifdef CPPHTTPLIB_SSL_ENABLED
  18924. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18925. // Test that read timeout during SSL streaming is detected
  18926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18927. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18928. res.set_content_provider(
  18929. 1000, "text/plain",
  18930. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18931. if (offset < 100) {
  18932. std::string data(100, 'A');
  18933. sink.write(data.c_str(), data.size());
  18934. return true;
  18935. }
  18936. std::this_thread::sleep_for(std::chrono::seconds(3));
  18937. std::string data(900, 'B');
  18938. sink.write(data.c_str(), data.size());
  18939. return true;
  18940. });
  18941. });
  18942. auto port = 8093;
  18943. std::thread t([&]() { svr.listen("localhost", port); });
  18944. svr.wait_until_ready();
  18945. SSLClient cli("localhost", port);
  18946. cli.enable_server_certificate_verification(false);
  18947. cli.set_read_timeout(1, 0); // 1 second timeout
  18948. auto handle = cli.open_stream("GET", "/slow-stream");
  18949. ASSERT_TRUE(handle.is_valid());
  18950. char buf[256];
  18951. ssize_t total = 0;
  18952. ssize_t n;
  18953. bool got_error = false;
  18954. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18955. total += n;
  18956. }
  18957. if (n < 0) {
  18958. got_error = true;
  18959. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18960. handle.get_read_error() == Error::Read)
  18961. << "Actual error: " << to_string(handle.get_read_error());
  18962. }
  18963. EXPECT_TRUE(got_error || total < 1000)
  18964. << "Expected timeout but got all " << total << " bytes";
  18965. svr.stop();
  18966. t.join();
  18967. }
  18968. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18969. // Test SSL connection closed detection
  18970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18971. std::atomic<bool> close_now{false};
  18972. svr.Get("/will-close", [&](const Request &, Response &res) {
  18973. res.set_content_provider(
  18974. 10000, "text/plain",
  18975. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18976. if (offset < 100) {
  18977. std::string data(100, 'X');
  18978. sink.write(data.c_str(), data.size());
  18979. return true;
  18980. }
  18981. while (!close_now) {
  18982. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18983. }
  18984. return false;
  18985. });
  18986. });
  18987. auto port = 8094;
  18988. std::thread t([&]() { svr.listen("localhost", port); });
  18989. svr.wait_until_ready();
  18990. SSLClient cli("localhost", port);
  18991. cli.enable_server_certificate_verification(false);
  18992. auto handle = cli.open_stream("GET", "/will-close");
  18993. ASSERT_TRUE(handle.is_valid());
  18994. char buf[256];
  18995. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18996. EXPECT_GT(n, 0);
  18997. // Signal server to close
  18998. close_now = true;
  18999. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19000. // Keep reading
  19001. }
  19002. if (n < 0) {
  19003. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19004. handle.get_read_error() == Error::Read)
  19005. << "Actual error: " << to_string(handle.get_read_error());
  19006. }
  19007. svr.stop();
  19008. t.join();
  19009. }
  19010. #endif
  19011. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19012. using namespace httplib;
  19013. // Create a test file
  19014. const char *fname = "etag_testfile.txt";
  19015. const char *content = "etag-content";
  19016. {
  19017. std::ofstream ofs(fname);
  19018. ofs << content;
  19019. ASSERT_TRUE(ofs.good());
  19020. }
  19021. Server svr;
  19022. svr.set_mount_point("/static", ".");
  19023. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19024. svr.wait_until_ready();
  19025. Client cli(HOST, PORT);
  19026. // First request: should get 200 with ETag header
  19027. auto res1 = cli.Get("/static/etag_testfile.txt");
  19028. ASSERT_TRUE(res1);
  19029. ASSERT_EQ(200, res1->status);
  19030. ASSERT_TRUE(res1->has_header("ETag"));
  19031. std::string etag = res1->get_header_value("ETag");
  19032. EXPECT_FALSE(etag.empty());
  19033. // Verify ETag format: W/"hex-hex"
  19034. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19035. EXPECT_EQ('W', etag[0]);
  19036. EXPECT_EQ('/', etag[1]);
  19037. EXPECT_EQ('"', etag[2]);
  19038. EXPECT_EQ('"', etag.back());
  19039. // Exact match: expect 304 Not Modified
  19040. Headers h2 = {{"If-None-Match", etag}};
  19041. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19042. ASSERT_TRUE(res2);
  19043. EXPECT_EQ(304, res2->status);
  19044. // Wildcard match: expect 304 Not Modified
  19045. Headers h3 = {{"If-None-Match", "*"}};
  19046. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19047. ASSERT_TRUE(res3);
  19048. EXPECT_EQ(304, res3->status);
  19049. // Non-matching ETag: expect 200
  19050. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19051. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19052. ASSERT_TRUE(res4);
  19053. EXPECT_EQ(200, res4->status);
  19054. // Multiple ETags with one matching: expect 304
  19055. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19056. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19057. ASSERT_TRUE(res5);
  19058. EXPECT_EQ(304, res5->status);
  19059. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19060. // that equivalent to the single comma-separated list above, so the match on
  19061. // the second line must still be found.
  19062. Headers h6;
  19063. h6.emplace("If-None-Match", "W/\"other\"");
  19064. h6.emplace("If-None-Match", etag);
  19065. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19066. ASSERT_TRUE(res6);
  19067. EXPECT_EQ(304, res6->status);
  19068. svr.stop();
  19069. t.join();
  19070. std::remove(fname);
  19071. }
  19072. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19073. using namespace httplib;
  19074. Server svr;
  19075. svr.set_mount_point("/static", ".");
  19076. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19077. svr.wait_until_ready();
  19078. Client cli(HOST, PORT);
  19079. // Send If-None-Match: * to a non-existent file
  19080. Headers h = {{"If-None-Match", "*"}};
  19081. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19083. EXPECT_EQ(404, res->status);
  19084. svr.stop();
  19085. t.join();
  19086. }
  19087. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19088. using namespace httplib;
  19089. // Create a test file
  19090. const char *fname = "etag_boundary_testfile.txt";
  19091. const char *content = "boundary-test";
  19092. {
  19093. std::ofstream ofs(fname);
  19094. ofs << content;
  19095. ASSERT_TRUE(ofs.good());
  19096. }
  19097. Server svr;
  19098. svr.set_mount_point("/static", ".");
  19099. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19100. svr.wait_until_ready();
  19101. Client cli(HOST, PORT);
  19102. // Get the actual ETag
  19103. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19104. ASSERT_TRUE(res1);
  19105. ASSERT_EQ(200, res1->status);
  19106. ASSERT_TRUE(res1->has_header("ETag"));
  19107. std::string etag = res1->get_header_value("ETag");
  19108. // Test 1: Very long ETag value (longer than actual ETag)
  19109. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19110. Headers h1 = {{"If-None-Match", "W/"
  19111. "\"very-long-etag-value-that-is-much-longer-"
  19112. "than-the-actual-etag-value\""}};
  19113. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19114. ASSERT_TRUE(res2);
  19115. EXPECT_EQ(200, res2->status); // Should not match
  19116. // Test 2: Long string followed by wildcard
  19117. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19118. // string)
  19119. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19120. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19121. ASSERT_TRUE(res3);
  19122. EXPECT_EQ(304, res3->status); // Should match on "*"
  19123. // Test 3: Wildcard followed by long string
  19124. // Should match on "*" immediately and return 304
  19125. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19126. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19127. ASSERT_TRUE(res4);
  19128. EXPECT_EQ(304, res4->status); // Should match on "*"
  19129. // Test 4: Multiple long non-matching values
  19130. // Should NOT match and return 200 (test that all comparisons are safe)
  19131. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19132. "W/\"second-long-non-matching-value\", "
  19133. "W/\"third-long-non-matching-value\""}};
  19134. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19135. ASSERT_TRUE(res5);
  19136. EXPECT_EQ(200, res5->status); // Should not match
  19137. // Test 5: Single character that is not "*" (edge case)
  19138. Headers h5 = {{"If-None-Match", "X"}};
  19139. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19140. ASSERT_TRUE(res6);
  19141. EXPECT_EQ(200, res6->status); // Should not match
  19142. svr.stop();
  19143. t.join();
  19144. std::remove(fname);
  19145. }
  19146. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19147. using namespace httplib;
  19148. // Create a test file
  19149. const char *fname = "ims_testfile.txt";
  19150. const char *content = "if-modified-since-test";
  19151. {
  19152. std::ofstream ofs(fname);
  19153. ofs << content;
  19154. ASSERT_TRUE(ofs.good());
  19155. }
  19156. Server svr;
  19157. svr.set_mount_point("/static", ".");
  19158. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19159. svr.wait_until_ready();
  19160. Client cli(HOST, PORT);
  19161. // First request: should get 200 with Last-Modified header
  19162. auto res1 = cli.Get("/static/ims_testfile.txt");
  19163. ASSERT_TRUE(res1);
  19164. ASSERT_EQ(200, res1->status);
  19165. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19166. std::string last_modified = res1->get_header_value("Last-Modified");
  19167. EXPECT_FALSE(last_modified.empty());
  19168. // If-Modified-Since with same time: expect 304
  19169. Headers h2 = {{"If-Modified-Since", last_modified}};
  19170. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19171. ASSERT_TRUE(res2);
  19172. EXPECT_EQ(304, res2->status);
  19173. // If-Modified-Since with future time: expect 304
  19174. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19175. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19176. ASSERT_TRUE(res3);
  19177. EXPECT_EQ(304, res3->status);
  19178. // If-Modified-Since with past time: expect 200
  19179. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19180. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19181. ASSERT_TRUE(res4);
  19182. EXPECT_EQ(200, res4->status);
  19183. // If-None-Match takes precedence over If-Modified-Since
  19184. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19185. ASSERT_TRUE(res1->has_header("ETag"));
  19186. std::string etag = res1->get_header_value("ETag");
  19187. Headers h5 = {{"If-None-Match", etag},
  19188. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19189. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19190. ASSERT_TRUE(res5);
  19191. EXPECT_EQ(304, res5->status);
  19192. svr.stop();
  19193. t.join();
  19194. std::remove(fname);
  19195. }
  19196. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19197. using namespace httplib;
  19198. Server svr;
  19199. // Endpoint that returns compressible content
  19200. svr.Get("/compressible", [](const Request &, Response &res) {
  19201. // Return a large enough body to trigger compression
  19202. std::string body(1000, 'a');
  19203. res.set_content(body, "text/plain");
  19204. });
  19205. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19206. svr.wait_until_ready();
  19207. Client cli(HOST, PORT);
  19208. // Request with gzip support: should get Vary header when compressed
  19209. cli.set_compress(true);
  19210. auto res1 = cli.Get("/compressible");
  19211. ASSERT_TRUE(res1);
  19212. EXPECT_EQ(200, res1->status);
  19213. // If Content-Encoding is set, Vary should also be set
  19214. if (res1->has_header("Content-Encoding")) {
  19215. EXPECT_TRUE(res1->has_header("Vary"));
  19216. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19217. }
  19218. // Request without Accept-Encoding header: should not have compression
  19219. Headers h_no_compress;
  19220. auto res2 = cli.Get("/compressible", h_no_compress);
  19221. ASSERT_TRUE(res2);
  19222. EXPECT_EQ(200, res2->status);
  19223. // Verify Vary header is present when compression is applied
  19224. // (the exact behavior depends on server configuration)
  19225. svr.stop();
  19226. t.join();
  19227. }
  19228. TEST(ETagTest, IfRangeWithETag) {
  19229. using namespace httplib;
  19230. // Create a test file with known content
  19231. const char *fname = "if_range_testfile.txt";
  19232. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19233. {
  19234. std::ofstream ofs(fname);
  19235. ofs << content;
  19236. ASSERT_TRUE(ofs.good());
  19237. }
  19238. Server svr;
  19239. svr.set_mount_point("/static", ".");
  19240. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19241. svr.wait_until_ready();
  19242. Client cli(HOST, PORT);
  19243. // First request: get ETag
  19244. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19245. ASSERT_TRUE(res1);
  19246. ASSERT_EQ(200, res1->status);
  19247. ASSERT_TRUE(res1->has_header("ETag"));
  19248. std::string etag = res1->get_header_value("ETag");
  19249. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19250. // Since our server generates weak ETags (W/"..."), If-Range with our
  19251. // ETag should NOT result in partial content - it should return full content.
  19252. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19253. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19254. ASSERT_TRUE(res2);
  19255. // Weak ETag in If-Range -> full content (200), not partial (206)
  19256. EXPECT_EQ(200, res2->status);
  19257. EXPECT_EQ(content, res2->body);
  19258. EXPECT_FALSE(res2->has_header("Content-Range"));
  19259. // Range request with non-matching If-Range (ETag): should get 200 (full
  19260. // content)
  19261. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19262. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19263. ASSERT_TRUE(res3);
  19264. EXPECT_EQ(200, res3->status);
  19265. EXPECT_EQ(content, res3->body);
  19266. EXPECT_FALSE(res3->has_header("Content-Range"));
  19267. // Range request with strong ETag (hypothetical - our server doesn't generate
  19268. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19269. // should return full content)
  19270. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19271. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19272. ASSERT_TRUE(res4);
  19273. EXPECT_EQ(200, res4->status);
  19274. EXPECT_EQ(content, res4->body);
  19275. EXPECT_FALSE(res4->has_header("Content-Range"));
  19276. svr.stop();
  19277. t.join();
  19278. std::remove(fname);
  19279. }
  19280. TEST(ETagTest, IfRangeWithDate) {
  19281. using namespace httplib;
  19282. // Create a test file
  19283. const char *fname = "if_range_date_testfile.txt";
  19284. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19285. {
  19286. std::ofstream ofs(fname);
  19287. ofs << content;
  19288. ASSERT_TRUE(ofs.good());
  19289. }
  19290. Server svr;
  19291. svr.set_mount_point("/static", ".");
  19292. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19293. svr.wait_until_ready();
  19294. Client cli(HOST, PORT);
  19295. // First request: get Last-Modified
  19296. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19297. ASSERT_TRUE(res1);
  19298. ASSERT_EQ(200, res1->status);
  19299. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19300. std::string last_modified = res1->get_header_value("Last-Modified");
  19301. // Range request with matching If-Range (date): should get 206
  19302. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19303. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19304. ASSERT_TRUE(res2);
  19305. EXPECT_EQ(206, res2->status);
  19306. EXPECT_EQ("FGHIJ", res2->body);
  19307. // Range request with old If-Range date: should get 200 (full content)
  19308. Headers h3 = {{"Range", "bytes=5-9"},
  19309. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19310. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19311. ASSERT_TRUE(res3);
  19312. EXPECT_EQ(200, res3->status);
  19313. EXPECT_EQ(content, res3->body);
  19314. // Range request with future If-Range date: should get 206
  19315. Headers h4 = {{"Range", "bytes=0-4"},
  19316. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19317. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19318. ASSERT_TRUE(res4);
  19319. EXPECT_EQ(206, res4->status);
  19320. EXPECT_EQ("ABCDE", res4->body);
  19321. svr.stop();
  19322. t.join();
  19323. std::remove(fname);
  19324. }
  19325. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19326. using namespace httplib;
  19327. const char *fname = "etag_malformed.txt";
  19328. const char *content = "malformed-etag";
  19329. {
  19330. std::ofstream ofs(fname);
  19331. ofs << content;
  19332. ASSERT_TRUE(ofs.good());
  19333. }
  19334. Server svr;
  19335. svr.set_mount_point("/static", ".");
  19336. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19337. svr.wait_until_ready();
  19338. Client cli(HOST, PORT);
  19339. // baseline: should get 200 and an ETag
  19340. auto res1 = cli.Get("/static/etag_malformed.txt");
  19341. ASSERT_TRUE(res1);
  19342. ASSERT_EQ(200, res1->status);
  19343. ASSERT_TRUE(res1->has_header("ETag"));
  19344. // Malformed ETag value (missing quotes) should be treated as non-matching
  19345. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19346. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19347. ASSERT_TRUE(res_bad);
  19348. EXPECT_EQ(200, res_bad->status);
  19349. // Whitespace-only header value should be considered invalid / non-matching
  19350. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19351. "Host: localhost\r\n"
  19352. "If-None-Match: \r\n"
  19353. "Connection: close\r\n"
  19354. "\r\n";
  19355. std::string out;
  19356. ASSERT_TRUE(send_request(5, raw_req, &out));
  19357. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19358. svr.stop();
  19359. t.join();
  19360. std::remove(fname);
  19361. }
  19362. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19363. using namespace httplib;
  19364. const char *fname = "ims_invalid_format.txt";
  19365. const char *content = "ims-bad-format";
  19366. {
  19367. std::ofstream ofs(fname);
  19368. ofs << content;
  19369. ASSERT_TRUE(ofs.good());
  19370. }
  19371. Server svr;
  19372. svr.set_mount_point("/static", ".");
  19373. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19374. svr.wait_until_ready();
  19375. Client cli(HOST, PORT);
  19376. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19377. ASSERT_TRUE(res1);
  19378. ASSERT_EQ(200, res1->status);
  19379. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19380. // If-Modified-Since with invalid format should not result in 304
  19381. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19382. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19383. ASSERT_TRUE(res_bad);
  19384. EXPECT_EQ(200, res_bad->status);
  19385. // If-Range with invalid date format should be treated as mismatch -> full
  19386. // content (200)
  19387. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19388. {"If-Range", "invalid-date"}};
  19389. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19390. ASSERT_TRUE(res_ifrange);
  19391. EXPECT_EQ(200, res_ifrange->status);
  19392. svr.stop();
  19393. t.join();
  19394. std::remove(fname);
  19395. }
  19396. TEST(ETagTest, IfRangeWithMalformedETag) {
  19397. using namespace httplib;
  19398. const char *fname = "ifrange_malformed.txt";
  19399. const std::string content = "0123456789";
  19400. {
  19401. std::ofstream ofs(fname);
  19402. ofs << content;
  19403. ASSERT_TRUE(ofs.good());
  19404. }
  19405. Server svr;
  19406. svr.set_mount_point("/static", ".");
  19407. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19408. svr.wait_until_ready();
  19409. Client cli(HOST, PORT);
  19410. // First request: get ETag
  19411. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19412. ASSERT_TRUE(res1);
  19413. ASSERT_EQ(200, res1->status);
  19414. ASSERT_TRUE(res1->has_header("ETag"));
  19415. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19416. // full content (200)
  19417. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19418. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19419. ASSERT_TRUE(res2);
  19420. EXPECT_EQ(200, res2->status);
  19421. EXPECT_EQ(content, res2->body);
  19422. svr.stop();
  19423. t.join();
  19424. std::remove(fname);
  19425. }
  19426. TEST(ETagTest, ExtremeLargeDateValues) {
  19427. using namespace httplib;
  19428. const char *fname = "ims_extreme_date.txt";
  19429. const char *content = "ims-extreme-date";
  19430. {
  19431. std::ofstream ofs(fname);
  19432. ofs << content;
  19433. ASSERT_TRUE(ofs.good());
  19434. }
  19435. Server svr;
  19436. svr.set_mount_point("/static", ".");
  19437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19438. svr.wait_until_ready();
  19439. Client cli(HOST, PORT);
  19440. auto res1 = cli.Get(std::string("/static/") + fname);
  19441. ASSERT_TRUE(res1);
  19442. ASSERT_EQ(200, res1->status);
  19443. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19444. // Extremely large year that may overflow date parsing routines.
  19445. Headers h_large_date = {
  19446. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19447. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19448. ASSERT_TRUE(res_bad);
  19449. // Expect server to treat this as invalid/mismatch and return full content
  19450. EXPECT_EQ(200, res_bad->status);
  19451. // If-Range with extremely large date should be treated as mismatch -> full
  19452. // content (200)
  19453. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19454. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19455. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19456. ASSERT_TRUE(res_ifrange);
  19457. EXPECT_EQ(200, res_ifrange->status);
  19458. svr.stop();
  19459. t.join();
  19460. std::remove(fname);
  19461. }
  19462. TEST(ETagTest, NegativeFileModificationTime) {
  19463. using namespace httplib;
  19464. const char *fname = "ims_negative_mtime.txt";
  19465. const std::string content = "negative-mtime";
  19466. {
  19467. std::ofstream ofs(fname);
  19468. ofs << content;
  19469. ASSERT_TRUE(ofs.good());
  19470. }
  19471. // Try to set file mtime to a negative value. This may fail on some
  19472. // platforms/filesystems; if it fails, the test will still verify server
  19473. // behaves safely by performing a regular conditional request.
  19474. #if defined(__APPLE__) || defined(__linux__)
  19475. bool set_negative = false;
  19476. do {
  19477. struct timeval times[2];
  19478. // access time: now
  19479. times[0].tv_sec = time(nullptr);
  19480. times[0].tv_usec = 0;
  19481. // modification time: negative (e.g., -1)
  19482. times[1].tv_sec = -1;
  19483. times[1].tv_usec = 0;
  19484. if (utimes(fname, times) == 0) { set_negative = true; }
  19485. } while (0);
  19486. #else
  19487. bool set_negative = false;
  19488. #endif
  19489. Server svr;
  19490. svr.set_mount_point("/static", ".");
  19491. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19492. svr.wait_until_ready();
  19493. Client cli(HOST, PORT);
  19494. auto res1 = cli.Get(std::string("/static/") + fname);
  19495. ASSERT_TRUE(res1);
  19496. ASSERT_EQ(200, res1->status);
  19497. bool has_last_modified = res1->has_header("Last-Modified");
  19498. std::string last_modified;
  19499. if (has_last_modified) {
  19500. last_modified = res1->get_header_value("Last-Modified");
  19501. }
  19502. if (set_negative) {
  19503. // If we successfully set a negative mtime, ensure server returns a
  19504. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19505. // with an old date and ensure server handles it without crash.
  19506. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19507. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19508. ASSERT_TRUE(res2);
  19509. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19510. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19511. } else {
  19512. // Could not set negative mtime on this platform; fall back to verifying
  19513. // that normal invalid/malformed dates are treated safely (non-304).
  19514. Headers h_bad_date = {
  19515. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19516. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19517. ASSERT_TRUE(res_bad);
  19518. EXPECT_EQ(200, res_bad->status);
  19519. }
  19520. svr.stop();
  19521. t.join();
  19522. std::remove(fname);
  19523. }
  19524. //==============================================================================
  19525. // Integration Tests with Server
  19526. //==============================================================================
  19527. class SSEIntegrationTest : public ::testing::Test {
  19528. protected:
  19529. void SetUp() override {
  19530. stop_server_.store(false);
  19531. events_.clear();
  19532. server_ = httplib::detail::make_unique<Server>();
  19533. setup_server();
  19534. start_server();
  19535. }
  19536. void TearDown() override {
  19537. stop_server_.store(true);
  19538. event_cv_.notify_all();
  19539. server_->stop();
  19540. if (server_thread_.joinable()) { server_thread_.join(); }
  19541. }
  19542. void setup_server() {
  19543. // Simple SSE endpoint
  19544. server_->Get("/events", [this](const Request &req, Response &res) {
  19545. auto last_id = req.get_header_value("Last-Event-ID");
  19546. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19547. res.set_chunked_content_provider(
  19548. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19549. std::unique_lock<std::mutex> lock(event_mutex_);
  19550. if (event_cv_.wait_for(
  19551. lock, std::chrono::milliseconds(200), [this] {
  19552. return !events_.empty() || stop_server_.load();
  19553. })) {
  19554. if (stop_server_.load()) { return false; }
  19555. if (!events_.empty()) {
  19556. std::string event = events_.front();
  19557. events_.erase(events_.begin());
  19558. sink.write(event.data(), event.size());
  19559. return true;
  19560. }
  19561. }
  19562. return !stop_server_.load();
  19563. });
  19564. });
  19565. // Endpoint that returns error
  19566. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19567. res.status = 500;
  19568. res.set_content("Internal Server Error", "text/plain");
  19569. });
  19570. // Endpoint for custom event types
  19571. server_->Get("/custom-events", [](const Request &, Response &res) {
  19572. res.set_chunked_content_provider(
  19573. "text/event-stream", [](size_t offset, DataSink &sink) {
  19574. if (offset == 0) {
  19575. std::string event = "event: update\ndata: updated\n\n"
  19576. "event: delete\ndata: deleted\n\n";
  19577. sink.write(event.data(), event.size());
  19578. }
  19579. return false; // End stream after sending
  19580. });
  19581. });
  19582. }
  19583. void start_server() {
  19584. port_ = server_->bind_to_any_port(HOST);
  19585. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19586. // Wait for server to start
  19587. while (!server_->is_running()) {
  19588. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19589. }
  19590. }
  19591. int get_port() const { return port_; }
  19592. void send_event(const std::string &event) {
  19593. std::lock_guard<std::mutex> lock(event_mutex_);
  19594. events_.push_back(event);
  19595. event_cv_.notify_all();
  19596. }
  19597. std::unique_ptr<Server> server_;
  19598. std::thread server_thread_;
  19599. std::mutex event_mutex_;
  19600. std::condition_variable event_cv_;
  19601. std::vector<std::string> events_;
  19602. std::atomic<bool> stop_server_{false};
  19603. std::string last_received_event_id_;
  19604. int port_ = 0;
  19605. };
  19606. //==============================================================================
  19607. // SSE Parsing Tests
  19608. //==============================================================================
  19609. class SSEParsingTest : public SSEIntegrationTest {
  19610. protected:
  19611. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19612. // A trailing sentinel event tells when the whole stream has been parsed.
  19613. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19614. auto body = stream + "event: end\ndata: end\n\n";
  19615. server_->Get("/parse", [body](const Request &, Response &res) {
  19616. res.set_content(body, "text/event-stream");
  19617. });
  19618. return collect("/parse");
  19619. }
  19620. // Runs SSEClient against path until an "end" event arrives and returns the
  19621. // messages dispatched before it
  19622. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19623. Client client(HOST, get_port());
  19624. sse::SSEClient sse(client, path);
  19625. std::mutex mutex;
  19626. std::condition_variable cv;
  19627. std::vector<sse::SSEMessage> messages;
  19628. auto done = false;
  19629. sse.on_message([&](const sse::SSEMessage &msg) {
  19630. std::lock_guard<std::mutex> lock(mutex);
  19631. // Ignore a replay from a reconnect that races with stop()
  19632. if (!done) { messages.push_back(msg); }
  19633. });
  19634. sse.on_event("end", [&](const sse::SSEMessage &) {
  19635. std::lock_guard<std::mutex> lock(mutex);
  19636. done = true;
  19637. cv.notify_all();
  19638. });
  19639. sse.set_reconnect_interval(100);
  19640. sse.start_async();
  19641. {
  19642. std::unique_lock<std::mutex> lock(mutex);
  19643. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19644. }
  19645. sse.stop();
  19646. EXPECT_TRUE(done);
  19647. return messages;
  19648. }
  19649. };
  19650. TEST_F(SSEParsingTest, SingleLineData) {
  19651. auto msgs = parse("data: hello\n\n");
  19652. ASSERT_EQ(msgs.size(), 1u);
  19653. EXPECT_EQ(msgs[0].data, "hello");
  19654. EXPECT_EQ(msgs[0].event, "message");
  19655. }
  19656. TEST_F(SSEParsingTest, MultiLineData) {
  19657. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19658. ASSERT_EQ(msgs.size(), 1u);
  19659. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19660. }
  19661. TEST_F(SSEParsingTest, CustomEventType) {
  19662. auto msgs = parse("event: update\ndata: payload\n\n");
  19663. ASSERT_EQ(msgs.size(), 1u);
  19664. EXPECT_EQ(msgs[0].event, "update");
  19665. EXPECT_EQ(msgs[0].data, "payload");
  19666. }
  19667. TEST_F(SSEParsingTest, EventIdHandling) {
  19668. auto msgs = parse("id: 12345\ndata: test\n\n");
  19669. ASSERT_EQ(msgs.size(), 1u);
  19670. EXPECT_EQ(msgs[0].id, "12345");
  19671. }
  19672. TEST_F(SSEParsingTest, EmptyEventId) {
  19673. auto msgs = parse("id:\ndata: test\n\n");
  19674. ASSERT_EQ(msgs.size(), 1u);
  19675. EXPECT_EQ(msgs[0].id, "");
  19676. }
  19677. TEST_F(SSEParsingTest, CommentsIgnored) {
  19678. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19679. ASSERT_EQ(msgs.size(), 1u);
  19680. EXPECT_EQ(msgs[0].data, "hello");
  19681. EXPECT_EQ(msgs[0].event, "message");
  19682. }
  19683. TEST_F(SSEParsingTest, ColonInValue) {
  19684. auto msgs = parse("data: hello:world:test\n\n");
  19685. ASSERT_EQ(msgs.size(), 1u);
  19686. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19687. }
  19688. TEST_F(SSEParsingTest, FieldNameOnly) {
  19689. // A line without a colon is a field name with an empty value
  19690. auto msgs = parse("data\n\n");
  19691. ASSERT_EQ(msgs.size(), 1u);
  19692. EXPECT_EQ(msgs[0].data, "");
  19693. }
  19694. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19695. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19696. ASSERT_EQ(msgs.size(), 1u);
  19697. EXPECT_EQ(msgs[0].event, "update");
  19698. EXPECT_EQ(msgs[0].data, "hello");
  19699. }
  19700. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19701. auto msgs = parse("data\r\n\r\n");
  19702. ASSERT_EQ(msgs.size(), 1u);
  19703. EXPECT_EQ(msgs[0].data, "");
  19704. }
  19705. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19706. auto msgs = parse("event: update\rdata: hello\r\r");
  19707. ASSERT_EQ(msgs.size(), 1u);
  19708. EXPECT_EQ(msgs[0].event, "update");
  19709. EXPECT_EQ(msgs[0].data, "hello");
  19710. }
  19711. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19712. // Chunk boundaries fall inside every \r\n and right before the first one
  19713. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19714. "\n\r", "\nevent: end\ndata: end\n\n"};
  19715. server_->Get("/split", [chunks](const Request &, Response &res) {
  19716. auto i = std::make_shared<size_t>(0);
  19717. res.set_chunked_content_provider(
  19718. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19719. if (*i == chunks.size()) {
  19720. sink.done();
  19721. } else {
  19722. sink.write(chunks[*i].data(), chunks[*i].size());
  19723. (*i)++;
  19724. }
  19725. return true;
  19726. });
  19727. });
  19728. auto msgs = collect("/split");
  19729. ASSERT_EQ(msgs.size(), 1u);
  19730. EXPECT_EQ(msgs[0].event, "update");
  19731. EXPECT_EQ(msgs[0].data, "hello");
  19732. }
  19733. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19734. // Only a BOM at the start of the stream is ignored
  19735. auto msgs = parse("\xEF\xBB\xBF"
  19736. "data: first\n\n"
  19737. "\xEF\xBB\xBF"
  19738. "data: second\n\n");
  19739. ASSERT_EQ(msgs.size(), 1u);
  19740. EXPECT_EQ(msgs[0].data, "first");
  19741. }
  19742. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19743. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19744. ASSERT_EQ(msgs.size(), 1u);
  19745. EXPECT_EQ(msgs[0].data, "hello");
  19746. EXPECT_EQ(msgs[0].event, "message");
  19747. }
  19748. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19749. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19750. ASSERT_EQ(msgs.size(), 2u);
  19751. EXPECT_EQ(msgs[0].data, "hello");
  19752. EXPECT_EQ(msgs[1].data, "hello");
  19753. }
  19754. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19755. // An event without data is not dispatched, and its type must not leak
  19756. // into the next event
  19757. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19758. ASSERT_EQ(msgs.size(), 1u);
  19759. EXPECT_EQ(msgs[0].event, "message");
  19760. EXPECT_EQ(msgs[0].data, "hello");
  19761. }
  19762. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19763. // The first connection sends only an id; the second echoes back the
  19764. // Last-Event-ID it was reconnected with
  19765. std::atomic<int> connection_count{0};
  19766. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19767. if (connection_count++ == 0) {
  19768. res.set_content("id: 42\n\n", "text/event-stream");
  19769. } else {
  19770. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19771. "\n\nevent: end\ndata: end\n\n",
  19772. "text/event-stream");
  19773. }
  19774. });
  19775. auto msgs = collect("/id-only");
  19776. ASSERT_EQ(msgs.size(), 1u);
  19777. EXPECT_EQ(msgs[0].data, "42");
  19778. }
  19779. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19780. // The first connection sets an id and then clears it with an empty one; the
  19781. // second reports whether it was reconnected with a Last-Event-ID
  19782. std::atomic<int> connection_count{0};
  19783. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19784. if (connection_count++ == 0) {
  19785. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19786. "text/event-stream");
  19787. } else {
  19788. res.set_content(
  19789. std::string("data: ") +
  19790. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19791. "\n\nevent: end\ndata: end\n\n",
  19792. "text/event-stream");
  19793. }
  19794. });
  19795. auto msgs = collect("/id-clear");
  19796. ASSERT_EQ(msgs.size(), 3u);
  19797. EXPECT_EQ(msgs[0].id, "1");
  19798. EXPECT_EQ(msgs[1].id, "");
  19799. EXPECT_EQ(msgs[2].data, "not sent");
  19800. }
  19801. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19802. // The first connection sets an id and then sends ids that cannot be carried
  19803. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19804. // with
  19805. std::atomic<int> connection_count{0};
  19806. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19807. if (connection_count++ == 0) {
  19808. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19809. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19810. "text/event-stream");
  19811. } else {
  19812. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19813. "\n\nevent: end\ndata: end\n\n",
  19814. "text/event-stream");
  19815. }
  19816. });
  19817. auto msgs = collect("/id-unsendable");
  19818. ASSERT_EQ(msgs.size(), 1u);
  19819. EXPECT_EQ(msgs[0].data, "42");
  19820. }
  19821. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19822. auto msgs = parse("event: notification\nid: evt-42\n"
  19823. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19824. ASSERT_EQ(msgs.size(), 1u);
  19825. EXPECT_EQ(msgs[0].event, "notification");
  19826. EXPECT_EQ(msgs[0].id, "evt-42");
  19827. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19828. }
  19829. TEST(SSEMessageTest, Clear) {
  19830. sse::SSEMessage msg;
  19831. msg.event = "custom";
  19832. msg.data = "some data";
  19833. msg.id = "123";
  19834. msg.clear();
  19835. EXPECT_EQ(msg.event, "message");
  19836. EXPECT_EQ(msg.data, "");
  19837. EXPECT_EQ(msg.id, "");
  19838. }
  19839. //==============================================================================
  19840. // SSE Integration Tests
  19841. //==============================================================================
  19842. // Test: Successful connection and on_open callback
  19843. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19844. // Add a simple endpoint that sends one event and closes
  19845. server_->Get("/simple-event", [](const Request &, Response &res) {
  19846. res.set_chunked_content_provider(
  19847. "text/event-stream", [](size_t offset, DataSink &sink) {
  19848. if (offset == 0) {
  19849. std::string event = "data: hello\n\n";
  19850. sink.write(event.data(), event.size());
  19851. }
  19852. return false; // Close stream after sending
  19853. });
  19854. });
  19855. Client client("localhost", get_port());
  19856. sse::SSEClient sse(client, "/simple-event");
  19857. std::atomic<bool> open_called{false};
  19858. std::atomic<bool> message_received{false};
  19859. sse.on_open([&open_called]() { open_called.store(true); });
  19860. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19861. if (msg.data == "hello") { message_received.store(true); }
  19862. });
  19863. sse.set_reconnect_interval(100);
  19864. sse.set_max_reconnect_attempts(1);
  19865. // Start async
  19866. sse.start_async();
  19867. // Wait for message to be processed
  19868. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19869. sse.stop();
  19870. EXPECT_TRUE(open_called.load());
  19871. EXPECT_TRUE(message_received.load());
  19872. }
  19873. // Test: on_message callback
  19874. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19875. // Endpoint that sends multiple events then closes
  19876. server_->Get("/multi-event", [](const Request &, Response &res) {
  19877. res.set_chunked_content_provider(
  19878. "text/event-stream", [](size_t offset, DataSink &sink) {
  19879. if (offset == 0) {
  19880. std::string events = "data: message1\n\ndata: message2\n\n";
  19881. sink.write(events.data(), events.size());
  19882. }
  19883. return false;
  19884. });
  19885. });
  19886. Client client("localhost", get_port());
  19887. sse::SSEClient sse(client, "/multi-event");
  19888. std::vector<std::string> received_messages;
  19889. std::mutex messages_mutex;
  19890. sse.on_message([&](const sse::SSEMessage &msg) {
  19891. std::lock_guard<std::mutex> lock(messages_mutex);
  19892. received_messages.push_back(msg.data);
  19893. });
  19894. sse.set_reconnect_interval(100);
  19895. sse.set_max_reconnect_attempts(1);
  19896. sse.start_async();
  19897. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19898. sse.stop();
  19899. std::lock_guard<std::mutex> lock(messages_mutex);
  19900. EXPECT_GE(received_messages.size(), 2u);
  19901. if (received_messages.size() >= 2) {
  19902. EXPECT_EQ(received_messages[0], "message1");
  19903. EXPECT_EQ(received_messages[1], "message2");
  19904. }
  19905. }
  19906. // Test: on_event for specific types
  19907. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19908. Client client("localhost", get_port());
  19909. sse::SSEClient sse(client, "/custom-events");
  19910. std::atomic<bool> update_received{false};
  19911. std::atomic<bool> delete_received{false};
  19912. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19913. if (msg.data == "updated") { update_received.store(true); }
  19914. });
  19915. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19916. if (msg.data == "deleted") { delete_received.store(true); }
  19917. });
  19918. sse.set_max_reconnect_attempts(1);
  19919. sse.start_async();
  19920. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19921. sse.stop();
  19922. EXPECT_TRUE(update_received.load());
  19923. EXPECT_TRUE(delete_received.load());
  19924. }
  19925. // Test: on_error callback on connection failure
  19926. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19927. // Connect to a non-existent port
  19928. Client client("localhost", 59999);
  19929. sse::SSEClient sse(client, "/events");
  19930. std::atomic<bool> error_called{false};
  19931. Error received_error = Error::Success;
  19932. sse.on_error([&](Error err) {
  19933. error_called.store(true);
  19934. received_error = err;
  19935. });
  19936. sse.set_reconnect_interval(50);
  19937. sse.set_max_reconnect_attempts(1);
  19938. sse.start_async();
  19939. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19940. sse.stop();
  19941. EXPECT_TRUE(error_called.load());
  19942. EXPECT_NE(received_error, Error::Success);
  19943. }
  19944. // Test: Last-Event-ID header sent on reconnect
  19945. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19946. // Endpoint that sends event with ID
  19947. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19948. res.set_chunked_content_provider(
  19949. "text/event-stream", [](size_t offset, DataSink &sink) {
  19950. if (offset == 0) {
  19951. std::string event = "id: evt-123\ndata: test\n\n";
  19952. sink.write(event.data(), event.size());
  19953. }
  19954. return false;
  19955. });
  19956. });
  19957. Client client("localhost", get_port());
  19958. sse::SSEClient sse(client, "/event-with-id");
  19959. std::atomic<bool> id_received{false};
  19960. sse.on_message([&](const sse::SSEMessage &msg) {
  19961. if (!msg.id.empty()) { id_received.store(true); }
  19962. });
  19963. sse.set_reconnect_interval(100);
  19964. sse.set_max_reconnect_attempts(1);
  19965. sse.start_async();
  19966. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19967. sse.stop();
  19968. EXPECT_TRUE(id_received.load());
  19969. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19970. }
  19971. // Test: Manual stop
  19972. TEST_F(SSEIntegrationTest, ManualStop) {
  19973. // Endpoint that sends one event and stays open briefly
  19974. std::atomic<bool> handler_running{true};
  19975. server_->Get("/stay-open", [&handler_running](const Request &,
  19976. Response &res) {
  19977. res.set_chunked_content_provider(
  19978. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19979. if (offset == 0) {
  19980. std::string event = "data: connected\n\n";
  19981. sink.write(event.data(), event.size());
  19982. }
  19983. // Keep connection open while handler_running is true
  19984. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19985. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19986. }
  19987. return false;
  19988. });
  19989. });
  19990. Client client("localhost", get_port());
  19991. sse::SSEClient sse(client, "/stay-open");
  19992. std::atomic<bool> connected{false};
  19993. sse.on_open([&connected]() { connected.store(true); });
  19994. sse.set_reconnect_interval(100);
  19995. sse.set_max_reconnect_attempts(1);
  19996. sse.start_async();
  19997. // Wait for connection to establish
  19998. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19999. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20000. }
  20001. EXPECT_TRUE(connected.load());
  20002. EXPECT_TRUE(sse.is_connected());
  20003. // Signal handler to stop
  20004. handler_running.store(false);
  20005. // Stop SSE client
  20006. sse.stop();
  20007. EXPECT_FALSE(sse.is_connected());
  20008. }
  20009. // Test: SSEClient with custom headers
  20010. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20011. // Setup a server endpoint that checks for custom header
  20012. std::atomic<bool> header_received{false};
  20013. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20014. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20015. header_received.store(true);
  20016. }
  20017. res.set_chunked_content_provider("text/event-stream",
  20018. [](size_t, DataSink &) { return false; });
  20019. });
  20020. Client client("localhost", get_port());
  20021. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20022. sse::SSEClient sse(client, "/header-check", headers);
  20023. sse.set_max_reconnect_attempts(1);
  20024. sse.start_async();
  20025. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20026. sse.stop();
  20027. EXPECT_TRUE(header_received.load());
  20028. }
  20029. // Test: Reconnect interval configuration
  20030. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20031. Client client("localhost", get_port());
  20032. sse::SSEClient sse(client, "/events");
  20033. auto &result = sse.set_reconnect_interval(500);
  20034. // Builder pattern should return reference to self
  20035. EXPECT_EQ(&result, &sse);
  20036. }
  20037. // Test: Max reconnect attempts
  20038. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20039. // Connect to non-existent port to force reconnects
  20040. Client client("localhost", 59998);
  20041. sse::SSEClient sse(client, "/events");
  20042. std::atomic<int> error_count{0};
  20043. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20044. sse.set_reconnect_interval(50);
  20045. sse.set_max_reconnect_attempts(2);
  20046. auto start = std::chrono::steady_clock::now();
  20047. sse.start(); // Blocking call
  20048. auto end = std::chrono::steady_clock::now();
  20049. // Should have stopped after 2 failed attempts
  20050. EXPECT_GE(error_count.load(), 2);
  20051. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20052. auto duration =
  20053. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20054. #ifdef _WIN32
  20055. // Windows is much slower for socket connection failures
  20056. EXPECT_LT(duration.count(), 7000);
  20057. #else
  20058. EXPECT_LT(duration.count(), 1000);
  20059. #endif
  20060. }
  20061. // Test: Multi-line data in integration
  20062. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20063. // Endpoint with multi-line data
  20064. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20065. res.set_chunked_content_provider(
  20066. "text/event-stream", [](size_t offset, DataSink &sink) {
  20067. if (offset == 0) {
  20068. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20069. sink.write(event.data(), event.size());
  20070. }
  20071. return false;
  20072. });
  20073. });
  20074. Client client("localhost", get_port());
  20075. sse::SSEClient sse(client, "/multiline-data");
  20076. std::string received_data;
  20077. std::mutex data_mutex;
  20078. sse.on_message([&](const sse::SSEMessage &msg) {
  20079. std::lock_guard<std::mutex> lock(data_mutex);
  20080. received_data = msg.data;
  20081. });
  20082. sse.set_reconnect_interval(100);
  20083. sse.set_max_reconnect_attempts(1);
  20084. sse.start_async();
  20085. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20086. sse.stop();
  20087. std::lock_guard<std::mutex> lock(data_mutex);
  20088. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20089. }
  20090. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20091. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20092. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20093. DataSink &sink) {
  20094. if (offset == 0) {
  20095. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20096. sink.write(events.data(), events.size());
  20097. }
  20098. return false;
  20099. });
  20100. });
  20101. Client client("localhost", get_port());
  20102. sse::SSEClient sse(client, "/empty-data-lines");
  20103. std::mutex mutex;
  20104. std::condition_variable cv;
  20105. std::vector<std::string> received;
  20106. sse.on_message([&](const sse::SSEMessage &msg) {
  20107. std::lock_guard<std::mutex> lock(mutex);
  20108. received.push_back(msg.data);
  20109. cv.notify_all();
  20110. });
  20111. sse.set_max_reconnect_attempts(1);
  20112. sse.start_async();
  20113. {
  20114. std::unique_lock<std::mutex> lock(mutex);
  20115. cv.wait_for(lock, std::chrono::seconds(2),
  20116. [&] { return received.size() >= 3; });
  20117. }
  20118. sse.stop();
  20119. ASSERT_GE(received.size(), 3u);
  20120. EXPECT_EQ(received[0], "");
  20121. EXPECT_EQ(received[1], "\nhello");
  20122. EXPECT_EQ(received[2], "");
  20123. }
  20124. // Test: Auto-reconnect after server disconnection
  20125. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20126. std::atomic<int> connection_count{0};
  20127. std::atomic<int> message_count{0};
  20128. // Endpoint that sends one event and closes, forcing reconnect
  20129. server_->Get("/reconnect-test",
  20130. [&connection_count](const Request &, Response &res) {
  20131. connection_count.fetch_add(1);
  20132. res.set_chunked_content_provider(
  20133. "text/event-stream", [](size_t offset, DataSink &sink) {
  20134. if (offset == 0) {
  20135. std::string event = "data: hello\n\n";
  20136. sink.write(event.data(), event.size());
  20137. }
  20138. return false; // Close connection after sending
  20139. });
  20140. });
  20141. Client client("localhost", get_port());
  20142. sse::SSEClient sse(client, "/reconnect-test");
  20143. sse.on_message([&message_count](const sse::SSEMessage &) {
  20144. message_count.fetch_add(1);
  20145. });
  20146. sse.set_reconnect_interval(100);
  20147. sse.set_max_reconnect_attempts(3);
  20148. sse.start_async();
  20149. // Wait long enough for multiple reconnects
  20150. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20151. sse.stop();
  20152. // Should have connected multiple times (initial + reconnects)
  20153. EXPECT_GE(connection_count.load(), 2);
  20154. // Should have received messages from multiple connections
  20155. EXPECT_GE(message_count.load(), 2);
  20156. }
  20157. // Test: A retry field that is not all ASCII digits is ignored
  20158. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20159. std::atomic<int> connection_count{0};
  20160. server_->Get("/bad-retry",
  20161. [&connection_count](const Request &, Response &res) {
  20162. connection_count.fetch_add(1);
  20163. res.set_chunked_content_provider(
  20164. "text/event-stream", [](size_t offset, DataSink &sink) {
  20165. if (offset == 0) {
  20166. std::string event = "retry: -1\ndata: hello\n\n";
  20167. sink.write(event.data(), event.size());
  20168. }
  20169. return false;
  20170. });
  20171. });
  20172. Client client("localhost", get_port());
  20173. sse::SSEClient sse(client, "/bad-retry");
  20174. sse.set_reconnect_interval(10000);
  20175. sse.start_async();
  20176. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20177. sse.stop();
  20178. EXPECT_EQ(connection_count.load(), 1);
  20179. }
  20180. // Test: A retry field of all ASCII digits sets the reconnection time
  20181. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20182. std::mutex mutex;
  20183. std::condition_variable cv;
  20184. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20185. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20186. {
  20187. std::lock_guard<std::mutex> lock(mutex);
  20188. connected_at.push_back(std::chrono::steady_clock::now());
  20189. cv.notify_all();
  20190. }
  20191. res.set_chunked_content_provider(
  20192. "text/event-stream", [](size_t offset, DataSink &sink) {
  20193. if (offset == 0) {
  20194. std::string event = "retry: 0\ndata: hello\n\n";
  20195. sink.write(event.data(), event.size());
  20196. }
  20197. return false;
  20198. });
  20199. });
  20200. Client client("localhost", get_port());
  20201. sse::SSEClient sse(client, "/zero-retry");
  20202. sse.set_reconnect_interval(10000);
  20203. sse.start_async();
  20204. {
  20205. std::unique_lock<std::mutex> lock(mutex);
  20206. cv.wait_for(lock, std::chrono::seconds(5),
  20207. [&] { return connected_at.size() >= 2; });
  20208. }
  20209. sse.stop();
  20210. // The server-supplied interval is applied, but never below 100ms, so
  20211. // "retry: 0" does not cause a busy reconnect loop
  20212. std::lock_guard<std::mutex> lock(mutex);
  20213. ASSERT_GE(connected_at.size(), 2u);
  20214. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20215. connected_at[1] - connected_at[0])
  20216. .count();
  20217. EXPECT_GE(interval_ms, 100);
  20218. }
  20219. // Test: Last-Event-ID sent on reconnect
  20220. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20221. std::atomic<int> connection_count{0};
  20222. std::vector<std::string> received_last_event_ids;
  20223. std::mutex id_mutex;
  20224. // Endpoint that checks Last-Event-ID header and sends event with ID
  20225. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20226. int conn = connection_count.fetch_add(1);
  20227. // Capture the Last-Event-ID header from each connection
  20228. {
  20229. std::lock_guard<std::mutex> lock(id_mutex);
  20230. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20231. }
  20232. res.set_chunked_content_provider(
  20233. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20234. if (offset == 0) {
  20235. std::string event =
  20236. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20237. sink.write(event.data(), event.size());
  20238. }
  20239. return false;
  20240. });
  20241. });
  20242. Client client("localhost", get_port());
  20243. sse::SSEClient sse(client, "/reconnect-with-id");
  20244. sse.set_reconnect_interval(100);
  20245. sse.set_max_reconnect_attempts(3);
  20246. sse.start_async();
  20247. // Wait for at least 2 connections
  20248. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20249. sse.stop();
  20250. // Verify behavior
  20251. std::lock_guard<std::mutex> lock(id_mutex);
  20252. EXPECT_GE(received_last_event_ids.size(), 2u);
  20253. // First connection should have no Last-Event-ID
  20254. if (!received_last_event_ids.empty()) {
  20255. EXPECT_EQ(received_last_event_ids[0], "");
  20256. }
  20257. // Second connection should have Last-Event-ID from first connection
  20258. if (received_last_event_ids.size() >= 2) {
  20259. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20260. }
  20261. }
  20262. // Test: set_headers updates headers used on reconnect
  20263. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20264. std::vector<std::string> received_tokens;
  20265. std::mutex token_mutex;
  20266. // Endpoint that captures Authorization header
  20267. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20268. {
  20269. std::lock_guard<std::mutex> lock(token_mutex);
  20270. received_tokens.push_back(req.get_header_value("Authorization"));
  20271. }
  20272. res.set_chunked_content_provider(
  20273. "text/event-stream", [](size_t offset, DataSink &sink) {
  20274. if (offset == 0) {
  20275. std::string event = "data: hello\n\n";
  20276. sink.write(event.data(), event.size());
  20277. }
  20278. return false; // Close connection to trigger reconnect
  20279. });
  20280. });
  20281. Client client("localhost", get_port());
  20282. Headers headers = {{"Authorization", "Bearer old-token"}};
  20283. sse::SSEClient sse(client, "/auth-check", headers);
  20284. // Update headers on each successful connection
  20285. sse.on_open(
  20286. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20287. sse.set_reconnect_interval(100);
  20288. sse.set_max_reconnect_attempts(3);
  20289. sse.start_async();
  20290. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20291. sse.stop();
  20292. std::lock_guard<std::mutex> lock(token_mutex);
  20293. ASSERT_GE(received_tokens.size(), 2u);
  20294. // First connection uses original header
  20295. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20296. // Second connection uses updated header from set_headers
  20297. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20298. }
  20299. // Test: 401 allows reconnection (so on_error can refresh headers)
  20300. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20301. std::atomic<int> connection_count{0};
  20302. // Endpoint: returns 401 on first attempt, 200 on second
  20303. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20304. int conn = connection_count.fetch_add(1);
  20305. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20306. res.status = StatusCode::Unauthorized_401;
  20307. res.set_content("Unauthorized", "text/plain");
  20308. return;
  20309. }
  20310. res.set_chunked_content_provider(
  20311. "text/event-stream", [](size_t offset, DataSink &sink) {
  20312. if (offset == 0) {
  20313. std::string event = "data: authenticated\n\n";
  20314. sink.write(event.data(), event.size());
  20315. }
  20316. return false;
  20317. });
  20318. });
  20319. Client client("localhost", get_port());
  20320. Headers headers = {{"Authorization", "Bearer expired"}};
  20321. sse::SSEClient sse(client, "/auth-retry", headers);
  20322. std::atomic<bool> message_received{false};
  20323. // Refresh token on error
  20324. sse.on_error(
  20325. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20326. sse.on_message([&](const sse::SSEMessage &msg) {
  20327. if (msg.data == "authenticated") { message_received.store(true); }
  20328. });
  20329. sse.set_reconnect_interval(100);
  20330. sse.set_max_reconnect_attempts(3);
  20331. sse.start_async();
  20332. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20333. sse.stop();
  20334. // Should have reconnected after 401 and succeeded with new token
  20335. EXPECT_GE(connection_count.load(), 2);
  20336. EXPECT_TRUE(message_received.load());
  20337. }
  20338. TEST(Issue2318Test, EmptyHostString) {
  20339. {
  20340. httplib::Client cli_empty("", PORT);
  20341. auto res = cli_empty.Get("/");
  20342. ASSERT_FALSE(res);
  20343. EXPECT_EQ(httplib::Error::Connection, res.error());
  20344. }
  20345. {
  20346. httplib::Client cli(" ", PORT);
  20347. auto res = cli.Get("/");
  20348. ASSERT_FALSE(res);
  20349. EXPECT_EQ(httplib::Error::Connection, res.error());
  20350. }
  20351. }
  20352. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20353. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20354. Server svr;
  20355. // Set a small payload limit (1KB)
  20356. svr.set_payload_max_length(1024);
  20357. svr.Post("/test", [&](const Request &req, Response &res) {
  20358. res.set_content("Body size: " + std::to_string(req.body.size()),
  20359. "text/plain");
  20360. });
  20361. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20362. auto se = detail::scope_exit([&] {
  20363. svr.stop();
  20364. listen_thread.join();
  20365. });
  20366. svr.wait_until_ready();
  20367. // Create data that compresses well but exceeds limit when decompressed
  20368. // 8KB of repeated null bytes compresses to a very small size
  20369. std::string original_data(8 * 1024, '\0');
  20370. // Compress the data using gzip
  20371. std::string compressed_data;
  20372. detail::gzip_compressor compressor;
  20373. compressor.compress(original_data.data(), original_data.size(), true,
  20374. [&](const char *data, size_t size) {
  20375. compressed_data.append(data, size);
  20376. return true;
  20377. });
  20378. // Verify compression worked (compressed should be much smaller)
  20379. ASSERT_LT(compressed_data.size(), original_data.size());
  20380. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20381. // Send compressed data with Content-Encoding: gzip
  20382. Client cli(HOST, PORT);
  20383. Headers headers = {{"Content-Encoding", "gzip"}};
  20384. auto res =
  20385. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20386. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20388. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20389. }
  20390. #endif
  20391. // ============================================================================
  20392. // OpenSSL-Specific Tests
  20393. // ============================================================================
  20394. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20395. X509 *readCertificate(const std::string &strFileName) {
  20396. std::ifstream inStream(strFileName);
  20397. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20398. std::istreambuf_iterator<char>());
  20399. if (strCertPEM.empty()) return (nullptr);
  20400. BIO *pbCert = BIO_new(BIO_s_mem());
  20401. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20402. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20403. BIO_free(pbCert);
  20404. return (pCert);
  20405. }
  20406. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20407. std::ifstream inStream(strFileName);
  20408. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20409. std::istreambuf_iterator<char>());
  20410. if (strPrivateKeyPEM.empty()) return (nullptr);
  20411. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20412. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20413. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20414. BIO_free(pbPrivKey);
  20415. return (pPrivateKey);
  20416. }
  20417. TEST(BindServerTest, UpdateCerts) {
  20418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20419. int port = svr.bind_to_any_port("0.0.0.0");
  20420. ASSERT_TRUE(svr.is_valid());
  20421. ASSERT_TRUE(port > 0);
  20422. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20423. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20424. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20425. ASSERT_TRUE(cert != nullptr);
  20426. ASSERT_TRUE(ca_cert != nullptr);
  20427. ASSERT_TRUE(key != nullptr);
  20428. X509_STORE *cert_store = X509_STORE_new();
  20429. X509_STORE_add_cert(cert_store, ca_cert);
  20430. // svr.update_certs(cert, key, cert_store); // deprecated
  20431. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20432. CLIENT_CA_CERT_FILE);
  20433. ASSERT_TRUE(svr.is_valid());
  20434. svr.stop();
  20435. X509_STORE_free(cert_store);
  20436. X509_free(cert);
  20437. X509_free(ca_cert);
  20438. EVP_PKEY_free(key);
  20439. }
  20440. // Test that update_certs() updates client CA list correctly
  20441. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20442. // Start with file-based constructor
  20443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20444. ASSERT_TRUE(svr.is_valid());
  20445. // Initially no client CA list should be set
  20446. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20447. ASSERT_TRUE(ssl_ctx != nullptr);
  20448. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20449. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20450. EXPECT_EQ(0, count_before);
  20451. // Now update with client CA (PEM string)
  20452. std::string cert_pem, key_pem, ca_pem;
  20453. read_file(SERVER_CERT_FILE, cert_pem);
  20454. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20455. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20456. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20457. ASSERT_TRUE(svr.is_valid());
  20458. // Now client CA list should be set
  20459. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20460. ASSERT_TRUE(ca_list_after != nullptr);
  20461. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20462. }
  20463. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20464. // Test that the file-path SSLServer constructor properly sets the client CA
  20465. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20467. ASSERT_TRUE(svr.is_valid());
  20468. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20469. ASSERT_TRUE(ssl_ctx != nullptr);
  20470. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20471. ASSERT_TRUE(ca_list != nullptr);
  20472. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20473. }
  20474. #endif
  20475. // ============================================================================
  20476. // MbedTLS-Specific Tests
  20477. // ============================================================================
  20478. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20479. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20480. using namespace httplib::tls;
  20481. // Track if callback was invoked
  20482. bool callback_invoked = false;
  20483. // The callback receives void* ctx which is actually MbedTlsContext*
  20484. // We can access the mbedtls_ssl_config via the context
  20485. auto setup_callback = [&callback_invoked](void *ctx) {
  20486. callback_invoked = true;
  20487. // Cast to MbedTlsContext* to access the ssl config
  20488. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20489. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20490. // Use static variables to hold certificate data (simplified for test)
  20491. static mbedtls_x509_crt own_cert;
  20492. static mbedtls_pk_context own_key;
  20493. static mbedtls_x509_crt ca_chain;
  20494. static bool initialized = false;
  20495. if (!initialized) {
  20496. mbedtls_x509_crt_init(&own_cert);
  20497. mbedtls_pk_init(&own_key);
  20498. mbedtls_x509_crt_init(&ca_chain);
  20499. // Load server certificate
  20500. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20501. return false;
  20502. }
  20503. // Load server private key.
  20504. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20505. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20506. #if MBEDTLS_VERSION_MAJOR == 3
  20507. ,
  20508. mbedtls_ctr_drbg_random, nullptr
  20509. #endif
  20510. ) != 0) {
  20511. return false;
  20512. }
  20513. // Load CA chain for client verification
  20514. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20515. return false;
  20516. }
  20517. initialized = true;
  20518. }
  20519. // Configure the SSL config
  20520. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20521. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20522. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20523. // Set minimum TLS version using mbedTLS native API
  20524. #if MBEDTLS_VERSION_MAJOR >= 3
  20525. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20526. #else
  20527. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20528. MBEDTLS_SSL_MINOR_VERSION_3);
  20529. #endif
  20530. return true;
  20531. };
  20532. SSLServer svr(setup_callback);
  20533. ASSERT_TRUE(svr.is_valid());
  20534. ASSERT_TRUE(callback_invoked);
  20535. svr.Get("/test", [&](const Request &req, Response &res) {
  20536. res.set_content("test", "text/plain");
  20537. auto cert = req.peer_cert();
  20538. ASSERT_TRUE(static_cast<bool>(cert));
  20539. auto common_name = cert.subject_cn();
  20540. EXPECT_EQ("Common Name", common_name);
  20541. });
  20542. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20543. auto se = detail::scope_exit([&] {
  20544. svr.stop();
  20545. t.join();
  20546. ASSERT_FALSE(svr.is_running());
  20547. });
  20548. svr.wait_until_ready();
  20549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20550. cli.enable_server_certificate_verification(false);
  20551. cli.set_connection_timeout(30);
  20552. auto res = cli.Get("/test");
  20553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20554. ASSERT_EQ(StatusCode::OK_200, res->status);
  20555. }
  20556. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20557. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20558. // keep-alive SSL session, which reads through that config in
  20559. // mbedtls_ssl_close_notify.
  20560. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20561. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20562. ASSERT_TRUE(svr.is_valid());
  20563. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20564. res.set_content("test", "text/plain");
  20565. });
  20566. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20567. auto se = detail::scope_exit([&] {
  20568. svr.stop();
  20569. t.join();
  20570. ASSERT_FALSE(svr.is_running());
  20571. });
  20572. svr.wait_until_ready();
  20573. {
  20574. SSLClient cli(HOST, PORT);
  20575. cli.enable_server_certificate_verification(false);
  20576. cli.set_keep_alive(true);
  20577. auto res = cli.Get("/test");
  20578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20579. ASSERT_EQ(StatusCode::OK_200, res->status);
  20580. // cli is destructed here with the keep-alive SSL session still open.
  20581. }
  20582. }
  20583. #endif
  20584. // WebSocket Tests
  20585. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20586. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20587. // defining the meaning of these bits has been negotiated.
  20588. auto make_frame = [](uint8_t first_byte) {
  20589. std::string frame;
  20590. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20591. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20592. frame += "Hello";
  20593. return frame;
  20594. };
  20595. // RSV1 set (0x40)
  20596. {
  20597. detail::BufferStream strm;
  20598. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20599. ws::Opcode opcode;
  20600. std::string payload;
  20601. bool fin;
  20602. EXPECT_EQ(
  20603. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20604. ws::impl::FrameRead::Fail);
  20605. }
  20606. // RSV2 set (0x20)
  20607. {
  20608. detail::BufferStream strm;
  20609. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20610. ws::Opcode opcode;
  20611. std::string payload;
  20612. bool fin;
  20613. EXPECT_EQ(
  20614. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20615. ws::impl::FrameRead::Fail);
  20616. }
  20617. // RSV3 set (0x10)
  20618. {
  20619. detail::BufferStream strm;
  20620. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20621. ws::Opcode opcode;
  20622. std::string payload;
  20623. bool fin;
  20624. EXPECT_EQ(
  20625. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20626. ws::impl::FrameRead::Fail);
  20627. }
  20628. // No RSV bits set - should succeed
  20629. {
  20630. detail::BufferStream strm;
  20631. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20632. ws::Opcode opcode;
  20633. std::string payload;
  20634. bool fin;
  20635. EXPECT_EQ(
  20636. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20637. ws::impl::FrameRead::Ok);
  20638. EXPECT_EQ(ws::Opcode::Text, opcode);
  20639. EXPECT_EQ("Hello", payload);
  20640. EXPECT_TRUE(fin);
  20641. }
  20642. }
  20643. TEST(WebSocketTest, ControlFrameValidation) {
  20644. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20645. // payload length <= 125.
  20646. // Ping with FIN=0 - must be rejected
  20647. {
  20648. detail::BufferStream strm;
  20649. std::string frame;
  20650. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20651. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20652. strm.write(frame.data(), frame.size());
  20653. ws::Opcode opcode;
  20654. std::string payload;
  20655. bool fin;
  20656. EXPECT_EQ(
  20657. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20658. ws::impl::FrameRead::Fail);
  20659. }
  20660. // Close with FIN=0 - must be rejected
  20661. {
  20662. detail::BufferStream strm;
  20663. std::string frame;
  20664. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20665. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20666. strm.write(frame.data(), frame.size());
  20667. ws::Opcode opcode;
  20668. std::string payload;
  20669. bool fin;
  20670. EXPECT_EQ(
  20671. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20672. ws::impl::FrameRead::Fail);
  20673. }
  20674. // Ping with payload_len=126 (extended length) - must be rejected
  20675. {
  20676. detail::BufferStream strm;
  20677. std::string frame;
  20678. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20679. frame += static_cast<char>(126); // payload_len=126 (>125)
  20680. frame += static_cast<char>(0x00); // extended length high byte
  20681. frame += static_cast<char>(126); // extended length low byte
  20682. frame += std::string(126, 'x');
  20683. strm.write(frame.data(), frame.size());
  20684. ws::Opcode opcode;
  20685. std::string payload;
  20686. bool fin;
  20687. EXPECT_EQ(
  20688. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20689. ws::impl::FrameRead::Fail);
  20690. }
  20691. // Ping with FIN=1 and payload_len=125 - should succeed
  20692. {
  20693. detail::BufferStream strm;
  20694. std::string frame;
  20695. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20696. frame += static_cast<char>(125); // payload_len=125
  20697. frame += std::string(125, 'x');
  20698. strm.write(frame.data(), frame.size());
  20699. ws::Opcode opcode;
  20700. std::string payload;
  20701. bool fin;
  20702. EXPECT_EQ(
  20703. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20704. ws::impl::FrameRead::Ok);
  20705. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20706. EXPECT_EQ(125u, payload.size());
  20707. EXPECT_TRUE(fin);
  20708. }
  20709. }
  20710. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20711. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20712. // length MUST be 0.
  20713. // MSB set - must be rejected
  20714. {
  20715. detail::BufferStream strm;
  20716. std::string frame;
  20717. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20718. frame += static_cast<char>(127); // 64-bit extended length
  20719. frame += static_cast<char>(0x80); // MSB set (invalid)
  20720. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20721. strm.write(frame.data(), frame.size());
  20722. ws::Opcode opcode;
  20723. std::string payload;
  20724. bool fin;
  20725. EXPECT_EQ(
  20726. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20727. ws::impl::FrameRead::Fail);
  20728. }
  20729. // MSB clear - should pass length parsing (will be rejected by max_len,
  20730. // but that's a different check; use a small length to verify)
  20731. {
  20732. detail::BufferStream strm;
  20733. std::string frame;
  20734. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20735. frame += static_cast<char>(127); // 64-bit extended length
  20736. frame += std::string(7, '\0'); // high bytes = 0
  20737. frame += static_cast<char>(0x03); // length = 3
  20738. frame += "abc";
  20739. strm.write(frame.data(), frame.size());
  20740. ws::Opcode opcode;
  20741. std::string payload;
  20742. bool fin;
  20743. EXPECT_EQ(
  20744. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20745. ws::impl::FrameRead::Ok);
  20746. EXPECT_EQ(ws::Opcode::Text, opcode);
  20747. EXPECT_EQ("abc", payload);
  20748. }
  20749. }
  20750. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20751. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20752. // Valid UTF-8
  20753. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20754. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20755. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20756. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20757. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20758. // Invalid UTF-8
  20759. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20760. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20761. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20762. EXPECT_FALSE(
  20763. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20764. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20765. }
  20766. TEST(WebSocketTest, ConnectAndDisconnect) {
  20767. Server svr;
  20768. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20769. std::string msg;
  20770. while (ws.read(msg)) {}
  20771. });
  20772. auto port = svr.bind_to_any_port(HOST);
  20773. std::thread t([&]() { svr.listen_after_bind(); });
  20774. svr.wait_until_ready();
  20775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20776. auto res = client.connect();
  20777. ASSERT_TRUE(res);
  20778. EXPECT_EQ(Error::Success, res.error());
  20779. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20780. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20781. EXPECT_TRUE(client.is_open());
  20782. client.close();
  20783. EXPECT_FALSE(client.is_open());
  20784. svr.stop();
  20785. t.join();
  20786. }
  20787. TEST(WebSocketTest, ValidURL) {
  20788. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20789. EXPECT_TRUE(ws1.is_valid());
  20790. ws::WebSocketClient ws2("ws://example.com/path");
  20791. EXPECT_TRUE(ws2.is_valid());
  20792. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20793. EXPECT_TRUE(ws3.is_valid());
  20794. #ifdef CPPHTTPLIB_SSL_ENABLED
  20795. ws::WebSocketClient wss1("wss://example.com/path");
  20796. EXPECT_TRUE(wss1.is_valid());
  20797. ws::WebSocketClient wss2("wss://example.com:443/path");
  20798. EXPECT_TRUE(wss2.is_valid());
  20799. #endif
  20800. }
  20801. TEST(WebSocketTest, InvalidURL) {
  20802. // No scheme
  20803. ws::WebSocketClient ws1("localhost:8080/path");
  20804. EXPECT_FALSE(ws1.is_valid());
  20805. // No path
  20806. ws::WebSocketClient ws2("ws://localhost:8080");
  20807. EXPECT_FALSE(ws2.is_valid());
  20808. // Empty string
  20809. ws::WebSocketClient ws3("");
  20810. EXPECT_FALSE(ws3.is_valid());
  20811. // Missing host
  20812. ws::WebSocketClient ws4("ws://:8080/path");
  20813. EXPECT_FALSE(ws4.is_valid());
  20814. // Port number overflow — should not crash
  20815. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20816. EXPECT_FALSE(ws5.is_valid());
  20817. // Port out of range
  20818. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20819. EXPECT_FALSE(ws6.is_valid());
  20820. }
  20821. TEST(WebSocketTest, UnsupportedScheme) {
  20822. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20823. ws::WebSocketClient ws1("http://localhost:8080/path");
  20824. EXPECT_FALSE(ws1.is_valid());
  20825. ws::WebSocketClient ws2("https://localhost:8080/path");
  20826. EXPECT_FALSE(ws2.is_valid());
  20827. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20828. EXPECT_FALSE(ws3.is_valid());
  20829. #else
  20830. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20831. std::invalid_argument);
  20832. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20833. std::invalid_argument);
  20834. #endif
  20835. }
  20836. TEST(WebSocketTest, ConnectWhenInvalid) {
  20837. ws::WebSocketClient ws("not a valid url");
  20838. EXPECT_FALSE(ws.is_valid());
  20839. auto res = ws.connect();
  20840. EXPECT_FALSE(res);
  20841. EXPECT_EQ(Error::Connection, res.error());
  20842. EXPECT_EQ(-1, res.status());
  20843. }
  20844. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20845. // Grab a port that is free, then close it again so nothing listens there
  20846. Server svr;
  20847. auto port = svr.bind_to_any_port(HOST);
  20848. svr.stop();
  20849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20850. auto res = client.connect();
  20851. ASSERT_FALSE(res);
  20852. EXPECT_EQ(Error::Connection, res.error());
  20853. EXPECT_EQ(-1, res.status());
  20854. }
  20855. TEST(WebSocketTest, DefaultPort) {
  20856. ws::WebSocketClient ws1("ws://example.com/path");
  20857. EXPECT_TRUE(ws1.is_valid());
  20858. // ws:// defaults to port 80 (verified by successful parse)
  20859. #ifdef CPPHTTPLIB_SSL_ENABLED
  20860. ws::WebSocketClient ws2("wss://example.com/path");
  20861. EXPECT_TRUE(ws2.is_valid());
  20862. // wss:// defaults to port 443 (verified by successful parse)
  20863. #endif
  20864. }
  20865. TEST(WebSocketTest, IPv6LiteralAddress) {
  20866. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20867. EXPECT_TRUE(ws1.is_valid());
  20868. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20869. EXPECT_TRUE(ws2.is_valid());
  20870. }
  20871. TEST(WebSocketTest, ComplexPath) {
  20872. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20873. EXPECT_TRUE(ws1.is_valid());
  20874. ws::WebSocketClient ws2("ws://localhost:8080/");
  20875. EXPECT_TRUE(ws2.is_valid());
  20876. }
  20877. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20878. Server svr;
  20879. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20880. std::string msg;
  20881. while (ws.read(msg)) {}
  20882. });
  20883. auto port = svr.bind_to_any_port(HOST);
  20884. std::thread t([&]() { svr.listen_after_bind(); });
  20885. svr.wait_until_ready();
  20886. auto another_host = "example.com";
  20887. auto wrong_ip = "192.0.2.1";
  20888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20889. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20890. ASSERT_TRUE(client.connect());
  20891. EXPECT_TRUE(client.is_open());
  20892. client.close();
  20893. svr.stop();
  20894. t.join();
  20895. }
  20896. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20897. Server svr;
  20898. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20899. std::string msg;
  20900. while (ws.read(msg)) {}
  20901. });
  20902. auto port = svr.bind_to_any_port(HOST);
  20903. std::thread t([&]() { svr.listen_after_bind(); });
  20904. svr.wait_until_ready();
  20905. auto wrong_ip = "192.0.2.1";
  20906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20907. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20908. client.set_connection_timeout(1);
  20909. client.set_read_timeout(1);
  20910. client.set_write_timeout(1);
  20911. EXPECT_FALSE(client.connect());
  20912. EXPECT_FALSE(client.is_open());
  20913. svr.stop();
  20914. t.join();
  20915. }
  20916. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20917. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20918. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20919. // (RFC 6761) is only a map key and the Host header value.
  20920. auto host = "target.invalid";
  20921. Server svr;
  20922. std::string received_host;
  20923. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20924. received_host = req.get_header_value("Host");
  20925. std::string msg;
  20926. while (ws.read(msg)) {}
  20927. });
  20928. auto port = svr.bind_to_any_port(HOST);
  20929. std::thread t([&]() { svr.listen_after_bind(); });
  20930. // ASSERT_* below returns from the test body, which would leave t joinable
  20931. // and make ~thread call std::terminate.
  20932. auto se = detail::scope_exit([&] {
  20933. svr.stop();
  20934. if (t.joinable()) { t.join(); }
  20935. });
  20936. svr.wait_until_ready();
  20937. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20938. std::to_string(port) + "/ws");
  20939. client.set_hostname_addr_map({{host, HOST}});
  20940. ASSERT_TRUE(client.connect());
  20941. EXPECT_TRUE(client.is_open());
  20942. client.close();
  20943. svr.stop();
  20944. t.join();
  20945. // The mapping only redirects the connection; the identity stays host_.
  20946. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20947. }
  20948. class WebSocketIntegrationTest : public ::testing::Test {
  20949. protected:
  20950. void SetUp() override {
  20951. server_ = httplib::detail::make_unique<Server>();
  20952. setup_server();
  20953. start_server();
  20954. }
  20955. void TearDown() override {
  20956. server_->stop();
  20957. if (server_thread_.joinable()) { server_thread_.join(); }
  20958. }
  20959. void setup_server() {
  20960. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20961. std::string msg;
  20962. ws::ReadResult ret;
  20963. while ((ret = ws.read(msg))) {
  20964. if (ret == ws::Binary) {
  20965. ws.send(msg.data(), msg.size());
  20966. } else {
  20967. ws.send(msg);
  20968. }
  20969. }
  20970. });
  20971. server_->WebSocket("/ws-echo-string",
  20972. [](const Request &, ws::WebSocket &ws) {
  20973. std::string msg;
  20974. while (ws.read(msg)) {
  20975. ws.send("echo: " + msg);
  20976. }
  20977. });
  20978. server_->WebSocket(
  20979. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20980. // Echo back request metadata
  20981. ws.send("path:" + req.path);
  20982. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20983. std::string msg;
  20984. while (ws.read(msg)) {}
  20985. });
  20986. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20987. std::string msg;
  20988. ws.read(msg); // wait for a message
  20989. ws.close();
  20990. });
  20991. server_->WebSocket("/ws-close-status",
  20992. [](const Request &, ws::WebSocket &ws) {
  20993. std::string msg;
  20994. ws.read(msg); // wait for a message
  20995. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20996. });
  20997. server_->WebSocket(
  20998. "/ws-subprotocol",
  20999. [](const Request &, ws::WebSocket &ws) {
  21000. std::string msg;
  21001. while (ws.read(msg)) {
  21002. ws.send(msg);
  21003. }
  21004. },
  21005. [](const std::vector<std::string> &protocols) -> std::string {
  21006. for (const auto &p : protocols) {
  21007. if (p == "graphql-ws") { return p; }
  21008. }
  21009. return "";
  21010. });
  21011. server_->WebSocket(
  21012. "/ws-subprotocol-unoffered",
  21013. [](const Request &, ws::WebSocket &ws) {
  21014. std::string msg;
  21015. while (ws.read(msg)) {
  21016. ws.send(msg);
  21017. }
  21018. },
  21019. [](const std::vector<std::string> &) -> std::string {
  21020. return "admin";
  21021. });
  21022. }
  21023. void start_server() {
  21024. port_ = server_->bind_to_any_port(HOST);
  21025. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21026. server_->wait_until_ready();
  21027. }
  21028. std::unique_ptr<Server> server_;
  21029. std::thread server_thread_;
  21030. int port_ = 0;
  21031. };
  21032. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21033. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21034. "/ws-echo");
  21035. ASSERT_TRUE(client.connect());
  21036. ASSERT_TRUE(client.is_open());
  21037. ASSERT_TRUE(client.send("Hello WebSocket"));
  21038. std::string msg;
  21039. EXPECT_EQ(ws::Text, client.read(msg));
  21040. EXPECT_EQ("Hello WebSocket", msg);
  21041. client.close();
  21042. }
  21043. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21045. "/ws-echo");
  21046. ASSERT_TRUE(client.connect());
  21047. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21048. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21049. std::string msg;
  21050. EXPECT_EQ(ws::Binary, client.read(msg));
  21051. EXPECT_EQ(binary_data, msg);
  21052. client.close();
  21053. }
  21054. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21055. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21056. "/ws-echo");
  21057. ASSERT_TRUE(client.connect());
  21058. for (int i = 0; i < 10; i++) {
  21059. auto text = "message " + std::to_string(i);
  21060. ASSERT_TRUE(client.send(text));
  21061. std::string msg;
  21062. ASSERT_TRUE(client.read(msg));
  21063. EXPECT_EQ(text, msg);
  21064. }
  21065. client.close();
  21066. }
  21067. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21068. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21069. "/ws-close");
  21070. ASSERT_TRUE(client.connect());
  21071. // Send a message to trigger the server to close
  21072. ASSERT_TRUE(client.send("trigger close"));
  21073. // The server will close, so read should return false
  21074. std::string msg;
  21075. EXPECT_FALSE(client.read(msg));
  21076. EXPECT_FALSE(client.is_open());
  21077. }
  21078. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21079. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21080. "/ws-echo");
  21081. ASSERT_TRUE(client.connect());
  21082. // 128KB message
  21083. std::string large_data(128 * 1024, 'X');
  21084. ASSERT_TRUE(client.send(large_data));
  21085. std::string msg;
  21086. ASSERT_TRUE(client.read(msg));
  21087. EXPECT_EQ(large_data, msg);
  21088. client.close();
  21089. }
  21090. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21092. "/ws-echo");
  21093. ASSERT_TRUE(client.connect());
  21094. const int num_threads = 4;
  21095. std::vector<std::thread> threads;
  21096. std::atomic<int> send_count{0};
  21097. for (int t = 0; t < num_threads; t++) {
  21098. threads.emplace_back([&client, &send_count, t]() {
  21099. for (int i = 0; i < 5; i++) {
  21100. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21101. if (client.send(text)) { send_count++; }
  21102. }
  21103. });
  21104. }
  21105. for (auto &th : threads) {
  21106. th.join();
  21107. }
  21108. int received = 0;
  21109. std::string msg;
  21110. while (received < send_count.load()) {
  21111. if (!client.read(msg)) { break; }
  21112. received++;
  21113. }
  21114. EXPECT_EQ(send_count.load(), received);
  21115. client.close();
  21116. }
  21117. TEST_F(WebSocketIntegrationTest, ReadString) {
  21118. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21119. "/ws-echo-string");
  21120. ASSERT_TRUE(client.connect());
  21121. ASSERT_TRUE(client.send("hello"));
  21122. std::string msg;
  21123. ASSERT_TRUE(client.read(msg));
  21124. EXPECT_EQ("echo: hello", msg);
  21125. ASSERT_TRUE(client.send("world"));
  21126. ASSERT_TRUE(client.read(msg));
  21127. EXPECT_EQ("echo: world", msg);
  21128. client.close();
  21129. }
  21130. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21131. Headers headers = {{"X-Test-Header", "test-value"}};
  21132. ws::WebSocketClient client(
  21133. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21134. ASSERT_TRUE(client.connect());
  21135. std::string msg;
  21136. ASSERT_TRUE(client.read(msg));
  21137. EXPECT_EQ("path:/ws-request-info", msg);
  21138. ASSERT_TRUE(client.read(msg));
  21139. EXPECT_EQ("header:test-value", msg);
  21140. client.close();
  21141. }
  21142. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21143. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21144. "/ws-echo");
  21145. client.set_read_timeout(1, 0); // 1 second
  21146. ASSERT_TRUE(client.connect());
  21147. // Don't send anything — server echo handler waits for a message, so read()
  21148. // should time out. The connection survives it: nothing was consumed.
  21149. std::string msg;
  21150. EXPECT_EQ(client.read(msg), ws::Timeout);
  21151. EXPECT_TRUE(client.is_open());
  21152. // And it is still usable afterwards.
  21153. EXPECT_TRUE(client.send("after timeout"));
  21154. EXPECT_EQ(client.read(msg), ws::Text);
  21155. EXPECT_EQ(msg, "after timeout");
  21156. }
  21157. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21158. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21159. "/ws-echo");
  21160. client.set_read_timeout(1, 0);
  21161. ASSERT_TRUE(client.connect());
  21162. ASSERT_TRUE(client.send("first"));
  21163. std::string msg;
  21164. ASSERT_EQ(client.read(msg), ws::Text);
  21165. ASSERT_EQ(msg, "first");
  21166. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21167. // not be used with a read timeout: it would reprocess the previous message.
  21168. EXPECT_EQ(client.read(msg), ws::Timeout);
  21169. EXPECT_EQ(msg, "first");
  21170. }
  21171. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21172. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21173. "/ws-echo");
  21174. ASSERT_TRUE(client.connect());
  21175. // Setting it once the connection is open reaches the live stream, not just
  21176. // the seed for the next connect().
  21177. client.set_read_timeout(1, 0);
  21178. std::string msg;
  21179. EXPECT_EQ(client.read(msg), ws::Timeout);
  21180. EXPECT_TRUE(client.is_open());
  21181. }
  21182. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21183. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21184. "/ws-echo");
  21185. client.set_read_timeout(5, 0);
  21186. ASSERT_TRUE(client.connect());
  21187. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21188. // The server should reject it and close the connection.
  21189. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21190. client.send(oversized);
  21191. // The server's read() should have failed due to payload limit,
  21192. // so our read() should return false (connection closed).
  21193. std::string msg;
  21194. EXPECT_FALSE(client.read(msg));
  21195. }
  21196. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21198. "/ws-echo");
  21199. client.set_read_timeout(10, 0);
  21200. ASSERT_TRUE(client.connect());
  21201. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21202. // This should succeed.
  21203. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21204. ASSERT_TRUE(client.send(at_limit));
  21205. std::string msg;
  21206. ASSERT_TRUE(client.read(msg));
  21207. EXPECT_EQ(at_limit.size(), msg.size());
  21208. client.close();
  21209. }
  21210. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21212. "/nonexistent");
  21213. auto res = client.connect();
  21214. EXPECT_FALSE(res);
  21215. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21216. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21217. EXPECT_FALSE(client.is_open());
  21218. }
  21219. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21221. "/ws-echo");
  21222. ASSERT_TRUE(client.connect());
  21223. ASSERT_TRUE(client.send(""));
  21224. std::string msg;
  21225. EXPECT_EQ(ws::Text, client.read(msg));
  21226. EXPECT_EQ("", msg);
  21227. client.close();
  21228. }
  21229. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21231. "/ws-echo");
  21232. // First connection
  21233. ASSERT_TRUE(client.connect());
  21234. ASSERT_TRUE(client.send("first"));
  21235. std::string msg;
  21236. ASSERT_TRUE(client.read(msg));
  21237. EXPECT_EQ("first", msg);
  21238. client.close();
  21239. EXPECT_FALSE(client.is_open());
  21240. // Reconnect using the same client object
  21241. ASSERT_TRUE(client.connect());
  21242. ASSERT_TRUE(client.is_open());
  21243. ASSERT_TRUE(client.send("second"));
  21244. ASSERT_TRUE(client.read(msg));
  21245. EXPECT_EQ("second", msg);
  21246. client.close();
  21247. }
  21248. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21249. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21250. "/ws-close-status");
  21251. ASSERT_TRUE(client.connect());
  21252. // Trigger the server to close with GoingAway status
  21253. ASSERT_TRUE(client.send("trigger"));
  21254. // read() should return false after receiving the close frame
  21255. std::string msg;
  21256. EXPECT_FALSE(client.read(msg));
  21257. EXPECT_FALSE(client.is_open());
  21258. }
  21259. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21260. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21261. "/ws-echo");
  21262. ASSERT_TRUE(client.connect());
  21263. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21264. EXPECT_FALSE(client.is_open());
  21265. }
  21266. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21267. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21268. ws::WebSocketClient client(
  21269. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21270. ASSERT_TRUE(client.connect());
  21271. // Server should have selected graphql-ws
  21272. EXPECT_EQ("graphql-ws", client.subprotocol());
  21273. client.close();
  21274. }
  21275. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21276. Headers headers;
  21277. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21278. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21279. ws::WebSocketClient client(
  21280. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21281. ASSERT_TRUE(client.connect());
  21282. // The offer on the second field line counts too, so graphql-ws is selected
  21283. EXPECT_EQ("graphql-ws", client.subprotocol());
  21284. client.close();
  21285. }
  21286. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21287. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21288. ws::WebSocketClient client(
  21289. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21290. ASSERT_TRUE(client.connect());
  21291. // Server should not have selected any subprotocol
  21292. EXPECT_TRUE(client.subprotocol().empty());
  21293. client.close();
  21294. }
  21295. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21296. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21297. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21298. "/ws-subprotocol-unoffered",
  21299. headers);
  21300. ASSERT_TRUE(client.connect());
  21301. EXPECT_TRUE(client.subprotocol().empty());
  21302. client.close();
  21303. }
  21304. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21305. // Connect without requesting any subprotocol
  21306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21307. "/ws-subprotocol");
  21308. ASSERT_TRUE(client.connect());
  21309. EXPECT_TRUE(client.subprotocol().empty());
  21310. client.close();
  21311. }
  21312. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21313. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21314. "/ws-echo");
  21315. client.set_tcp_nodelay(true);
  21316. client.set_connection_timeout(3, 0);
  21317. bool socket_options_called = false;
  21318. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21319. ASSERT_TRUE(client.connect());
  21320. ASSERT_TRUE(client.is_open());
  21321. EXPECT_TRUE(socket_options_called);
  21322. ASSERT_TRUE(client.send("hello"));
  21323. std::string msg;
  21324. auto result = client.read(msg);
  21325. EXPECT_EQ(result, ws::ReadResult::Text);
  21326. EXPECT_EQ(msg, "hello");
  21327. client.close();
  21328. }
  21329. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21330. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21331. "/ws-echo");
  21332. client.set_connection_timeout(std::chrono::seconds(3));
  21333. client.set_write_timeout(std::chrono::seconds(3));
  21334. // A sub-second remainder exercises the seconds/microseconds split.
  21335. client.set_read_timeout(std::chrono::milliseconds(1500));
  21336. ASSERT_TRUE(client.connect());
  21337. auto start = std::chrono::steady_clock::now();
  21338. std::string msg;
  21339. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21340. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21341. std::chrono::steady_clock::now() - start)
  21342. .count();
  21343. // Above 1s so that dropping the microseconds half of the split fails here.
  21344. // Ignoring the setter altogether would not reach this line at all: a client
  21345. // waits forever by default.
  21346. EXPECT_GE(elapsed, 1400);
  21347. EXPECT_LT(elapsed, 30000);
  21348. }
  21349. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21350. Server svr;
  21351. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21352. if (!req.has_header("Authorization")) {
  21353. res.status = StatusCode::Unauthorized_401;
  21354. res.set_content("Unauthorized", "text/plain");
  21355. return Server::HandlerResponse::Handled;
  21356. }
  21357. return Server::HandlerResponse::Unhandled;
  21358. });
  21359. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21360. std::string msg;
  21361. while (ws.read(msg)) {
  21362. ws.send(msg);
  21363. }
  21364. });
  21365. auto port = svr.bind_to_any_port("localhost");
  21366. std::thread t([&]() { svr.listen_after_bind(); });
  21367. svr.wait_until_ready();
  21368. // Without Authorization header - should be rejected before upgrade
  21369. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21370. EXPECT_FALSE(client1.connect());
  21371. // The rejection is framed like any other HTTP response
  21372. {
  21373. Client cli("localhost", port);
  21374. Headers headers = {{"Upgrade", "websocket"},
  21375. {"Connection", "Upgrade"},
  21376. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21377. {"Sec-WebSocket-Version", "13"}};
  21378. auto res = cli.Get("/ws", headers);
  21379. ASSERT_TRUE(res);
  21380. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21381. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21382. EXPECT_EQ("Unauthorized", res->body);
  21383. }
  21384. // With Authorization header - should succeed
  21385. Headers headers = {{"Authorization", "Bearer token123"}};
  21386. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21387. headers);
  21388. ASSERT_TRUE(client2.connect());
  21389. ASSERT_TRUE(client2.send("hello"));
  21390. std::string msg;
  21391. ASSERT_TRUE(client2.read(msg));
  21392. EXPECT_EQ("hello", msg);
  21393. client2.close();
  21394. svr.stop();
  21395. t.join();
  21396. }
  21397. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21398. Server svr;
  21399. std::atomic<int> pre_request_calls{0};
  21400. std::atomic<bool> route_matched{false};
  21401. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21402. pre_request_calls++;
  21403. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21404. if (req.get_header_value("Authorization") != "Bearer token123") {
  21405. res.status = StatusCode::Unauthorized_401;
  21406. res.set_content("Unauthorized", "text/plain");
  21407. return Server::HandlerResponse::Handled;
  21408. }
  21409. return Server::HandlerResponse::Unhandled;
  21410. });
  21411. std::atomic<bool> handler_called{false};
  21412. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21413. handler_called = true;
  21414. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21415. });
  21416. auto port = svr.bind_to_any_port("localhost");
  21417. std::thread t([&]() { svr.listen_after_bind(); });
  21418. svr.wait_until_ready();
  21419. // Without Authorization header - should be rejected before upgrade
  21420. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21421. "/ws/1");
  21422. EXPECT_FALSE(client1.connect());
  21423. EXPECT_FALSE(handler_called);
  21424. EXPECT_EQ(1, pre_request_calls);
  21425. EXPECT_TRUE(route_matched);
  21426. // The rejection is an ordinary HTTP response, not a protocol switch
  21427. {
  21428. Client cli("localhost", port);
  21429. Headers headers = {{"Upgrade", "websocket"},
  21430. {"Connection", "Upgrade"},
  21431. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21432. {"Sec-WebSocket-Version", "13"}};
  21433. auto res = cli.Get("/ws/1", headers);
  21434. ASSERT_TRUE(res);
  21435. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21436. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21437. EXPECT_EQ("Unauthorized", res->body);
  21438. }
  21439. EXPECT_FALSE(handler_called);
  21440. // With Authorization header - should succeed
  21441. Headers headers = {{"Authorization", "Bearer token123"}};
  21442. ws::WebSocketClient client2(
  21443. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21444. ASSERT_TRUE(client2.connect());
  21445. std::string msg;
  21446. ASSERT_TRUE(client2.read(msg));
  21447. EXPECT_EQ("/ws/:id 2", msg);
  21448. EXPECT_TRUE(handler_called);
  21449. client2.close();
  21450. svr.stop();
  21451. t.join();
  21452. }
  21453. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21454. Server svr;
  21455. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21456. // A read timeout is how a handler gets control back. Without it, a handler
  21457. // parked in read() can never write on the connection it is reading.
  21458. ws.set_read_timeout(std::chrono::milliseconds(100));
  21459. std::string msg;
  21460. while (ws.is_open()) {
  21461. auto r = ws.read(msg);
  21462. if (r == httplib::ws::Timeout) {
  21463. ws.send("tick");
  21464. continue;
  21465. }
  21466. if (r == httplib::ws::Fail) { break; }
  21467. ws.send(msg);
  21468. }
  21469. });
  21470. auto port = svr.bind_to_any_port("localhost");
  21471. std::thread t([&]() { svr.listen_after_bind(); });
  21472. svr.wait_until_ready();
  21473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21474. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21475. ASSERT_TRUE(client.connect());
  21476. // The client sends nothing, so anything it receives came out of the
  21477. // handler's timeout path.
  21478. std::string msg;
  21479. ASSERT_EQ(client.read(msg), ws::Text);
  21480. EXPECT_EQ("tick", msg);
  21481. client.close();
  21482. svr.stop();
  21483. t.join();
  21484. }
  21485. // Stream::read may return fewer bytes than asked for. This is that contract at
  21486. // its worst -- one byte per call -- which is what a frame header straddling a
  21487. // read buffer's boundary looks like to the frame parser.
  21488. class WsByteAtATimeStream : public Stream {
  21489. public:
  21490. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21491. bool is_readable() const override { return true; }
  21492. bool wait_readable() const override { return true; }
  21493. bool wait_writable() const override { return true; }
  21494. ssize_t read(char *ptr, size_t size) override {
  21495. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21496. *ptr = data_[pos_++];
  21497. return 1;
  21498. }
  21499. ssize_t write(const char *, size_t size) override {
  21500. return static_cast<ssize_t>(size);
  21501. }
  21502. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21503. ip = "127.0.0.1";
  21504. port = 0;
  21505. }
  21506. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21507. ip = "127.0.0.1";
  21508. port = 0;
  21509. }
  21510. socket_t socket() const override { return INVALID_SOCKET; }
  21511. time_t duration() const override { return 0; }
  21512. private:
  21513. std::string data_;
  21514. size_t pos_ = 0;
  21515. };
  21516. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21517. // The payload uses the 16-bit extended length, so the header, the length
  21518. // and the mask key are all multi-byte fields here. Each used to be read
  21519. // with a single read() call, which fails as soon as one is split. The
  21520. // payload is also a little over one read chunk, so it is read in two.
  21521. std::string body;
  21522. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21523. body += static_cast<char>(i % 251);
  21524. }
  21525. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21526. std::string frame;
  21527. frame += static_cast<char>(0x81); // FIN + Text
  21528. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21529. frame += static_cast<char>(body.size() >> 8);
  21530. frame += static_cast<char>(body.size() & 0xff);
  21531. for (size_t i = 0; i < 4; i++) {
  21532. frame += static_cast<char>(mask[i]);
  21533. }
  21534. for (size_t i = 0; i < body.size(); i++) {
  21535. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21536. }
  21537. WsByteAtATimeStream strm(frame);
  21538. ws::Opcode opcode;
  21539. std::string payload;
  21540. bool fin = false;
  21541. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21542. /*expect_masked=*/true, body.size()),
  21543. ws::impl::FrameRead::Ok);
  21544. EXPECT_TRUE(fin);
  21545. EXPECT_EQ(opcode, ws::Opcode::Text);
  21546. EXPECT_EQ(payload, body);
  21547. }
  21548. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21549. // The header announces the largest payload allowed, and only 3 bytes of it
  21550. // ever arrive.
  21551. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21552. std::string frame;
  21553. frame += static_cast<char>(0x82); // FIN + Binary
  21554. frame += static_cast<char>(127); // 64-bit length follows
  21555. for (int shift = 56; shift >= 0; shift -= 8) {
  21556. frame += static_cast<char>((len >> shift) & 0xff);
  21557. }
  21558. frame += "abc";
  21559. detail::BufferStream strm;
  21560. strm.write(frame.data(), frame.size());
  21561. ws::Opcode opcode;
  21562. std::string payload;
  21563. bool fin;
  21564. EXPECT_EQ(
  21565. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21566. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21567. ws::impl::FrameRead::Fail);
  21568. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21569. }
  21570. TEST(WebSocketTest, QueryStringInHandshake) {
  21571. Server svr;
  21572. std::mutex mtx;
  21573. std::string received_target;
  21574. std::string received_token;
  21575. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21576. {
  21577. std::lock_guard<std::mutex> lock(mtx);
  21578. received_target = req.target;
  21579. if (req.has_param("token")) {
  21580. received_token = req.get_param_value("token");
  21581. }
  21582. }
  21583. std::string msg;
  21584. while (ws.read(msg)) {
  21585. ws.send(msg);
  21586. }
  21587. });
  21588. auto port = svr.bind_to_any_port("localhost");
  21589. std::thread t([&]() { svr.listen_after_bind(); });
  21590. svr.wait_until_ready();
  21591. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21592. "/ws?token=ABC&session=123");
  21593. ASSERT_TRUE(client.connect());
  21594. // Round-trip ensures the handler has run and captured the request.
  21595. ASSERT_TRUE(client.send("hello"));
  21596. std::string msg;
  21597. ASSERT_TRUE(client.read(msg));
  21598. EXPECT_EQ("hello", msg);
  21599. client.close();
  21600. {
  21601. std::lock_guard<std::mutex> lock(mtx);
  21602. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21603. EXPECT_EQ("ABC", received_token);
  21604. }
  21605. svr.stop();
  21606. t.join();
  21607. }
  21608. // Run a handshake against a throwaway server and hand the request the server
  21609. // received back to the caller, so tests can assert on the headers the client
  21610. // actually put on the wire.
  21611. static void capture_websocket_handshake_request(
  21612. const Headers &client_headers,
  21613. std::function<void(const Request &, int port)> verify) {
  21614. Server svr;
  21615. std::mutex mtx;
  21616. Request received;
  21617. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21618. {
  21619. std::lock_guard<std::mutex> lock(mtx);
  21620. received = req;
  21621. }
  21622. std::string msg;
  21623. while (ws.read(msg)) {
  21624. ws.send(msg);
  21625. }
  21626. });
  21627. auto port = svr.bind_to_any_port("localhost");
  21628. std::thread t([&]() { svr.listen_after_bind(); });
  21629. auto se = detail::scope_exit([&] {
  21630. svr.stop();
  21631. t.join();
  21632. });
  21633. svr.wait_until_ready();
  21634. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21635. client_headers);
  21636. ASSERT_TRUE(client.connect());
  21637. ASSERT_TRUE(client.send("hello"));
  21638. std::string msg;
  21639. ASSERT_TRUE(client.read(msg));
  21640. client.close();
  21641. {
  21642. std::lock_guard<std::mutex> lock(mtx);
  21643. verify(received, port);
  21644. }
  21645. }
  21646. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21647. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21648. // Non-default port must be present in the Host header. Default ports
  21649. // (80/443) are omitted; that logic is covered by
  21650. // MakeHostAndPortStringTest.
  21651. EXPECT_EQ("localhost:" + std::to_string(port),
  21652. req.get_header_value("Host"));
  21653. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21654. req.get_header_value("User-Agent"));
  21655. EXPECT_FALSE(req.has_header("Accept"));
  21656. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21657. EXPECT_FALSE(req.has_header("Content-Length"));
  21658. });
  21659. }
  21660. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21661. capture_websocket_handshake_request(
  21662. {{"Host", "example.com"},
  21663. {"User-Agent", "custom-agent"},
  21664. {"X-Custom", "value"}},
  21665. [](const Request &req, int) {
  21666. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21667. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21668. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21669. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21670. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21671. });
  21672. }
  21673. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21674. capture_websocket_handshake_request(
  21675. {{"Upgrade", "bogus"},
  21676. {"Connection", "close"},
  21677. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21678. {"Sec-WebSocket-Version", "8"}},
  21679. [](const Request &req, int) {
  21680. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21681. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21682. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21683. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21684. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21685. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21686. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21687. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21688. req.get_header_value("Sec-WebSocket-Key"));
  21689. });
  21690. }
  21691. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21692. // A header the client refuses to send must abort the handshake before any
  21693. // part of it reaches the wire; a lone request line would otherwise sit in
  21694. // the peer's buffer as a truncated request.
  21695. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21696. ASSERT_NE(INVALID_SOCKET, srv);
  21697. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21698. sockaddr_in addr{};
  21699. addr.sin_family = AF_INET;
  21700. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21701. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21702. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21703. ASSERT_EQ(0, ::listen(srv, 1));
  21704. sockaddr_in bound{};
  21705. socklen_t bound_len = sizeof(bound);
  21706. ASSERT_EQ(
  21707. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21708. auto port = ntohs(bound.sin_port);
  21709. ssize_t received = -1;
  21710. std::thread t([&] {
  21711. // Bound every blocking call so a regression fails the test with a bad
  21712. // value instead of hanging the suite.
  21713. fd_set rfds;
  21714. FD_ZERO(&rfds);
  21715. FD_SET(srv, &rfds);
  21716. timeval tv{5, 0};
  21717. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21718. 0) {
  21719. return;
  21720. }
  21721. sockaddr_in cli_addr{};
  21722. socklen_t cli_len = sizeof(cli_addr);
  21723. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21724. if (cli == INVALID_SOCKET) { return; }
  21725. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21726. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21727. char buf[4096];
  21728. received = ::recv(cli, buf, sizeof(buf), 0);
  21729. });
  21730. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21731. // connect() has already shut the socket down by the time it returns false,
  21732. // so the peer sees EOF without waiting for the client to be destroyed.
  21733. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21734. {{"X-Bad", "a\r\nInjected: 1"}});
  21735. EXPECT_FALSE(client.connect());
  21736. t.join();
  21737. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21738. EXPECT_EQ(0, received);
  21739. }
  21740. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21741. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21742. // contains "upgrade" as a substring is a different token and must not
  21743. // start a WebSocket handshake.
  21744. auto make_request = [](const std::vector<std::string> &connection_values) {
  21745. Request req;
  21746. req.method = "GET";
  21747. req.headers.emplace("Upgrade", "websocket");
  21748. for (const auto &value : connection_values) {
  21749. req.headers.emplace("Connection", value);
  21750. }
  21751. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21752. req.headers.emplace("Sec-WebSocket-Version", "13");
  21753. return req;
  21754. };
  21755. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21756. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21757. EXPECT_TRUE(
  21758. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21759. EXPECT_TRUE(
  21760. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21761. EXPECT_TRUE(
  21762. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21763. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21764. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21765. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21766. EXPECT_FALSE(
  21767. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21768. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21769. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21770. }
  21771. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21772. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21773. // asks recipients to match each protocol-name case-insensitively, and RFC
  21774. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21775. // client naming websocket alongside another protocol, or on a second field
  21776. // line, is offering websocket; a value that merely contains "websocket" as a
  21777. // substring is a different protocol name and is not.
  21778. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21779. Request req;
  21780. req.method = "GET";
  21781. for (const auto &value : upgrade_values) {
  21782. req.headers.emplace("Upgrade", value);
  21783. }
  21784. req.headers.emplace("Connection", "Upgrade");
  21785. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21786. req.headers.emplace("Sec-WebSocket-Version", "13");
  21787. return req;
  21788. };
  21789. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21790. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21791. EXPECT_TRUE(
  21792. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21793. EXPECT_TRUE(
  21794. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21795. EXPECT_TRUE(
  21796. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21797. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21798. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21799. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21800. EXPECT_FALSE(
  21801. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21802. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21803. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21804. }
  21805. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21806. Server svr;
  21807. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21808. auto port = svr.bind_to_any_port("localhost");
  21809. std::thread t([&]() { svr.listen_after_bind(); });
  21810. auto se = detail::scope_exit([&] {
  21811. svr.stop();
  21812. t.join();
  21813. });
  21814. svr.wait_until_ready();
  21815. Headers headers = {{"Upgrade", "websocket"},
  21816. {"Connection", "notupgrade"},
  21817. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21818. {"Sec-WebSocket-Version", "13"}};
  21819. Client cli("localhost", port);
  21820. auto res = cli.Get("/ws", headers);
  21821. // The route exists only as a WebSocket route, so a request that fails the
  21822. // handshake check falls through to ordinary routing.
  21823. ASSERT_TRUE(res);
  21824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21825. }
  21826. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21827. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21828. // Connection value is the only thing left for the client to reject.
  21829. Server svr;
  21830. svr.Get("/ws", [](const Request &req, Response &res) {
  21831. res.status = StatusCode::SwitchingProtocol_101;
  21832. res.set_header("Upgrade", "websocket");
  21833. res.set_header("Connection", "notupgrade");
  21834. res.set_header("Sec-WebSocket-Accept",
  21835. detail::websocket_accept_key(
  21836. req.get_header_value("Sec-WebSocket-Key")));
  21837. });
  21838. auto port = svr.bind_to_any_port("localhost");
  21839. std::thread t([&]() { svr.listen_after_bind(); });
  21840. auto se = detail::scope_exit([&] {
  21841. svr.stop();
  21842. t.join();
  21843. });
  21844. svr.wait_until_ready();
  21845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21846. auto res = client.connect();
  21847. EXPECT_FALSE(res);
  21848. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21849. EXPECT_FALSE(client.is_open());
  21850. }
  21851. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21852. Server svr;
  21853. svr.Get("/ws", [](const Request &req, Response &res) {
  21854. res.status = StatusCode::SwitchingProtocol_101;
  21855. res.set_header("Upgrade", "websocket");
  21856. res.set_header("Connection", "Upgrade");
  21857. res.set_header("Sec-WebSocket-Accept",
  21858. detail::websocket_accept_key(
  21859. req.get_header_value("Sec-WebSocket-Key")));
  21860. res.set_header("Sec-WebSocket-Protocol", "admin");
  21861. });
  21862. auto port = svr.bind_to_any_port("localhost");
  21863. std::thread t([&]() { svr.listen_after_bind(); });
  21864. auto se = detail::scope_exit([&] {
  21865. svr.stop();
  21866. t.join();
  21867. });
  21868. svr.wait_until_ready();
  21869. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21870. // Server selects a subprotocol the client never offered
  21871. {
  21872. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21873. ws::WebSocketClient client(url, headers);
  21874. auto res = client.connect();
  21875. EXPECT_FALSE(res);
  21876. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21877. EXPECT_FALSE(client.is_open());
  21878. EXPECT_TRUE(client.subprotocol().empty());
  21879. }
  21880. // Client offered none but the server named one anyway
  21881. {
  21882. ws::WebSocketClient client(url);
  21883. auto res = client.connect();
  21884. EXPECT_FALSE(res);
  21885. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21886. EXPECT_FALSE(client.is_open());
  21887. EXPECT_TRUE(client.subprotocol().empty());
  21888. }
  21889. }
  21890. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21891. // The socket path doubles as the URL host, so it must not contain '/'.
  21892. const char *shard = getenv("GTEST_SHARD_INDEX");
  21893. const std::string sock_path =
  21894. shard ? std::string("httplib-ws-") + shard + ".sock"
  21895. : std::string("httplib-ws.sock");
  21896. std::remove(sock_path.c_str());
  21897. Server svr;
  21898. std::mutex mtx;
  21899. std::string received_host;
  21900. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21901. {
  21902. std::lock_guard<std::mutex> lock(mtx);
  21903. received_host = req.get_header_value("Host");
  21904. }
  21905. std::string msg;
  21906. while (ws.read(msg)) {
  21907. ws.send(msg);
  21908. }
  21909. });
  21910. svr.set_address_family(AF_UNIX);
  21911. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21912. auto se = detail::scope_exit([&] {
  21913. svr.stop();
  21914. t.join();
  21915. std::remove(sock_path.c_str());
  21916. });
  21917. svr.wait_until_ready();
  21918. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21919. client.set_address_family(AF_UNIX);
  21920. ASSERT_TRUE(client.connect());
  21921. ASSERT_TRUE(client.send("hello"));
  21922. std::string msg;
  21923. ASSERT_TRUE(client.read(msg));
  21924. client.close();
  21925. {
  21926. std::lock_guard<std::mutex> lock(mtx);
  21927. // There is no host:port for a Unix socket, so the same "localhost"
  21928. // placeholder the HTTP client uses is expected.
  21929. EXPECT_EQ("localhost", received_host);
  21930. }
  21931. }
  21932. // Two threads must never parse WebSocket frames from the same stream.
  21933. // close() used to read the peer's Close reply with its own frame read, so it
  21934. // raced a reader thread that was in the middle of a payload: the payload loop
  21935. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21936. // so bytes taken by close() were replaced with bytes from further along the
  21937. // stream. The message kept its length and silently changed content.
  21938. //
  21939. // The raw peer below sends a frame header plus part of the payload, waits for
  21940. // the handler to call close(), and only then sends the rest. Whichever thread
  21941. // would win the race for those bytes, the message must arrive intact, because
  21942. // close() must not touch the stream while read() owns it.
  21943. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21944. #ifndef _WIN32
  21945. signal(SIGPIPE, SIG_IGN);
  21946. #endif
  21947. const size_t payload_len = 120; // fits the 7-bit length field
  21948. const size_t prefix_len = 8;
  21949. const int attempts = 8;
  21950. std::string expected(payload_len, '\0');
  21951. for (size_t i = 0; i < payload_len; i++) {
  21952. expected[i] = static_cast<char>('a' + i % 26);
  21953. }
  21954. std::atomic<bool> peer_stalled{false};
  21955. std::atomic<bool> handler_done{false};
  21956. std::mutex received_mutex;
  21957. std::vector<std::string> received;
  21958. // Bound every wait, so a regression fails the test instead of hanging the
  21959. // suite.
  21960. auto wait_for = [](const std::atomic<bool> &flag) {
  21961. for (int i = 0; i < 500 && !flag; i++) {
  21962. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21963. }
  21964. };
  21965. Server svr;
  21966. svr.set_websocket_ping_interval(0);
  21967. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21968. std::thread reader([&]() {
  21969. std::string msg;
  21970. while (ws.read(msg)) {
  21971. std::lock_guard<std::mutex> guard(received_mutex);
  21972. received.push_back(msg);
  21973. }
  21974. });
  21975. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21976. // inside read_websocket_frame() when close() runs.
  21977. wait_for(peer_stalled);
  21978. ws.close();
  21979. reader.join();
  21980. handler_done = true;
  21981. });
  21982. auto port = svr.bind_to_any_port("127.0.0.1");
  21983. std::thread t([&]() { svr.listen_after_bind(); });
  21984. auto se = detail::scope_exit([&] {
  21985. svr.stop();
  21986. t.join();
  21987. });
  21988. svr.wait_until_ready();
  21989. auto send_bytes = [](socket_t s, const std::string &data) {
  21990. #ifdef _WIN32
  21991. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21992. #else
  21993. auto n = ::send(s, data.data(), data.size(), 0);
  21994. #endif
  21995. return n == static_cast<decltype(n)>(data.size());
  21996. };
  21997. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21998. // Every length used here fits the 7-bit length field.
  21999. auto masked_header = [](uint8_t first_byte, size_t len) {
  22000. std::string h;
  22001. h += static_cast<char>(first_byte);
  22002. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22003. h.append(4, '\0'); // mask key
  22004. return h;
  22005. };
  22006. for (int attempt = 0; attempt < attempts; attempt++) {
  22007. peer_stalled = false;
  22008. handler_done = false;
  22009. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22010. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22011. auto se_sock = detail::scope_exit([&] {
  22012. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22013. });
  22014. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22015. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22016. sockaddr_in addr{};
  22017. addr.sin_family = AF_INET;
  22018. addr.sin_port = htons(static_cast<uint16_t>(port));
  22019. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22020. ASSERT_EQ(
  22021. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22022. << "attempt " << attempt;
  22023. ASSERT_TRUE(send_bytes(sock,
  22024. "GET /ws HTTP/1.1\r\n"
  22025. "Host: 127.0.0.1\r\n"
  22026. "Upgrade: websocket\r\n"
  22027. "Connection: Upgrade\r\n"
  22028. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22029. "Sec-WebSocket-Version: 13\r\n"
  22030. "\r\n"))
  22031. << "attempt " << attempt;
  22032. std::string response;
  22033. while (response.find("\r\n\r\n") == std::string::npos) {
  22034. char buf[512];
  22035. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22036. if (n <= 0) { break; }
  22037. response.append(buf, static_cast<size_t>(n));
  22038. }
  22039. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22040. << "attempt " << attempt;
  22041. // Send the header of a Binary message but only the first prefix_len bytes
  22042. // of its payload, leaving the reader thread stalled inside the payload.
  22043. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22044. expected.substr(0, prefix_len)))
  22045. << "attempt " << attempt;
  22046. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22047. peer_stalled = true;
  22048. // Let close() send its Close frame and park in its own read before the
  22049. // rest of the payload arrives, so both threads are waiting for it.
  22050. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22051. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22052. close_frame += static_cast<char>(0x03); // status 1000
  22053. close_frame += static_cast<char>(0xE8);
  22054. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22055. << "attempt " << attempt;
  22056. // Closing the peer releases the reader thread even on the buggy path,
  22057. // where it waits for bytes another thread already consumed.
  22058. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22059. detail::close_socket(sock);
  22060. sock = INVALID_SOCKET;
  22061. wait_for(handler_done);
  22062. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22063. }
  22064. std::lock_guard<std::mutex> guard(received_mutex);
  22065. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22066. << "a message in flight when close() ran was dropped";
  22067. for (size_t i = 0; i < received.size(); i++) {
  22068. EXPECT_EQ(expected, received[i]) << "message " << i;
  22069. }
  22070. }
  22071. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22072. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22073. protected:
  22074. void SetUp() override {
  22075. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22076. SERVER_PRIVATE_KEY_FILE);
  22077. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22078. std::string msg;
  22079. ws::ReadResult ret;
  22080. while ((ret = ws.read(msg))) {
  22081. if (ret == ws::Binary) {
  22082. ws.send(msg.data(), msg.size());
  22083. } else {
  22084. ws.send(msg);
  22085. }
  22086. }
  22087. });
  22088. port_ = server_->bind_to_any_port(HOST);
  22089. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22090. server_->wait_until_ready();
  22091. }
  22092. void TearDown() override {
  22093. server_->stop();
  22094. if (server_thread_.joinable()) { server_thread_.join(); }
  22095. }
  22096. std::unique_ptr<SSLServer> server_;
  22097. std::thread server_thread_;
  22098. int port_ = 0;
  22099. };
  22100. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22101. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22102. "/ws-echo");
  22103. client.enable_server_certificate_verification(false);
  22104. ASSERT_TRUE(client.connect());
  22105. ASSERT_TRUE(client.is_open());
  22106. ASSERT_TRUE(client.send("Hello WSS"));
  22107. std::string msg;
  22108. EXPECT_EQ(ws::Text, client.read(msg));
  22109. EXPECT_EQ("Hello WSS", msg);
  22110. client.close();
  22111. }
  22112. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22113. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22114. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22115. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22116. // client (without calling close() first) is the only path that runs
  22117. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22118. // bug exactly.
  22119. //
  22120. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22121. // when linked against an instrumented libssl; run under Valgrind to catch it
  22122. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22123. // suite (the freed session otherwise stalls on the close handshake) — this test
  22124. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22125. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22126. {
  22127. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22128. "/ws-echo");
  22129. client.enable_server_certificate_verification(false);
  22130. client.set_read_timeout(2, 0);
  22131. client.set_write_timeout(2, 0);
  22132. ASSERT_TRUE(client.connect());
  22133. ASSERT_TRUE(client.is_open());
  22134. ASSERT_TRUE(client.send("still open"));
  22135. // Intentionally do NOT call client.close(): leaving scope runs
  22136. // shutdown_and_close() with the WebSocket still open, which must send the
  22137. // close frame while the TLS session is still alive.
  22138. }
  22139. }
  22140. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22141. // shutdown_and_close() at the start of connect(), reproducing the same
  22142. // use-after-free within the test body rather than at scope exit. The second
  22143. // connect must succeed and echo, proving the close handshake ran over a live
  22144. // session. See the note above about memory-tool requirements.
  22145. TEST_F(WebSocketSSLIntegrationTest,
  22146. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22147. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22148. "/ws-echo");
  22149. client.enable_server_certificate_verification(false);
  22150. client.set_read_timeout(2, 0);
  22151. client.set_write_timeout(2, 0);
  22152. ASSERT_TRUE(client.connect());
  22153. ASSERT_TRUE(client.is_open());
  22154. ASSERT_TRUE(client.send("still open"));
  22155. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22156. // the still-open connection, which must not touch a freed TLS session.
  22157. ASSERT_TRUE(client.connect());
  22158. ASSERT_TRUE(client.is_open());
  22159. ASSERT_TRUE(client.send("after reconnect"));
  22160. std::string msg;
  22161. EXPECT_EQ(ws::Text, client.read(msg));
  22162. EXPECT_EQ("after reconnect", msg);
  22163. client.close();
  22164. }
  22165. #endif
  22166. #ifdef CPPHTTPLIB_SSL_ENABLED
  22167. class WebSocketSSLCATest : public ::testing::Test {
  22168. protected:
  22169. void SetUp() override {
  22170. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22171. SERVER_PRIVATE_KEY_FILE);
  22172. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22173. std::string msg;
  22174. while (ws.read(msg)) {
  22175. ws.send(msg);
  22176. }
  22177. });
  22178. port_ = server_->bind_to_any_port("127.0.0.1");
  22179. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22180. server_->wait_until_ready();
  22181. }
  22182. void TearDown() override {
  22183. server_->stop();
  22184. if (server_thread_.joinable()) { server_thread_.join(); }
  22185. }
  22186. std::string url() const {
  22187. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22188. }
  22189. std::unique_ptr<SSLServer> server_;
  22190. std::thread server_thread_;
  22191. int port_ = 0;
  22192. };
  22193. // A custom CA loaded as PEM verifies the server with full certificate
  22194. // verification enabled
  22195. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22196. ws::WebSocketClient client(url());
  22197. std::string cert;
  22198. read_file(SERVER_CERT2_FILE, cert);
  22199. client.load_ca_cert_store(cert.c_str(), cert.size());
  22200. ASSERT_TRUE(client.connect());
  22201. ASSERT_TRUE(client.send("hello"));
  22202. std::string msg;
  22203. EXPECT_EQ(ws::Text, client.read(msg));
  22204. EXPECT_EQ("hello", msg);
  22205. client.close();
  22206. }
  22207. // A custom CA that does not cover the server must fail verification (the
  22208. // custom CA is exclusive; system certs are not loaded alongside it)
  22209. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22210. ws::WebSocketClient client(url());
  22211. std::string cert;
  22212. read_file(CLIENT_CA_CERT_FILE, cert);
  22213. client.load_ca_cert_store(cert.c_str(), cert.size());
  22214. auto res = client.connect();
  22215. ASSERT_FALSE(res);
  22216. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22217. EXPECT_EQ(-1, res.status());
  22218. EXPECT_NE(0u, res.ssl_backend_error());
  22219. }
  22220. // The same CA as a file path rather than PEM in memory
  22221. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22222. ws::WebSocketClient client(url());
  22223. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22224. ASSERT_TRUE(client.connect());
  22225. ASSERT_TRUE(client.send("hello"));
  22226. std::string msg;
  22227. EXPECT_EQ(ws::Text, client.read(msg));
  22228. EXPECT_EQ("hello", msg);
  22229. client.close();
  22230. }
  22231. // ...and a CA file that does not cover the server still fails, so it is the
  22232. // path above that decides the outcome
  22233. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22234. ws::WebSocketClient client(url());
  22235. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22236. ASSERT_FALSE(client.connect());
  22237. }
  22238. // Regression test: reconnecting with a native custom CA store used to reuse
  22239. // a store handle the previous TLS context had already freed (use-after-free
  22240. // under the OpenSSL backend). The context now lives as long as the client.
  22241. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22242. ws::WebSocketClient client(url());
  22243. std::string cert;
  22244. read_file(SERVER_CERT2_FILE, cert);
  22245. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22246. ASSERT_TRUE(client.connect());
  22247. client.close();
  22248. ASSERT_TRUE(client.connect());
  22249. ASSERT_TRUE(client.send("again"));
  22250. std::string msg;
  22251. EXPECT_EQ(ws::Text, client.read(msg));
  22252. EXPECT_EQ("again", msg);
  22253. client.close();
  22254. }
  22255. // Regression test: a certificate with a trusted chain but no identity match
  22256. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22257. // verification entirely for IP hosts, so this connection succeeded there.
  22258. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22259. // chain verification while the identity check must still fail.
  22260. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22262. ASSERT_TRUE(svr.is_valid());
  22263. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22264. std::string msg;
  22265. while (ws.read(msg)) {
  22266. ws.send(msg);
  22267. }
  22268. });
  22269. auto port = svr.bind_to_any_port("127.0.0.1");
  22270. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22271. auto se = detail::scope_exit([&] {
  22272. svr.stop();
  22273. t.join();
  22274. });
  22275. svr.wait_until_ready();
  22276. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22277. "/echo");
  22278. std::string cert;
  22279. read_file(SERVER_CERT_FILE, cert);
  22280. client.load_ca_cert_store(cert.c_str(), cert.size());
  22281. ASSERT_FALSE(client.connect());
  22282. }
  22283. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22284. // SNI, so nothing binds the host name to the TLS session. These bind the
  22285. // server to "localhost" instead, the only shape that exercises the SNI and
  22286. // hostname-verification path with certificate verification left enabled.
  22287. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22288. protected:
  22289. void Start(const char *cert_file) {
  22290. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22291. SERVER_PRIVATE_KEY_FILE);
  22292. ASSERT_TRUE(server_->is_valid());
  22293. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22294. std::string msg;
  22295. while (ws.read(msg)) {
  22296. ws.send(msg);
  22297. }
  22298. });
  22299. port_ = server_->bind_to_any_port("localhost");
  22300. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22301. server_->wait_until_ready();
  22302. }
  22303. void TearDown() override {
  22304. if (server_) { server_->stop(); }
  22305. if (server_thread_.joinable()) { server_thread_.join(); }
  22306. }
  22307. std::string url() const {
  22308. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22309. }
  22310. std::unique_ptr<SSLServer> server_;
  22311. std::thread server_thread_;
  22312. int port_ = 0;
  22313. };
  22314. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22315. // out and the connection is usable
  22316. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22317. Start(SERVER_CERT2_FILE);
  22318. ws::WebSocketClient client(url());
  22319. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22320. ASSERT_TRUE(client.connect());
  22321. ASSERT_TRUE(client.send("hello"));
  22322. std::string msg;
  22323. EXPECT_EQ(ws::Text, client.read(msg));
  22324. EXPECT_EQ("hello", msg);
  22325. client.close();
  22326. }
  22327. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22328. // while the identity check must still reject "localhost"
  22329. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22330. Start(SERVER_CERT_FILE);
  22331. ws::WebSocketClient client(url());
  22332. client.set_ca_cert_path(SERVER_CERT_FILE);
  22333. auto res = client.connect();
  22334. ASSERT_FALSE(res);
  22335. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22336. EXPECT_EQ(-1, res.status());
  22337. }
  22338. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22339. // disabled: the chain is still checked, only the identity check is skipped
  22340. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22341. Start(SERVER_CERT_FILE);
  22342. ws::WebSocketClient client(url());
  22343. client.set_ca_cert_path(SERVER_CERT_FILE);
  22344. client.enable_server_hostname_verification(false);
  22345. ASSERT_TRUE(client.connect());
  22346. ASSERT_TRUE(client.send("hello"));
  22347. std::string msg;
  22348. EXPECT_EQ(ws::Text, client.read(msg));
  22349. EXPECT_EQ("hello", msg);
  22350. client.close();
  22351. }
  22352. // A CA that did not sign the server certificate fails the chain, even though
  22353. // the name would match
  22354. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22355. Start(SERVER_CERT2_FILE);
  22356. ws::WebSocketClient client(url());
  22357. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22358. ASSERT_FALSE(client.connect());
  22359. }
  22360. // With verification disabled, neither the chain nor the name is checked
  22361. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22362. Start(SERVER_CERT_FILE);
  22363. ws::WebSocketClient client(url());
  22364. client.enable_server_certificate_verification(false);
  22365. ASSERT_TRUE(client.connect());
  22366. ASSERT_TRUE(client.send("hello"));
  22367. std::string msg;
  22368. EXPECT_EQ(ws::Text, client.read(msg));
  22369. EXPECT_EQ("hello", msg);
  22370. client.close();
  22371. }
  22372. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22373. protected:
  22374. void SetUp() override {
  22375. server_ = httplib::detail::make_unique<SSLServer>(
  22376. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22377. ASSERT_TRUE(server_->is_valid());
  22378. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22379. std::string msg;
  22380. while (ws.read(msg)) {
  22381. ws.send(msg);
  22382. }
  22383. });
  22384. port_ = server_->bind_to_any_port("localhost");
  22385. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22386. server_->wait_until_ready();
  22387. }
  22388. void TearDown() override {
  22389. server_->stop();
  22390. if (server_thread_.joinable()) { server_thread_.join(); }
  22391. }
  22392. std::string url() const {
  22393. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22394. }
  22395. void ConnectWithClientCert(const std::string &client_cert_file,
  22396. const std::string &client_private_key_file,
  22397. const char *private_key_password) {
  22398. std::string cert_pem, key_pem;
  22399. read_file(client_cert_file, cert_pem);
  22400. read_file(client_private_key_file, key_pem);
  22401. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22402. key_pem.c_str(), key_pem.size(),
  22403. private_key_password};
  22404. ws::WebSocketClient client(url(), pem);
  22405. ASSERT_TRUE(client.is_valid());
  22406. client.enable_server_certificate_verification(false);
  22407. ASSERT_TRUE(client.connect());
  22408. ASSERT_TRUE(client.send("hello"));
  22409. std::string msg;
  22410. EXPECT_EQ(ws::Text, client.read(msg));
  22411. EXPECT_EQ("hello", msg);
  22412. client.close();
  22413. }
  22414. std::unique_ptr<SSLServer> server_;
  22415. std::thread server_thread_;
  22416. int port_ = 0;
  22417. };
  22418. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22419. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22420. }
  22421. // Control for the tests above: the fixture's server really does require a
  22422. // client certificate, so it is the PEM the constructor installed that decides
  22423. // the outcome.
  22424. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22425. ws::WebSocketClient client(url());
  22426. ASSERT_TRUE(client.is_valid());
  22427. client.enable_server_certificate_verification(false);
  22428. EXPECT_FALSE(client.connect());
  22429. }
  22430. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22431. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22432. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22433. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22434. }
  22435. #endif
  22436. #if !defined(_WIN32)
  22437. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22438. auto secret_dir = std::string("./symlink_test_secret");
  22439. auto served_dir = std::string("./symlink_test_served");
  22440. auto secret_file = secret_dir + "/secret.txt";
  22441. auto symlink_path = served_dir + "/escape";
  22442. // Setup: create directories and files
  22443. mkdir(secret_dir.c_str(), 0755);
  22444. mkdir(served_dir.c_str(), 0755);
  22445. {
  22446. std::ofstream ofs(secret_file);
  22447. ofs << "SECRET_DATA";
  22448. }
  22449. // Create symlink using absolute path so it resolves correctly
  22450. #ifdef PATH_MAX
  22451. char abs_secret[PATH_MAX];
  22452. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22453. #else
  22454. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22455. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22456. ASSERT_NE(nullptr, abs_secret);
  22457. #endif
  22458. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22459. auto se = detail::scope_exit([&] {
  22460. unlink(symlink_path.c_str());
  22461. unlink(secret_file.c_str());
  22462. rmdir(served_dir.c_str());
  22463. rmdir(secret_dir.c_str());
  22464. });
  22465. Server svr;
  22466. svr.set_mount_point("/", served_dir);
  22467. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22468. auto se2 = detail::scope_exit([&] {
  22469. svr.stop();
  22470. listen_thread.join();
  22471. });
  22472. svr.wait_until_ready();
  22473. Client cli("localhost", PORT);
  22474. // Symlink pointing outside base dir should be blocked
  22475. auto res = cli.Get("/escape/secret.txt");
  22476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22477. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22478. }
  22479. #endif
  22480. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22481. // "GET /smuggled" request), reads the first response, and only then sends the
  22482. // embedded request as the body. Returns how many times /smuggled ran.
  22483. //
  22484. // The body is sent AFTER receiving the first response (as in the original
  22485. // PoC) so that the stream_line_reader cannot buffer it together with the
  22486. // headers of the first request.
  22487. static int count_smuggled_requests(const std::string &outer_head,
  22488. std::string &first_response) {
  22489. Server svr;
  22490. svr.set_mount_point("/", "./www");
  22491. std::atomic<int> smuggled_count(0);
  22492. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22493. smuggled_count++;
  22494. res.set_content("oops", "text/plain");
  22495. });
  22496. svr.Post("/post", [&](const Request &req, Response &res) {
  22497. res.set_content(req.body, "text/plain");
  22498. });
  22499. auto port = svr.bind_to_any_port("localhost");
  22500. thread t = thread([&] { svr.listen_after_bind(); });
  22501. auto se = detail::scope_exit([&] {
  22502. svr.stop();
  22503. t.join();
  22504. });
  22505. svr.wait_until_ready();
  22506. auto error = Error::Success;
  22507. auto sock = detail::create_client_socket(
  22508. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22509. /*connection_timeout_sec=*/2, 0,
  22510. /*read_timeout_sec=*/2, 0,
  22511. /*write_timeout_sec=*/2, 0, std::string(), error);
  22512. EXPECT_NE(INVALID_SOCKET, sock);
  22513. if (sock == INVALID_SOCKET) { return -1; }
  22514. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22515. // The "smuggled" request will be sent as the body of the outer request
  22516. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22517. "Host: localhost\r\n"
  22518. "Connection: close\r\n"
  22519. "\r\n";
  22520. auto head = outer_head;
  22521. auto len = std::to_string(smuggled.size());
  22522. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22523. pos = head.find("{len}", pos + len.size())) {
  22524. head.replace(pos, 5, len);
  22525. }
  22526. // Step 1: Send only the outer request headers (no body yet)
  22527. auto sent = send(sock, head.data(), head.size(), 0);
  22528. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22529. // Step 2: Read the first response
  22530. char buf[4096];
  22531. for (;;) {
  22532. auto n = recv(sock, buf, sizeof(buf), 0);
  22533. if (n <= 0) break;
  22534. first_response.append(buf, static_cast<size_t>(n));
  22535. // Stop once we have a complete response (headers + body)
  22536. auto hdr_end = first_response.find("\r\n\r\n");
  22537. if (hdr_end != std::string::npos) {
  22538. // Check for Content-Length to know when the body is complete
  22539. auto cl_pos = first_response.find("Content-Length:");
  22540. if (cl_pos != std::string::npos) {
  22541. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22542. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22543. auto cl = std::stoul(
  22544. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22545. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22546. } else {
  22547. break; // No Content-Length, assume headers-only response
  22548. }
  22549. }
  22550. }
  22551. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22552. // vulnerable server the keep-alive loop reads this as a second request. The
  22553. // server may already have closed the connection, so the result is ignored.
  22554. send(sock, smuggled.data(), smuggled.size(), 0);
  22555. // Half-close so that a server which drained the body sees EOF and closes,
  22556. // instead of the read below waiting for the read timeout.
  22557. #ifdef _WIN32
  22558. ::shutdown(sock, SD_SEND);
  22559. #else
  22560. ::shutdown(sock, SHUT_WR);
  22561. #endif
  22562. // Step 4: Read until the server closes the connection
  22563. for (;;) {
  22564. auto n = recv(sock, buf, sizeof(buf), 0);
  22565. if (n <= 0) break;
  22566. }
  22567. return smuggled_count.load();
  22568. }
  22569. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22570. // A GET request with Content-Length to a static file handler must have its
  22571. // body drained before the keep-alive connection is reused. Otherwise the
  22572. // unread body bytes are interpreted as the next HTTP request.
  22573. std::string first_response;
  22574. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22575. "Host: localhost\r\n"
  22576. "Content-Length: {len}\r\n"
  22577. "\r\n",
  22578. first_response));
  22579. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22580. }
  22581. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22582. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22583. // be answered with 400 and the connection closed. Treating it as "no body"
  22584. // leaves the body to be parsed as the next request.
  22585. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22586. const char *targets[] = {
  22587. "GET /file", // handler that never reads the body
  22588. "GET /not-found", // no handler matches (404)
  22589. "POST /post", // handler that reads the body
  22590. };
  22591. for (auto target : targets) {
  22592. for (auto value : values) {
  22593. std::string first_response;
  22594. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22595. " HTTP/1.1\r\n"
  22596. "Host: localhost\r\n"
  22597. "Content-Length: " +
  22598. value + "\r\n\r\n",
  22599. first_response))
  22600. << target << " with Content-Length: " << value;
  22601. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22602. << target << " with Content-Length: " << value;
  22603. }
  22604. }
  22605. }
  22606. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22607. // A 400 for an unparseable request line leaves the rest of the message
  22608. // unread, so the connection must be closed rather than reused.
  22609. std::string first_response;
  22610. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22611. "Host: localhost\r\n"
  22612. "Content-Length: {len}\r\n"
  22613. "\r\n",
  22614. first_response));
  22615. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22616. }
  22617. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22618. // Same as above for a header block that fails to parse.
  22619. std::string first_response;
  22620. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22621. "Host: localhost\r\n"
  22622. "Bad Header\r\n"
  22623. "Content-Length: {len}\r\n"
  22624. "\r\n",
  22625. first_response));
  22626. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22627. }
  22628. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22629. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22630. // server must not read another request on that connection, even when the
  22631. // request had no body to drain.
  22632. std::string first_response;
  22633. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22634. "Host: localhost\r\n"
  22635. "\r\n",
  22636. first_response));
  22637. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22638. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22639. }
  22640. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22641. // A content reader that stops early leaves the stream inside the body.
  22642. // Draining the whole Content-Length from there, or reading the body again,
  22643. // reads into the next request, and whatever follows is parsed as a request
  22644. // of its own.
  22645. Server svr;
  22646. std::atomic<int> smuggled_count(0);
  22647. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22648. svr.Post("/upload", [](const Request &req, Response &res,
  22649. const ContentReader &content_reader) {
  22650. // Stop at the last chunk, so the whole body has been read however it
  22651. // arrives.
  22652. auto length = req.get_header_value_u64("Content-Length");
  22653. size_t total = 0;
  22654. auto consumed = content_reader([&](const char *, size_t n) {
  22655. total += n;
  22656. return total < length;
  22657. });
  22658. EXPECT_FALSE(consumed);
  22659. if (req.has_param("retry")) {
  22660. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22661. }
  22662. // Replace the 400 the aborted read set, which would close the connection.
  22663. res.set_redirect("/done");
  22664. });
  22665. auto port = svr.bind_to_any_port(HOST);
  22666. thread t = thread([&] { svr.listen_after_bind(); });
  22667. auto se = detail::scope_exit([&] {
  22668. svr.stop();
  22669. t.join();
  22670. });
  22671. svr.wait_until_ready();
  22672. // A front end sees the second request as a POST whose body is the GET. The
  22673. // first body is as long as the POST's headers, so draining it again reads
  22674. // exactly those and leaves the GET to be parsed next.
  22675. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22676. "Host: localhost\r\n"
  22677. "\r\n";
  22678. std::string second_head = "POST /post HTTP/1.1\r\n"
  22679. "Host: localhost\r\n"
  22680. "Content-Length: " +
  22681. std::to_string(inner.size()) +
  22682. "\r\n"
  22683. "\r\n";
  22684. for (auto target : {"/upload", "/upload?retry"}) {
  22685. smuggled_count = 0;
  22686. std::string request = "POST " + std::string(target) +
  22687. " HTTP/1.1\r\n"
  22688. "Host: localhost\r\n"
  22689. "Content-Length: " +
  22690. std::to_string(second_head.size()) +
  22691. "\r\n"
  22692. "\r\n" +
  22693. std::string(second_head.size(), 'A') + second_head +
  22694. inner;
  22695. std::string response;
  22696. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22697. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22698. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22699. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22700. EXPECT_EQ(0, smuggled_count.load()) << target;
  22701. }
  22702. }
  22703. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22704. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22705. // must be rejected with 400 Bad Request.
  22706. Server svr;
  22707. svr.Post("/test", [&](const Request &, Response &res) {
  22708. res.set_content("ok", "text/plain");
  22709. });
  22710. thread t = thread([&] { svr.listen(HOST, PORT); });
  22711. auto se = detail::scope_exit([&] {
  22712. svr.stop();
  22713. t.join();
  22714. ASSERT_FALSE(svr.is_running());
  22715. });
  22716. svr.wait_until_ready();
  22717. // Exact "chunked"
  22718. {
  22719. auto req = "POST /test HTTP/1.1\r\n"
  22720. "Host: localhost\r\n"
  22721. "Content-Length: 5\r\n"
  22722. "Transfer-Encoding: chunked\r\n"
  22723. "Connection: close\r\n"
  22724. "\r\n"
  22725. "hello";
  22726. std::string response;
  22727. ASSERT_TRUE(send_request(1, req, &response));
  22728. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22729. response.substr(0, response.find("\r\n")));
  22730. }
  22731. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22732. {
  22733. auto req = "POST /test HTTP/1.1\r\n"
  22734. "Host: localhost\r\n"
  22735. "Content-Length: 5\r\n"
  22736. "Transfer-Encoding: gzip, chunked\r\n"
  22737. "Connection: close\r\n"
  22738. "\r\n"
  22739. "hello";
  22740. std::string response;
  22741. ASSERT_TRUE(send_request(1, req, &response));
  22742. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22743. response.substr(0, response.find("\r\n")));
  22744. }
  22745. }
  22746. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22747. Server svr;
  22748. svr.Post("/test", [&](const Request &, Response &res) {
  22749. res.set_content("ok", "text/plain");
  22750. });
  22751. thread t = thread([&] { svr.listen(HOST, PORT); });
  22752. auto se = detail::scope_exit([&] {
  22753. svr.stop();
  22754. t.join();
  22755. ASSERT_FALSE(svr.is_running());
  22756. });
  22757. svr.wait_until_ready();
  22758. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22759. // length cannot be determined, so the server must answer 400 and close
  22760. // rather than treat the request as bodyless and leave the body in the
  22761. // socket for the next request to pick up.
  22762. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22763. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22764. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22765. std::string response;
  22766. ASSERT_TRUE(send_request(1, req, &response));
  22767. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22768. response.substr(0, response.find("\r\n")))
  22769. << transfer_encoding;
  22770. }
  22771. // RFC 9110 5.3: the codings may also be split across several
  22772. // Transfer-Encoding lines, which combine in the order they were received.
  22773. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22774. // just like the single-line "chunked, gzip" above.
  22775. {
  22776. auto req = "POST /test HTTP/1.1\r\n"
  22777. "Host: localhost\r\n"
  22778. "Transfer-Encoding: chunked\r\n"
  22779. "Transfer-Encoding: gzip\r\n"
  22780. "\r\n"
  22781. "0\r\n\r\n";
  22782. std::string response;
  22783. ASSERT_TRUE(send_request(1, req, &response));
  22784. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22785. response.substr(0, response.find("\r\n")));
  22786. }
  22787. // A sequence ending in chunked stays valid.
  22788. auto req = "POST /test HTTP/1.1\r\n"
  22789. "Host: localhost\r\n"
  22790. "Transfer-Encoding: gzip, chunked\r\n"
  22791. "Connection: close\r\n"
  22792. "\r\n"
  22793. "0\r\n\r\n";
  22794. std::string response;
  22795. ASSERT_TRUE(send_request(1, req, &response));
  22796. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22797. // ...including when it is spread over several lines.
  22798. auto split_req = "POST /test HTTP/1.1\r\n"
  22799. "Host: localhost\r\n"
  22800. "Transfer-Encoding: gzip\r\n"
  22801. "Transfer-Encoding: chunked\r\n"
  22802. "Connection: close\r\n"
  22803. "\r\n"
  22804. "0\r\n\r\n";
  22805. std::string split_response;
  22806. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22807. EXPECT_EQ("HTTP/1.1 200 OK",
  22808. split_response.substr(0, split_response.find("\r\n")));
  22809. }
  22810. // Regression for issue #2450: a DELETE without Content-Length on a
  22811. // keep-alive connection must not let the post-response drain consume the
  22812. // next request's bytes.
  22813. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22814. Server svr;
  22815. std::atomic<int> delete_count(0);
  22816. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22817. delete_count++;
  22818. res.status = StatusCode::NoContent_204;
  22819. });
  22820. auto port = svr.bind_to_any_port(HOST);
  22821. thread t = thread([&] { svr.listen_after_bind(); });
  22822. auto se = detail::scope_exit([&] {
  22823. svr.stop();
  22824. t.join();
  22825. });
  22826. svr.wait_until_ready();
  22827. auto error = Error::Success;
  22828. auto sock = detail::create_client_socket(
  22829. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22830. /*connection_timeout_sec=*/2, 0,
  22831. /*read_timeout_sec=*/2, 0,
  22832. /*write_timeout_sec=*/2, 0, std::string(), error);
  22833. ASSERT_NE(INVALID_SOCKET, sock);
  22834. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22835. auto send_request_and_read_response = [&](const std::string &req,
  22836. std::string &out) -> bool {
  22837. auto sent = send(sock, req.data(), req.size(), 0);
  22838. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22839. char buf[4096];
  22840. for (;;) {
  22841. auto n = recv(sock, buf, sizeof(buf), 0);
  22842. if (n <= 0) { return !out.empty(); }
  22843. out.append(buf, static_cast<size_t>(n));
  22844. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22845. }
  22846. };
  22847. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22848. "Host: localhost\r\n"
  22849. "\r\n";
  22850. std::string resp1;
  22851. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22852. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22853. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22854. "Host: localhost\r\n"
  22855. "Connection: close\r\n"
  22856. "\r\n";
  22857. std::string resp2;
  22858. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22859. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22860. EXPECT_EQ(2, delete_count.load());
  22861. }
  22862. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22863. Server svr;
  22864. svr.Post("/ingest", [&](const Request &, Response &res,
  22865. const ContentReader &content_reader) {
  22866. auto consumed = content_reader([](const char *, size_t) { return false; });
  22867. EXPECT_FALSE(consumed);
  22868. res.status = StatusCode::Conflict_409;
  22869. res.set_header("Connection", "close");
  22870. });
  22871. auto port = svr.bind_to_any_port(HOST);
  22872. thread t = thread([&] { svr.listen_after_bind(); });
  22873. auto se = detail::scope_exit([&] {
  22874. svr.stop();
  22875. t.join();
  22876. });
  22877. svr.wait_until_ready();
  22878. auto error = Error::Success;
  22879. auto sock = detail::create_client_socket(
  22880. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22881. /*connection_timeout_sec=*/2, 0,
  22882. /*read_timeout_sec=*/1, 0,
  22883. /*write_timeout_sec=*/2, 0, std::string(), error);
  22884. ASSERT_NE(INVALID_SOCKET, sock);
  22885. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22886. std::string request = "POST /ingest HTTP/1.1\r\n"
  22887. "Host: localhost\r\n"
  22888. "Transfer-Encoding: chunked\r\n"
  22889. "\r\n"
  22890. "4\r\n"
  22891. "data\r\n";
  22892. auto sent = send(sock, request.data(), request.size(), 0);
  22893. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22894. std::string response;
  22895. ssize_t received = 0;
  22896. do {
  22897. char buf[4096];
  22898. received = recv(sock, buf, sizeof(buf), 0);
  22899. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22900. } while (received > 0);
  22901. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22902. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22903. EXPECT_EQ(0, received);
  22904. }
  22905. namespace no_proxy_test {
  22906. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22907. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22908. // calling listen().
  22909. class ScopedServer {
  22910. public:
  22911. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22912. ~ScopedServer() {
  22913. svr_.stop();
  22914. if (th_.joinable()) { th_.join(); }
  22915. }
  22916. Server &svr() { return svr_; }
  22917. int port() const { return port_; }
  22918. void listen() {
  22919. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22920. svr_.wait_until_ready();
  22921. }
  22922. private:
  22923. Server svr_;
  22924. std::thread th_;
  22925. int port_ = 0;
  22926. };
  22927. class ProxyAndTargetServers {
  22928. public:
  22929. ProxyAndTargetServers() {
  22930. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22931. proxy_hits_++;
  22932. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22933. res.set_content("via-proxy", "text/plain");
  22934. });
  22935. target_.Get(".*", [this](const Request &req, Response &res) {
  22936. target_hits_++;
  22937. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22938. res.set_content("direct", "text/plain");
  22939. });
  22940. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22941. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22942. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22943. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22944. proxy_mock_.wait_until_ready();
  22945. target_.wait_until_ready();
  22946. }
  22947. ~ProxyAndTargetServers() {
  22948. proxy_mock_.stop();
  22949. target_.stop();
  22950. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22951. if (target_thread_.joinable()) { target_thread_.join(); }
  22952. }
  22953. Server &proxy_mock() { return proxy_mock_; }
  22954. Server &target() { return target_; }
  22955. int proxy_port() const { return proxy_port_; }
  22956. int target_port() const { return target_port_; }
  22957. int proxy_hits() const { return proxy_hits_.load(); }
  22958. int target_hits() const { return target_hits_.load(); }
  22959. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22960. void reset_counters() {
  22961. proxy_hits_ = 0;
  22962. target_hits_ = 0;
  22963. last_had_proxy_authz_ = false;
  22964. }
  22965. private:
  22966. Server proxy_mock_;
  22967. Server target_;
  22968. std::thread proxy_thread_;
  22969. std::thread target_thread_;
  22970. int proxy_port_ = 0;
  22971. int target_port_ = 0;
  22972. std::atomic<int> proxy_hits_{0};
  22973. std::atomic<int> target_hits_{0};
  22974. std::atomic<bool> last_had_proxy_authz_{false};
  22975. };
  22976. inline std::unique_ptr<Client> make_client(const std::string &host,
  22977. ProxyAndTargetServers &s) {
  22978. auto cli = detail::make_unique<Client>(host, s.target_port());
  22979. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22980. cli->set_proxy("127.0.0.1", s.proxy_port());
  22981. return cli;
  22982. }
  22983. } // namespace no_proxy_test
  22984. using no_proxy_test::make_client;
  22985. using no_proxy_test::ProxyAndTargetServers;
  22986. TEST(NoProxyTest, ExactHostnameBypasses) {
  22987. ProxyAndTargetServers s;
  22988. auto cli = make_client("example.com", s);
  22989. cli->set_no_proxy({"example.com"});
  22990. auto res = cli->Get("/");
  22991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22992. EXPECT_EQ(0, s.proxy_hits());
  22993. EXPECT_EQ(1, s.target_hits());
  22994. }
  22995. TEST(NoProxyTest, SubdomainBypasses) {
  22996. ProxyAndTargetServers s;
  22997. auto cli = make_client("foo.example.com", s);
  22998. cli->set_no_proxy({"example.com"});
  22999. auto res = cli->Get("/");
  23000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23001. EXPECT_EQ(0, s.proxy_hits());
  23002. EXPECT_EQ(1, s.target_hits());
  23003. }
  23004. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23005. // Regression guard: "evilexample.com" must not be considered a subdomain
  23006. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23007. // check would let traffic bypass the proxy and leak credentials direct
  23008. // to the attacker host.
  23009. ProxyAndTargetServers s;
  23010. auto cli = make_client("evilexample.com", s);
  23011. cli->set_no_proxy({"example.com"});
  23012. auto res = cli->Get("/");
  23013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23014. EXPECT_GE(s.proxy_hits(), 1);
  23015. EXPECT_EQ(0, s.target_hits());
  23016. }
  23017. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23018. ProxyAndTargetServers s;
  23019. auto cli = make_client("example.com.evil.com", s);
  23020. cli->set_no_proxy({"example.com"});
  23021. auto res = cli->Get("/");
  23022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23023. EXPECT_GE(s.proxy_hits(), 1);
  23024. EXPECT_EQ(0, s.target_hits());
  23025. }
  23026. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23027. ProxyAndTargetServers s;
  23028. auto cli = make_client("example.com", s);
  23029. cli->set_no_proxy({".example.com"});
  23030. auto res = cli->Get("/");
  23031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23032. EXPECT_EQ(0, s.proxy_hits());
  23033. EXPECT_EQ(1, s.target_hits());
  23034. }
  23035. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23036. ProxyAndTargetServers s;
  23037. auto cli = make_client("Example.COM", s);
  23038. cli->set_no_proxy({"EXAMPLE.com"});
  23039. auto res = cli->Get("/");
  23040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23041. EXPECT_EQ(0, s.proxy_hits());
  23042. EXPECT_EQ(1, s.target_hits());
  23043. }
  23044. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23045. ProxyAndTargetServers s;
  23046. auto cli = make_client("example.com.", s);
  23047. cli->set_no_proxy({"example.com"});
  23048. auto res = cli->Get("/");
  23049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23050. EXPECT_EQ(0, s.proxy_hits());
  23051. EXPECT_EQ(1, s.target_hits());
  23052. }
  23053. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23054. // Trailing dots must be normalized on BOTH sides — host and entry.
  23055. // An implementation that only strips the host-side trailing dot would
  23056. // fail to match host "example.com" against entry "example.com." because
  23057. // a literal substring search would compare 11 chars against 12.
  23058. ProxyAndTargetServers s;
  23059. auto cli = make_client("example.com", s);
  23060. cli->set_no_proxy({"example.com."});
  23061. auto res = cli->Get("/");
  23062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23063. EXPECT_EQ(0, s.proxy_hits());
  23064. EXPECT_EQ(1, s.target_hits());
  23065. }
  23066. TEST(NoProxyTest, WildcardBypassesEverything) {
  23067. ProxyAndTargetServers s;
  23068. auto cli = make_client("anything.invalid.test", s);
  23069. cli->set_no_proxy({"*"});
  23070. auto res = cli->Get("/");
  23071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23072. EXPECT_EQ(0, s.proxy_hits());
  23073. EXPECT_EQ(1, s.target_hits());
  23074. }
  23075. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23076. ProxyAndTargetServers s;
  23077. Client cli("127.0.0.1", s.target_port());
  23078. cli.set_proxy("127.0.0.1", s.proxy_port());
  23079. cli.set_no_proxy({"127.0.0.1"});
  23080. auto res = cli.Get("/");
  23081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23082. EXPECT_EQ(0, s.proxy_hits());
  23083. EXPECT_EQ(1, s.target_hits());
  23084. }
  23085. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23086. ProxyAndTargetServers s;
  23087. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23088. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23089. cli.set_proxy("127.0.0.1", s.proxy_port());
  23090. cli.set_no_proxy({"::1"});
  23091. auto res = cli.Get("/");
  23092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23093. EXPECT_EQ(0, s.proxy_hits());
  23094. EXPECT_EQ(1, s.target_hits());
  23095. }
  23096. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23097. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23098. // must still be recognized as IPv6 for CIDR matching. Implementations
  23099. // that detect IPv6 only when the host begins with '[' would parse the
  23100. // host as a hostname and miss the match.
  23101. ProxyAndTargetServers s;
  23102. Client cli("fe80::1", s.target_port());
  23103. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23104. cli.set_proxy("127.0.0.1", s.proxy_port());
  23105. cli.set_no_proxy({"fe80::/10"});
  23106. auto res = cli.Get("/");
  23107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23108. EXPECT_EQ(0, s.proxy_hits());
  23109. EXPECT_EQ(1, s.target_hits());
  23110. }
  23111. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23112. ProxyAndTargetServers s;
  23113. Client cli("::1", s.target_port());
  23114. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23115. cli.set_proxy("127.0.0.1", s.proxy_port());
  23116. cli.set_no_proxy({"[::1]"});
  23117. auto res = cli.Get("/");
  23118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23119. EXPECT_EQ(0, s.proxy_hits());
  23120. EXPECT_EQ(1, s.target_hits());
  23121. }
  23122. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23123. ProxyAndTargetServers s;
  23124. Client cli("fe80::1", s.target_port());
  23125. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23126. cli.set_proxy("127.0.0.1", s.proxy_port());
  23127. cli.set_no_proxy({"[fe80::]/10"});
  23128. auto res = cli.Get("/");
  23129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23130. EXPECT_EQ(0, s.proxy_hits());
  23131. EXPECT_EQ(1, s.target_hits());
  23132. }
  23133. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23134. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23135. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23136. // tricks via address-family conversion.
  23137. ProxyAndTargetServers s;
  23138. Client cli("::ffff:127.0.0.1", s.target_port());
  23139. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23140. cli.set_proxy("127.0.0.1", s.proxy_port());
  23141. cli.set_no_proxy({"127.0.0.1"});
  23142. auto res = cli.Get("/");
  23143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23144. EXPECT_GE(s.proxy_hits(), 1);
  23145. EXPECT_EQ(0, s.target_hits());
  23146. }
  23147. TEST(NoProxyTest, IPv4CidrMatch) {
  23148. ProxyAndTargetServers s;
  23149. Client cli("127.0.0.1", s.target_port());
  23150. cli.set_proxy("127.0.0.1", s.proxy_port());
  23151. cli.set_no_proxy({"127.0.0.0/8"});
  23152. auto res = cli.Get("/");
  23153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23154. EXPECT_EQ(0, s.proxy_hits());
  23155. EXPECT_EQ(1, s.target_hits());
  23156. }
  23157. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23158. ProxyAndTargetServers s;
  23159. Client cli("127.0.0.1", s.target_port());
  23160. cli.set_proxy("127.0.0.1", s.proxy_port());
  23161. cli.set_no_proxy({"10.0.0.0/8"});
  23162. auto res = cli.Get("/");
  23163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23164. EXPECT_GE(s.proxy_hits(), 1);
  23165. EXPECT_EQ(0, s.target_hits());
  23166. }
  23167. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23168. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23169. // IPv4 target matches.
  23170. ProxyAndTargetServers s;
  23171. Client cli("127.0.0.1", s.target_port());
  23172. cli.set_proxy("127.0.0.1", s.proxy_port());
  23173. cli.set_no_proxy({"0.0.0.0/0"});
  23174. auto res = cli.Get("/");
  23175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23176. EXPECT_EQ(0, s.proxy_hits());
  23177. EXPECT_EQ(1, s.target_hits());
  23178. }
  23179. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23180. ProxyAndTargetServers s;
  23181. Client cli("127.0.0.1", s.target_port());
  23182. cli.set_proxy("127.0.0.1", s.proxy_port());
  23183. cli.set_no_proxy({"127.0.0.1"});
  23184. auto res = cli.Get("/");
  23185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23186. EXPECT_EQ(0, s.proxy_hits());
  23187. EXPECT_EQ(1, s.target_hits());
  23188. }
  23189. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23190. ProxyAndTargetServers s;
  23191. Client cli("127.0.0.1", s.target_port());
  23192. cli.set_proxy("127.0.0.1", s.proxy_port());
  23193. cli.set_no_proxy({"127.0.0.0/33"});
  23194. auto res = cli.Get("/");
  23195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23196. EXPECT_GE(s.proxy_hits(), 1);
  23197. EXPECT_EQ(0, s.target_hits());
  23198. }
  23199. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23200. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23201. ProxyAndTargetServers s;
  23202. Client cli("127.0.0.1", s.target_port());
  23203. cli.set_proxy("127.0.0.1", s.proxy_port());
  23204. cli.set_no_proxy({"127.0.0.1/"});
  23205. auto res = cli.Get("/");
  23206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23207. EXPECT_GE(s.proxy_hits(), 1);
  23208. EXPECT_EQ(0, s.target_hits());
  23209. }
  23210. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23211. ProxyAndTargetServers s;
  23212. auto cli = make_client("internal.corp", s);
  23213. cli->set_proxy_basic_auth("u", "p");
  23214. cli->set_no_proxy({"internal.corp"});
  23215. auto res = cli->Get("/");
  23216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23217. EXPECT_EQ(1, s.target_hits());
  23218. EXPECT_EQ(0, s.proxy_hits());
  23219. EXPECT_FALSE(s.last_had_proxy_authz())
  23220. << "Proxy-Authorization must not be sent direct to the target";
  23221. }
  23222. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23223. ProxyAndTargetServers s;
  23224. auto cli = make_client("public.example", s);
  23225. cli->set_proxy_basic_auth("u", "p");
  23226. cli->set_no_proxy({"internal.corp"}); // does not match
  23227. auto res = cli->Get("/");
  23228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23229. EXPECT_GE(s.proxy_hits(), 1);
  23230. EXPECT_TRUE(s.last_had_proxy_authz());
  23231. }
  23232. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23233. std::atomic<int> hits{0};
  23234. std::atomic<int> hits_with_authz{0};
  23235. no_proxy_test::ScopedServer proxy_mock;
  23236. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23237. hits++;
  23238. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23239. if (req.target.find("/redir") != std::string::npos) {
  23240. res.set_redirect("http://other.example/landed");
  23241. } else {
  23242. res.set_content("via-proxy", "text/plain");
  23243. }
  23244. });
  23245. proxy_mock.listen();
  23246. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23247. hits = 0;
  23248. hits_with_authz = 0;
  23249. Client cli("public.example", 80);
  23250. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23251. cli.set_proxy_basic_auth(c.first, c.second);
  23252. cli.set_follow_location(true);
  23253. // The redirect to another host goes through the proxy as well
  23254. auto res = cli.Get("/redir");
  23255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23256. EXPECT_EQ(2, hits.load());
  23257. EXPECT_EQ(2, hits_with_authz.load());
  23258. }
  23259. }
  23260. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23261. ProxyAndTargetServers s;
  23262. auto cli = make_client("anything.test", s);
  23263. auto res = cli->Get("/");
  23264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23265. EXPECT_GE(s.proxy_hits(), 1);
  23266. EXPECT_EQ(0, s.target_hits());
  23267. }
  23268. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23269. ProxyAndTargetServers s;
  23270. auto cli = make_client("example.com", s);
  23271. cli->set_no_proxy({"example.com:8080"});
  23272. auto res = cli->Get("/");
  23273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23274. EXPECT_GE(s.proxy_hits(), 1);
  23275. EXPECT_EQ(0, s.target_hits());
  23276. }
  23277. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23278. ProxyAndTargetServers s;
  23279. auto cli = make_client("anything.test", s);
  23280. cli->set_no_proxy({"", " ", "\t"});
  23281. auto res = cli->Get("/");
  23282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23283. EXPECT_GE(s.proxy_hits(), 1);
  23284. EXPECT_EQ(0, s.target_hits());
  23285. }
  23286. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23287. // An entry with leading/trailing whitespace must still match — env-style
  23288. // values are commonly pasted with stray spaces and an implementation
  23289. // that feeds the raw token directly to inet_pton would fail to match
  23290. // valid CIDRs because of the spaces.
  23291. ProxyAndTargetServers s;
  23292. Client cli("127.0.0.1", s.target_port());
  23293. cli.set_proxy("127.0.0.1", s.proxy_port());
  23294. cli.set_no_proxy({" 127.0.0.0/8 "});
  23295. auto res = cli.Get("/");
  23296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23297. EXPECT_EQ(0, s.proxy_hits());
  23298. EXPECT_EQ(1, s.target_hits());
  23299. }
  23300. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23301. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23302. // go direct and must NOT carry Proxy-Authorization.
  23303. std::atomic<int> proxy_hits{0};
  23304. std::atomic<int> target_hits{0};
  23305. std::atomic<bool> target_saw_authz{false};
  23306. no_proxy_test::ScopedServer proxy_mock, target;
  23307. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23308. proxy_hits++;
  23309. res.status = 302;
  23310. res.set_header("Location", "http://127.0.0.1:" +
  23311. std::to_string(target.port()) + "/landed");
  23312. });
  23313. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23314. target_hits++;
  23315. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23316. res.set_content("direct", "text/plain");
  23317. });
  23318. proxy_mock.listen();
  23319. target.listen();
  23320. Client cli("public.example", target.port());
  23321. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23322. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23323. cli.set_proxy_basic_auth("u", "p");
  23324. cli.set_no_proxy({"127.0.0.1"});
  23325. cli.set_follow_location(true);
  23326. auto res = cli.Get("/redir");
  23327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23328. EXPECT_GE(proxy_hits.load(), 1);
  23329. EXPECT_GE(target_hits.load(), 1);
  23330. EXPECT_FALSE(target_saw_authz.load());
  23331. }
  23332. #ifdef CPPHTTPLIB_SSL_ENABLED
  23333. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23334. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23335. // proxy creds would be sent to the (possibly hostile) origin.
  23336. std::atomic<int> target_hits{0};
  23337. std::atomic<bool> target_saw_proxy_authz{false};
  23338. no_proxy_test::ScopedServer target;
  23339. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23340. target_hits++;
  23341. if (req.has_header("Proxy-Authorization")) {
  23342. target_saw_proxy_authz = true;
  23343. }
  23344. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23345. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23346. "nonce=\"abc\", algorithm=MD5");
  23347. });
  23348. target.listen();
  23349. // The proxy address is set to the target's port: the bypass MUST kick in;
  23350. // if it doesn't, the test still routes "via proxy" to the same server and
  23351. // the Proxy-Authorization assertion below catches the leak.
  23352. Client cli("evil.example", target.port());
  23353. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23354. cli.set_proxy("127.0.0.1", target.port());
  23355. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23356. cli.set_no_proxy({"evil.example"});
  23357. auto res = cli.Get("/x");
  23358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23359. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23360. EXPECT_EQ(1, target_hits.load());
  23361. EXPECT_FALSE(target_saw_proxy_authz.load());
  23362. }
  23363. #endif
  23364. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23365. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23366. std::atomic<int> proxy_hits{0};
  23367. std::atomic<int> bypass_hits{0};
  23368. std::atomic<bool> proxy_saw_c_url{false};
  23369. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23370. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23371. proxy_hits++;
  23372. if (req.path.find("/start") != std::string::npos) {
  23373. res.status = 302;
  23374. res.set_header("Location", "http://127.0.0.1:" +
  23375. std::to_string(bypass_server.port()) +
  23376. "/middle");
  23377. return;
  23378. }
  23379. if (req.path.find("/end") != std::string::npos) {
  23380. proxy_saw_c_url = true;
  23381. res.set_content("c-via-proxy", "text/plain");
  23382. return;
  23383. }
  23384. res.set_content("unexpected", "text/plain");
  23385. });
  23386. // public.example's "advertised" port is arbitrary (the request never lands
  23387. // there — it goes through the proxy), but use a dynamic value to stay
  23388. // friendly with sharded parallel runs.
  23389. int public_port = bypass_server.port();
  23390. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23391. bypass_hits++;
  23392. res.status = 302;
  23393. res.set_header("Location", "http://public.example:" +
  23394. std::to_string(public_port) + "/end");
  23395. });
  23396. proxy_mock.listen();
  23397. bypass_server.listen();
  23398. Client cli("public.example", public_port);
  23399. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23400. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23401. cli.set_no_proxy({"127.0.0.1"});
  23402. cli.set_follow_location(true);
  23403. auto res = cli.Get("/start");
  23404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23405. EXPECT_EQ(StatusCode::OK_200, res->status);
  23406. EXPECT_EQ("c-via-proxy", res->body);
  23407. EXPECT_GE(proxy_hits.load(), 2);
  23408. EXPECT_GE(bypass_hits.load(), 1);
  23409. EXPECT_TRUE(proxy_saw_c_url.load());
  23410. }
  23411. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23412. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23413. // request reconnects to the correct endpoint.
  23414. std::atomic<int> proxy_hits{0};
  23415. std::atomic<int> target_hits{0};
  23416. no_proxy_test::ScopedServer proxy_mock, target;
  23417. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23418. proxy_hits++;
  23419. res.set_content("via-proxy", "text/plain");
  23420. });
  23421. target.svr().Get(".*", [&](const Request &, Response &res) {
  23422. target_hits++;
  23423. res.set_content("direct", "text/plain");
  23424. });
  23425. proxy_mock.listen();
  23426. target.listen();
  23427. Client cli("public.example", target.port());
  23428. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23429. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23430. cli.set_keep_alive(true);
  23431. auto res1 = cli.Get("/a");
  23432. ASSERT_TRUE(res1);
  23433. EXPECT_EQ("via-proxy", res1->body);
  23434. EXPECT_EQ(1, proxy_hits.load());
  23435. EXPECT_EQ(0, target_hits.load());
  23436. cli.set_no_proxy({"public.example"});
  23437. auto res2 = cli.Get("/b");
  23438. ASSERT_TRUE(res2);
  23439. EXPECT_EQ("direct", res2->body);
  23440. EXPECT_EQ(1, proxy_hits.load());
  23441. EXPECT_EQ(1, target_hits.load());
  23442. }
  23443. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23444. namespace proxy_tunnel_test {
  23445. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23446. class ScopedSSLServer {
  23447. public:
  23448. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23449. port_ = svr_.bind_to_any_port("127.0.0.1");
  23450. }
  23451. ~ScopedSSLServer() {
  23452. svr_.stop();
  23453. if (th_.joinable()) { th_.join(); }
  23454. }
  23455. SSLServer &svr() { return svr_; }
  23456. int port() const { return port_; }
  23457. void listen() {
  23458. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23459. svr_.wait_until_ready();
  23460. }
  23461. private:
  23462. SSLServer svr_;
  23463. std::thread th_;
  23464. int port_ = 0;
  23465. };
  23466. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23467. class ScopedConnectProxy {
  23468. public:
  23469. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23470. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23471. if (listen_fd_ < 0) { return; }
  23472. int yes = 1;
  23473. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23474. sockaddr_in a{};
  23475. a.sin_family = AF_INET;
  23476. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23477. a.sin_port = 0;
  23478. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23479. return;
  23480. }
  23481. socklen_t alen = sizeof(a);
  23482. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23483. 0) {
  23484. return;
  23485. }
  23486. port_ = ntohs(a.sin_port);
  23487. if (::listen(listen_fd_, 1) != 0) { return; }
  23488. th_ = std::thread([this] { run(); });
  23489. }
  23490. ~ScopedConnectProxy() {
  23491. stop_ = true;
  23492. if (listen_fd_ >= 0) {
  23493. ::shutdown(listen_fd_, SHUT_RDWR);
  23494. ::close(listen_fd_);
  23495. }
  23496. if (th_.joinable()) { th_.join(); }
  23497. }
  23498. int port() const { return port_; }
  23499. int connect_hits() const { return connect_hits_.load(); }
  23500. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23501. std::string connect_request() const {
  23502. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23503. return connect_request_;
  23504. }
  23505. private:
  23506. void run() {
  23507. while (!stop_.load()) {
  23508. fd_set rfds;
  23509. FD_ZERO(&rfds);
  23510. FD_SET(listen_fd_, &rfds);
  23511. timeval tv{0, 100 * 1000};
  23512. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23513. if (sel <= 0) { continue; }
  23514. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23515. if (client_fd < 0) { continue; }
  23516. std::string req;
  23517. char buf[2048];
  23518. while (req.find("\r\n\r\n") == std::string::npos) {
  23519. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23520. if (n <= 0) { break; }
  23521. req.append(buf, static_cast<size_t>(n));
  23522. }
  23523. if (req.compare(0, 7, "CONNECT") != 0) {
  23524. ::close(client_fd);
  23525. continue;
  23526. }
  23527. connect_hits_++;
  23528. {
  23529. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23530. connect_request_ = req;
  23531. }
  23532. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23533. ::send(client_fd, ok, std::strlen(ok), 0);
  23534. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23535. sockaddr_in o{};
  23536. o.sin_family = AF_INET;
  23537. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23538. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23539. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23540. 0) {
  23541. ::close(client_fd);
  23542. ::close(origin_fd);
  23543. continue;
  23544. }
  23545. auto forward = [](int from, int to) {
  23546. char b[8192];
  23547. for (;;) {
  23548. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23549. if (n <= 0) { break; }
  23550. ssize_t off = 0;
  23551. while (off < n) {
  23552. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23553. if (s <= 0) {
  23554. off = n;
  23555. break;
  23556. }
  23557. off += s;
  23558. }
  23559. }
  23560. ::shutdown(to, SHUT_WR);
  23561. };
  23562. std::thread t1([&] { forward(client_fd, origin_fd); });
  23563. std::thread t2([&] { forward(origin_fd, client_fd); });
  23564. t1.join();
  23565. t2.join();
  23566. ::close(client_fd);
  23567. ::close(origin_fd);
  23568. }
  23569. }
  23570. int forward_port_ = -1;
  23571. int listen_fd_ = -1;
  23572. int port_ = 0;
  23573. std::thread th_;
  23574. std::atomic<bool> stop_{false};
  23575. std::atomic<int> connect_hits_{0};
  23576. mutable std::mutex connect_request_mutex_;
  23577. std::string connect_request_;
  23578. };
  23579. // Sends one request through the CONNECT proxy to the TLS origin with a
  23580. // credential configured for each hop, and checks that each credential reaches
  23581. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23582. // origin's (every header in origin_headers) on the tunnelled request.
  23583. void CredentialsStayWithTheirHop(
  23584. const std::function<void(SSLClient &)> &set_credentials,
  23585. const std::string &scheme,
  23586. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23587. std::atomic<int> origin_hits{0};
  23588. std::atomic<bool> origin_saw_proxy_authz{false};
  23589. std::atomic<bool> origin_saw_headers{false};
  23590. ScopedSSLServer origin;
  23591. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23592. origin_hits++;
  23593. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23594. origin_saw_headers =
  23595. std::all_of(origin_headers.begin(), origin_headers.end(),
  23596. [&](const std::string &h) { return req.has_header(h); });
  23597. res.set_content("ok", "text/plain");
  23598. });
  23599. origin.listen();
  23600. ScopedConnectProxy proxy(origin.port());
  23601. ASSERT_NE(0, proxy.port());
  23602. // Pinned to 127.0.0.1 for the same reason as the test below.
  23603. SSLClient cli("127.0.0.1", origin.port());
  23604. cli.enable_server_certificate_verification(false);
  23605. cli.set_proxy("127.0.0.1", proxy.port());
  23606. set_credentials(cli);
  23607. auto res = cli.Get("/x");
  23608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23609. EXPECT_EQ(StatusCode::OK_200, res->status);
  23610. EXPECT_EQ(1, origin_hits.load());
  23611. EXPECT_EQ(1, proxy.connect_hits());
  23612. EXPECT_TRUE(origin_saw_headers.load());
  23613. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23614. << "Proxy-Authorization must not be sent inside the tunnel";
  23615. auto connect_req = proxy.connect_request();
  23616. EXPECT_NE(std::string::npos,
  23617. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23618. for (const auto &h : origin_headers) {
  23619. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23620. << h << " must not be sent to the proxy on CONNECT";
  23621. }
  23622. }
  23623. } // namespace proxy_tunnel_test
  23624. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23625. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23626. [](SSLClient &cli) {
  23627. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23628. cli.set_basic_auth("origin-user", "origin-pass");
  23629. },
  23630. "Basic");
  23631. }
  23632. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23633. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23634. [](SSLClient &cli) {
  23635. cli.set_proxy_bearer_token_auth("proxy-token");
  23636. cli.set_bearer_token_auth("origin-token");
  23637. },
  23638. "Bearer");
  23639. }
  23640. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23641. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23642. [](SSLClient &cli) {
  23643. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23644. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23645. {"Cookie", "sid=origin-session"},
  23646. {"X-Api-Key", "origin-key"}});
  23647. },
  23648. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23649. }
  23650. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23651. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23652. // retry; otherwise proxy creds would be sent to the origin.
  23653. std::atomic<int> origin_hits{0};
  23654. std::atomic<bool> origin_saw_proxy_authz{false};
  23655. proxy_tunnel_test::ScopedSSLServer origin;
  23656. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23657. origin_hits++;
  23658. if (req.has_header("Proxy-Authorization")) {
  23659. origin_saw_proxy_authz = true;
  23660. }
  23661. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23662. res.set_header("Proxy-Authenticate",
  23663. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23664. "algorithm=MD5");
  23665. });
  23666. origin.listen();
  23667. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23668. ASSERT_NE(0, proxy.port());
  23669. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23670. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23671. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23672. // and answer with its own status, making this test flaky.
  23673. SSLClient cli("127.0.0.1", origin.port());
  23674. cli.enable_server_certificate_verification(false);
  23675. cli.set_proxy("127.0.0.1", proxy.port());
  23676. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23677. auto res = cli.Get("/x");
  23678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23679. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23680. EXPECT_EQ(1, origin_hits.load());
  23681. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23682. EXPECT_EQ(1, proxy.connect_hits());
  23683. }
  23684. #endif