test.cc 907 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005
  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. static void
  3182. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3183. Server svr1;
  3184. std::string captured_authorization;
  3185. svr1.Get("/target", [&](const Request &req, Response &res) {
  3186. captured_authorization = req.get_header_value("Authorization");
  3187. res.set_content("OK", "text/plain");
  3188. });
  3189. int svr1_port = 0;
  3190. auto thread1 = std::thread([&]() {
  3191. svr1_port = svr1.bind_to_any_port(HOST);
  3192. svr1.listen_after_bind();
  3193. });
  3194. Server svr2;
  3195. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3196. res.set_redirect(
  3197. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3198. });
  3199. int svr2_port = 0;
  3200. auto thread2 = std::thread([&]() {
  3201. svr2_port = svr2.bind_to_any_port(HOST);
  3202. svr2.listen_after_bind();
  3203. });
  3204. auto se = detail::scope_exit([&] {
  3205. svr2.stop();
  3206. thread2.join();
  3207. svr1.stop();
  3208. thread1.join();
  3209. ASSERT_FALSE(svr2.is_running());
  3210. ASSERT_FALSE(svr1.is_running());
  3211. });
  3212. svr1.wait_until_ready();
  3213. svr2.wait_until_ready();
  3214. Client cli("localhost", svr2_port);
  3215. cli.set_follow_location(true);
  3216. set_auth(cli);
  3217. auto res = cli.Get("/redir");
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3221. EXPECT_TRUE(captured_authorization.empty());
  3222. }
  3223. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3224. TestDoNotForwardCredentialsOnRedirect(
  3225. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3226. }
  3227. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3228. TestDoNotForwardCredentialsOnRedirect(
  3229. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3230. }
  3231. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3232. Server svr1;
  3233. std::string captured_cookie;
  3234. bool target_hit = false;
  3235. svr1.Get("/target", [&](const Request &req, Response &res) {
  3236. captured_cookie = req.get_header_value("Cookie");
  3237. target_hit = true;
  3238. res.set_content("OK", "text/plain");
  3239. });
  3240. int svr1_port = 0;
  3241. auto thread1 = std::thread([&]() {
  3242. svr1_port = svr1.bind_to_any_port(HOST);
  3243. svr1.listen_after_bind();
  3244. });
  3245. Server svr2;
  3246. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3247. res.set_redirect(
  3248. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3249. });
  3250. int svr2_port = 0;
  3251. auto thread2 = std::thread([&]() {
  3252. svr2_port = svr2.bind_to_any_port(HOST);
  3253. svr2.listen_after_bind();
  3254. });
  3255. auto se = detail::scope_exit([&] {
  3256. svr2.stop();
  3257. thread2.join();
  3258. svr1.stop();
  3259. thread1.join();
  3260. ASSERT_FALSE(svr2.is_running());
  3261. ASSERT_FALSE(svr1.is_running());
  3262. });
  3263. svr1.wait_until_ready();
  3264. svr2.wait_until_ready();
  3265. Client cli("localhost", svr2_port);
  3266. cli.set_follow_location(true);
  3267. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3268. auto res = cli.Get("/redir", headers);
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. EXPECT_TRUE(target_hit);
  3272. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3273. EXPECT_TRUE(captured_cookie.empty());
  3274. }
  3275. TEST(RedirectToSamePort, ForwardCookie) {
  3276. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3277. // header so that ordinary session flows keep working.
  3278. Server svr;
  3279. std::string captured_cookie;
  3280. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3281. res.set_redirect("/target", 302);
  3282. });
  3283. svr.Get("/target", [&](const Request &req, Response &res) {
  3284. captured_cookie = req.get_header_value("Cookie");
  3285. res.set_content("OK", "text/plain");
  3286. });
  3287. auto port = svr.bind_to_any_port(HOST);
  3288. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3289. auto se = detail::scope_exit([&] {
  3290. svr.stop();
  3291. thread.join();
  3292. ASSERT_FALSE(svr.is_running());
  3293. });
  3294. svr.wait_until_ready();
  3295. Client cli(HOST, port);
  3296. cli.set_follow_location(true);
  3297. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3298. auto res = cli.Get("/redir", headers);
  3299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3302. }
  3303. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3304. Server svr;
  3305. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3306. // Port number that overflows int — should not crash
  3307. res.set_redirect("http://localhost:99999999999999999999/target");
  3308. });
  3309. auto port = svr.bind_to_any_port(HOST);
  3310. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. thread.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. svr.wait_until_ready();
  3317. Client cli(HOST, port);
  3318. cli.set_follow_location(true);
  3319. auto res = cli.Get("/redir");
  3320. // Should fail gracefully, not crash (no valid response due to bad port)
  3321. EXPECT_FALSE(res);
  3322. }
  3323. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3324. Server svr;
  3325. auto port = svr.bind_to_any_port(HOST);
  3326. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3327. // The server's own port followed by junk must not be followed
  3328. res.set_redirect("http://" + std::string(HOST) + ":" +
  3329. std::to_string(port) + "junk/target");
  3330. });
  3331. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3332. res.set_content("target", "text/plain");
  3333. });
  3334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. Client cli(HOST, port);
  3342. cli.set_follow_location(true);
  3343. auto res = cli.Get("/redir");
  3344. EXPECT_FALSE(res);
  3345. }
  3346. TEST(RedirectFromPageWithContent, Redirect) {
  3347. Server svr;
  3348. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3349. res.set_content("___", "text/plain");
  3350. res.set_redirect("/2");
  3351. });
  3352. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3353. res.set_content("Hello World!", "text/plain");
  3354. });
  3355. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3356. auto se = detail::scope_exit([&] {
  3357. svr.stop();
  3358. th.join();
  3359. ASSERT_FALSE(svr.is_running());
  3360. });
  3361. svr.wait_until_ready();
  3362. {
  3363. Client cli("localhost", PORT);
  3364. cli.set_follow_location(true);
  3365. std::string body;
  3366. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3367. body.append(data, data_length);
  3368. return true;
  3369. });
  3370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3371. EXPECT_EQ(StatusCode::OK_200, res->status);
  3372. EXPECT_EQ("Hello World!", body);
  3373. }
  3374. {
  3375. Client cli("localhost", PORT);
  3376. std::string body;
  3377. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3378. body.append(data, data_length);
  3379. return true;
  3380. });
  3381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3382. EXPECT_EQ(StatusCode::Found_302, res->status);
  3383. EXPECT_EQ("___", body);
  3384. }
  3385. }
  3386. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3387. Server svr;
  3388. auto port_str = std::to_string(PORT);
  3389. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3390. auto expected_host = "[::1]:" + port_str;
  3391. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3392. res.set_content("___", "text/plain");
  3393. // res.set_redirect("/2");
  3394. res.set_redirect(redirect_url);
  3395. });
  3396. svr.Get("/2", [&](const Request &req, Response &res) {
  3397. auto host_header = req.headers.find("Host");
  3398. ASSERT_TRUE(host_header != req.headers.end());
  3399. EXPECT_EQ(expected_host, host_header->second);
  3400. res.set_content("Hello World!", "text/plain");
  3401. });
  3402. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3403. auto se = detail::scope_exit([&] {
  3404. svr.stop();
  3405. th.join();
  3406. ASSERT_FALSE(svr.is_running());
  3407. });
  3408. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3409. // actually starts anything, so the condition !svr.is_running() will
  3410. // always remain true, and the loop never stops.
  3411. // This basically counts how many milliseconds have passed since the
  3412. // call to svr.listen(), and if after 5 seconds nothing started yet
  3413. // aborts the test.
  3414. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3415. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3416. ASSERT_LT(milliseconds, 5000U);
  3417. }
  3418. {
  3419. Client cli("::1", PORT);
  3420. cli.set_follow_location(true);
  3421. std::string body;
  3422. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3423. body.append(data, data_length);
  3424. return true;
  3425. });
  3426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("Hello World!", body);
  3429. }
  3430. {
  3431. Client cli("::1", PORT);
  3432. std::string body;
  3433. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3434. body.append(data, data_length);
  3435. return true;
  3436. });
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(StatusCode::Found_302, res->status);
  3439. EXPECT_EQ("___", body);
  3440. }
  3441. }
  3442. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3443. Server svr;
  3444. svr.Get("/foo", [](const Request &req, Response &res) {
  3445. auto a = req.params.find("a");
  3446. if (a != req.params.end()) {
  3447. res.set_content((*a).second, "text/plain");
  3448. res.status = StatusCode::OK_200;
  3449. } else {
  3450. res.status = StatusCode::BadRequest_400;
  3451. }
  3452. });
  3453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. {
  3461. Client cli(HOST, PORT);
  3462. cli.set_path_encode(false);
  3463. auto res = cli.Get("/foo?a=explicitly+encoded");
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. // This expects it back with a space, as the `+` won't have been
  3467. // url-encoded, and server-side the params get decoded turning `+`
  3468. // into spaces.
  3469. EXPECT_EQ("explicitly encoded", res->body);
  3470. }
  3471. }
  3472. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3473. // When path encoding is disabled the client must transmit the supplied
  3474. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3475. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3476. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3477. // than a space (0x20). Assert on the raw wire target to catch this.
  3478. Server svr;
  3479. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3480. svr.Get("/foo", [&](const Request &req, Response &res) {
  3481. EXPECT_EQ(expected_target, req.target);
  3482. res.status = StatusCode::OK_200;
  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(expected_target.c_str());
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. }
  3498. }
  3499. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3500. // `open_stream()` used to skip the path encoding that the buffered send
  3501. // path applies, so the same `path` produced different bytes in the request
  3502. // line depending on which API was used. Assert the two agree.
  3503. Server svr;
  3504. std::string target;
  3505. svr.Get(".*", [&](const Request &req, Response &res) {
  3506. target = req.target;
  3507. res.status = StatusCode::OK_200;
  3508. });
  3509. auto port = svr.bind_to_any_port(HOST);
  3510. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. thread.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. svr.wait_until_ready();
  3517. struct {
  3518. const char *path;
  3519. const char *expected;
  3520. } cases[] = {
  3521. {"/a b?x=1", "/a%20b?x=1"},
  3522. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3523. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3524. };
  3525. for (const auto &c : cases) {
  3526. Client cli(HOST, port);
  3527. target.clear();
  3528. auto res = cli.Get(c.path);
  3529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3530. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3531. auto buffered_target = target;
  3532. target.clear();
  3533. auto handle = cli.open_stream("GET", c.path);
  3534. EXPECT_TRUE(handle.is_valid())
  3535. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3536. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3537. }
  3538. }
  3539. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3540. // The `set_path_encode(false)` contract — transmit the supplied target
  3541. // verbatim — must hold for the streaming API too.
  3542. Server svr;
  3543. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3544. std::string target;
  3545. svr.Get("/foo", [&](const Request &req, Response &res) {
  3546. target = req.target;
  3547. res.status = StatusCode::OK_200;
  3548. });
  3549. auto port = svr.bind_to_any_port(HOST);
  3550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. svr.wait_until_ready();
  3557. {
  3558. Client cli(HOST, port);
  3559. cli.set_path_encode(false);
  3560. auto handle = cli.open_stream("GET", expected_target);
  3561. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3562. EXPECT_EQ(expected_target, target);
  3563. }
  3564. }
  3565. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3566. // With path encoding enabled a CR/LF in the target is percent-encoded
  3567. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3568. // write_request_line still backstops `set_path_encode(false)`, which is
  3569. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3570. Server svr;
  3571. // Captured before routing: the decoded path contains a newline, which a
  3572. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3573. std::string target;
  3574. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3575. target = req.target;
  3576. res.status = StatusCode::OK_200;
  3577. return Server::HandlerResponse::Handled;
  3578. });
  3579. auto port = svr.bind_to_any_port(HOST);
  3580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3581. auto se = detail::scope_exit([&] {
  3582. svr.stop();
  3583. thread.join();
  3584. ASSERT_FALSE(svr.is_running());
  3585. });
  3586. svr.wait_until_ready();
  3587. {
  3588. Client cli(HOST, port);
  3589. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3590. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3591. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3592. }
  3593. }
  3594. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3595. // Every control character is percent-encoded, not just CR/LF, so the target
  3596. // passes the request-target check in write_request_line.
  3597. Server svr;
  3598. std::string target;
  3599. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3600. target = req.target;
  3601. res.status = StatusCode::OK_200;
  3602. return Server::HandlerResponse::Handled;
  3603. });
  3604. auto port = svr.bind_to_any_port(HOST);
  3605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. thread.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. svr.wait_until_ready();
  3612. {
  3613. Client cli(HOST, port);
  3614. auto res = cli.Get("/a\tb\x1b\x7f");
  3615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3616. EXPECT_EQ("/a%09b%1B%7F", target);
  3617. }
  3618. }
  3619. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3620. // Nothing may reach the wire: a raw CR/LF target would split the request
  3621. // line and inject headers.
  3622. Server svr;
  3623. // Pre-routing so that "not called" means nothing reached the server at all,
  3624. // rather than merely failing to match a handler pattern.
  3625. auto handler_called = false;
  3626. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3627. handler_called = true;
  3628. res.status = StatusCode::OK_200;
  3629. return Server::HandlerResponse::Handled;
  3630. });
  3631. auto port = svr.bind_to_any_port(HOST);
  3632. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3633. auto se = detail::scope_exit([&] {
  3634. svr.stop();
  3635. thread.join();
  3636. ASSERT_FALSE(svr.is_running());
  3637. });
  3638. svr.wait_until_ready();
  3639. {
  3640. Client cli(HOST, port);
  3641. cli.set_path_encode(false);
  3642. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3643. EXPECT_FALSE(handle.is_valid());
  3644. EXPECT_EQ(Error::Write, handle.error);
  3645. EXPECT_FALSE(handler_called);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3649. // Which of the two branches runs is decided by whether the query component
  3650. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3651. // an empty query and must still fall back to building one from
  3652. // `req.params`, while a non-empty query must win over `req.params`.
  3653. Server svr;
  3654. std::string target;
  3655. svr.Get("/foo", [&](const Request &req, Response &res) {
  3656. target = req.target;
  3657. res.status = StatusCode::OK_200;
  3658. });
  3659. auto port = svr.bind_to_any_port(HOST);
  3660. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3661. auto se = detail::scope_exit([&] {
  3662. svr.stop();
  3663. thread.join();
  3664. ASSERT_FALSE(svr.is_running());
  3665. });
  3666. svr.wait_until_ready();
  3667. {
  3668. // Trailing `?` -> empty query component -> `req.params` is used.
  3669. Client cli(HOST, port);
  3670. Request req;
  3671. req.method = "GET";
  3672. req.path = "/foo?";
  3673. req.params.emplace("a", "1");
  3674. target.clear();
  3675. auto res = cli.send(req);
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ("/foo?a=1", target);
  3678. }
  3679. {
  3680. // Non-empty query in `req.path` -> `req.params` is not appended.
  3681. Client cli(HOST, port);
  3682. Request req;
  3683. req.method = "GET";
  3684. req.path = "/foo?b=2";
  3685. req.params.emplace("a", "1");
  3686. target.clear();
  3687. auto res = cli.send(req);
  3688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3689. EXPECT_EQ("/foo?b=2", target);
  3690. }
  3691. }
  3692. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3693. Server svr;
  3694. svr.Get("/", [](const Request &req, Response &) {
  3695. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3696. });
  3697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3698. auto se = detail::scope_exit([&] {
  3699. svr.stop();
  3700. thread.join();
  3701. ASSERT_FALSE(svr.is_running());
  3702. });
  3703. svr.wait_until_ready();
  3704. {
  3705. Client cli(HOST, PORT);
  3706. cli.set_path_encode(false);
  3707. auto res = cli.Get("/?something=%0A");
  3708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3709. EXPECT_EQ(StatusCode::OK_200, res->status);
  3710. }
  3711. }
  3712. TEST(BindServerTest, BindDualStack) {
  3713. Server svr;
  3714. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3715. res.set_content("Hello World!", "text/plain");
  3716. });
  3717. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3718. auto se = detail::scope_exit([&] {
  3719. svr.stop();
  3720. thread.join();
  3721. ASSERT_FALSE(svr.is_running());
  3722. });
  3723. svr.wait_until_ready();
  3724. {
  3725. Client cli("127.0.0.1", PORT);
  3726. auto res = cli.Get("/1");
  3727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3728. EXPECT_EQ(StatusCode::OK_200, res->status);
  3729. EXPECT_EQ("Hello World!", res->body);
  3730. }
  3731. {
  3732. Client cli("::1", PORT);
  3733. auto res = cli.Get("/1");
  3734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3735. EXPECT_EQ(StatusCode::OK_200, res->status);
  3736. EXPECT_EQ("Hello World!", res->body);
  3737. }
  3738. }
  3739. TEST(BindServerTest, BindAndListenSeparately) {
  3740. Server svr;
  3741. int port = svr.bind_to_any_port("0.0.0.0");
  3742. ASSERT_TRUE(svr.is_valid());
  3743. ASSERT_TRUE(port > 0);
  3744. svr.stop();
  3745. }
  3746. // Reports whether anything is still listening on a loopback port. A plain
  3747. // connect() is used instead of a Client request because a socket left bound by
  3748. // mistake accepts the connection into its backlog and never answers, which
  3749. // would hang the test instead of failing it.
  3750. static bool is_loopback_port_accepting(int port) {
  3751. sockaddr_in addr{};
  3752. addr.sin_family = AF_INET;
  3753. addr.sin_port = htons(static_cast<uint16_t>(port));
  3754. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3755. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3756. EXPECT_NE(sock, INVALID_SOCKET);
  3757. if (sock == INVALID_SOCKET) { return false; }
  3758. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3759. static_cast<socklen_t>(sizeof(addr)));
  3760. detail::close_socket(sock);
  3761. return ret == 0;
  3762. }
  3763. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3764. Server svr;
  3765. auto port = svr.bind_to_any_port("127.0.0.1");
  3766. ASSERT_TRUE(port > 0);
  3767. svr.stop();
  3768. // bind_to_any_port() already called listen(2), so until stop() closed the
  3769. // descriptor the port kept accepting connections into the backlog. ASSERT
  3770. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3771. // below blocks forever in the accept loop.
  3772. ASSERT_FALSE(is_loopback_port_accepting(port));
  3773. // Nothing is left to accept on, so listen_after_bind() must report failure
  3774. // instead of returning success without ever serving.
  3775. EXPECT_FALSE(svr.listen_after_bind());
  3776. // The failed listen marks the server decommissioned, so a waiter returns
  3777. // instead of spinning forever.
  3778. svr.wait_until_ready();
  3779. }
  3780. #ifdef CPPHTTPLIB_SSL_ENABLED
  3781. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3783. CLIENT_CA_CERT_DIR);
  3784. int port = svr.bind_to_any_port("0.0.0.0");
  3785. ASSERT_TRUE(svr.is_valid());
  3786. ASSERT_TRUE(port > 0);
  3787. svr.stop();
  3788. }
  3789. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3790. // or a rejected CustomRoute() registration would not stop the server binding.
  3791. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3793. CLIENT_CA_CERT_DIR);
  3794. ASSERT_TRUE(svr.is_valid());
  3795. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3796. EXPECT_FALSE(svr.is_valid());
  3797. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3798. }
  3799. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3800. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3801. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3802. int port = svr.bind_to_any_port("0.0.0.0");
  3803. ASSERT_TRUE(svr.is_valid());
  3804. ASSERT_TRUE(port > 0);
  3805. svr.stop();
  3806. }
  3807. TEST(BindServerTest, UpdateCertsPem) {
  3808. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3809. int port = svr.bind_to_any_port("0.0.0.0");
  3810. ASSERT_TRUE(svr.is_valid());
  3811. ASSERT_TRUE(port > 0);
  3812. // Read PEM files
  3813. std::string cert_pem, key_pem, ca_pem;
  3814. read_file(SERVER_CERT_FILE, cert_pem);
  3815. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3816. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3817. // Update server certificates using PEM API
  3818. ASSERT_TRUE(
  3819. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3820. ASSERT_TRUE(svr.is_valid());
  3821. svr.stop();
  3822. }
  3823. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3824. // Start server with client CA (enables client auth)
  3825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3826. ASSERT_TRUE(svr.is_valid());
  3827. bool handler_called = false;
  3828. svr.Get("/test", [&](const Request &req, Response &res) {
  3829. handler_called = true;
  3830. // Verify client certificate is present
  3831. auto cert = req.peer_cert();
  3832. EXPECT_TRUE(static_cast<bool>(cert));
  3833. res.set_content("ok", "text/plain");
  3834. });
  3835. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. t.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. // Read PEM files
  3843. std::string cert_pem, key_pem, ca_pem;
  3844. read_file(SERVER_CERT_FILE, cert_pem);
  3845. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3846. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3847. // Update server certificates and client CA using PEM API while server running
  3848. ASSERT_TRUE(
  3849. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3850. // Connect with client certificate
  3851. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3852. cli.enable_server_certificate_verification(false);
  3853. cli.set_connection_timeout(30);
  3854. auto res = cli.Get("/test");
  3855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3856. ASSERT_EQ(StatusCode::OK_200, res->status);
  3857. ASSERT_TRUE(handler_called);
  3858. EXPECT_EQ("ok", res->body);
  3859. }
  3860. #endif
  3861. TEST(ErrorHandlerTest, ContentLength) {
  3862. Server svr;
  3863. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3864. res.status = StatusCode::OK_200;
  3865. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3866. "text/html"); // <= Content-Length still 13
  3867. });
  3868. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3869. res.set_content("Hello World!\n", "text/plain");
  3870. res.status = 524;
  3871. });
  3872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3873. auto se = detail::scope_exit([&] {
  3874. svr.stop();
  3875. thread.join();
  3876. ASSERT_FALSE(svr.is_running());
  3877. });
  3878. svr.wait_until_ready();
  3879. {
  3880. Client cli(HOST, PORT);
  3881. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3883. EXPECT_EQ(StatusCode::OK_200, res->status);
  3884. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3885. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3886. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3887. }
  3888. }
  3889. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3890. TEST(ExceptionTest, WithoutExceptionHandler) {
  3891. Server svr;
  3892. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3893. throw std::runtime_error("exception...");
  3894. });
  3895. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3896. throw std::runtime_error("exception\r\n...");
  3897. });
  3898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3899. auto se = detail::scope_exit([&] {
  3900. svr.stop();
  3901. listen_thread.join();
  3902. ASSERT_FALSE(svr.is_running());
  3903. });
  3904. svr.wait_until_ready();
  3905. Client cli("localhost", PORT);
  3906. {
  3907. auto res = cli.Get("/exception");
  3908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3909. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3910. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3911. }
  3912. {
  3913. auto res = cli.Get("/unknown");
  3914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3915. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3916. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3917. }
  3918. }
  3919. TEST(ExceptionTest, WithExceptionHandler) {
  3920. Server svr;
  3921. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3922. std::exception_ptr ep) {
  3923. EXPECT_FALSE(ep == nullptr);
  3924. try {
  3925. std::rethrow_exception(ep);
  3926. } catch (std::exception &e) {
  3927. EXPECT_EQ("abc", std::string(e.what()));
  3928. } catch (...) {}
  3929. res.status = StatusCode::InternalServerError_500;
  3930. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3931. "text/html"); // <= Content-Length still 13 at this point
  3932. });
  3933. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3934. res.set_content("Hello World!\n", "text/plain");
  3935. throw std::runtime_error("abc");
  3936. });
  3937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3938. auto se = detail::scope_exit([&] {
  3939. svr.stop();
  3940. thread.join();
  3941. ASSERT_FALSE(svr.is_running());
  3942. });
  3943. svr.wait_until_ready();
  3944. for (size_t i = 0; i < 10; i++) {
  3945. Client cli(HOST, PORT);
  3946. for (size_t j = 0; j < 100; j++) {
  3947. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3949. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3950. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3951. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3952. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3953. }
  3954. cli.set_keep_alive(true);
  3955. for (size_t j = 0; j < 100; j++) {
  3956. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3958. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3959. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3960. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3961. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3962. }
  3963. }
  3964. }
  3965. TEST(ExceptionTest, AndErrorHandler) {
  3966. Server svr;
  3967. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3968. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3969. });
  3970. svr.set_exception_handler(
  3971. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3972. EXPECT_FALSE(ep == nullptr);
  3973. try {
  3974. std::rethrow_exception(ep);
  3975. } catch (std::exception &e) {
  3976. res.set_content(e.what(), "text/html");
  3977. } catch (...) {}
  3978. res.status = StatusCode::InternalServerError_500;
  3979. });
  3980. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3981. throw std::runtime_error("EXCEPTION");
  3982. });
  3983. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3984. res.set_content("ERROR", "text/html");
  3985. res.status = StatusCode::InternalServerError_500;
  3986. });
  3987. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3988. auto se = detail::scope_exit([&] {
  3989. svr.stop();
  3990. thread.join();
  3991. ASSERT_FALSE(svr.is_running());
  3992. });
  3993. svr.wait_until_ready();
  3994. Client cli(HOST, PORT);
  3995. {
  3996. auto res = cli.Get("/exception");
  3997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3998. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3999. EXPECT_EQ("EXCEPTION", res->body);
  4000. }
  4001. {
  4002. auto res = cli.Get("/error");
  4003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4004. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4005. EXPECT_EQ("ERROR", res->body);
  4006. }
  4007. {
  4008. auto res = cli.Get("/invalid");
  4009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4010. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4011. EXPECT_EQ("NOT_FOUND", res->body);
  4012. }
  4013. }
  4014. #endif
  4015. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4016. // process_request() wraps only routing() in a try/catch, so an exception from
  4017. // any other user callback used to unwind into the task queue - which does not
  4018. // catch - and terminate the process. Each test below runs the server on a
  4019. // single worker thread: a guard that catches the exception but still loses the
  4020. // thread would otherwise be hidden by a spare worker serving the follow-up
  4021. // request. Note that a regression here aborts the whole test binary rather
  4022. // than failing one test.
  4023. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4024. Server svr;
  4025. svr.new_task_queue = [] { return new ThreadPool(1); };
  4026. std::atomic<int> reported{0};
  4027. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4028. if (err == Error::UserCallbackException) { reported++; }
  4029. });
  4030. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4031. res.set_content_provider(
  4032. 1024, "text/plain",
  4033. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4034. sink.write("hello", 5);
  4035. throw std::runtime_error("from the content provider");
  4036. });
  4037. });
  4038. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4039. res.set_content("ok", "text/plain");
  4040. });
  4041. auto port = svr.bind_to_any_port(HOST);
  4042. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4043. auto se = detail::scope_exit([&] {
  4044. svr.stop();
  4045. listen_thread.join();
  4046. ASSERT_FALSE(svr.is_running());
  4047. });
  4048. svr.wait_until_ready();
  4049. {
  4050. Client cli(HOST, port);
  4051. cli.set_read_timeout(5, 0);
  4052. EXPECT_FALSE(cli.Get("/throw"));
  4053. }
  4054. EXPECT_TRUE(svr.is_running());
  4055. EXPECT_EQ(1, reported.load());
  4056. // A request on a fresh connection is still served.
  4057. {
  4058. Client cli(HOST, port);
  4059. auto res = cli.Get("/ok");
  4060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4061. EXPECT_EQ(StatusCode::OK_200, res->status);
  4062. EXPECT_EQ("ok", res->body);
  4063. }
  4064. }
  4065. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4066. Server svr;
  4067. svr.new_task_queue = [] { return new ThreadPool(1); };
  4068. std::atomic<bool> should_throw{true};
  4069. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4070. res.set_content("hi", "text/plain");
  4071. });
  4072. svr.set_post_routing_handler(
  4073. [&](const Request & /*req*/, Response & /*res*/) {
  4074. if (should_throw) {
  4075. throw std::runtime_error("from the post-routing handler");
  4076. }
  4077. });
  4078. auto port = svr.bind_to_any_port(HOST);
  4079. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. listen_thread.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. {
  4087. Client cli(HOST, port);
  4088. cli.set_read_timeout(5, 0);
  4089. EXPECT_FALSE(cli.Get("/hi"));
  4090. }
  4091. EXPECT_TRUE(svr.is_running());
  4092. should_throw = false;
  4093. {
  4094. Client cli(HOST, port);
  4095. auto res = cli.Get("/hi");
  4096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4097. EXPECT_EQ(StatusCode::OK_200, res->status);
  4098. EXPECT_EQ("hi", res->body);
  4099. }
  4100. }
  4101. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4102. // The guard reports the caught exception through the error logger, which is
  4103. // a user callback too. A logger that throws has to be contained as well, or
  4104. // the process would terminate from inside the catch.
  4105. Server svr;
  4106. svr.new_task_queue = [] { return new ThreadPool(1); };
  4107. std::atomic<int> reported{0};
  4108. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4109. if (err == Error::UserCallbackException) {
  4110. reported++;
  4111. throw std::runtime_error("from the error logger");
  4112. }
  4113. });
  4114. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4115. res.set_content_provider(
  4116. 1024, "text/plain",
  4117. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4118. sink.write("hello", 5);
  4119. throw std::runtime_error("from the content provider");
  4120. });
  4121. });
  4122. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4123. res.set_content("ok", "text/plain");
  4124. });
  4125. auto port = svr.bind_to_any_port(HOST);
  4126. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4127. auto se = detail::scope_exit([&] {
  4128. svr.stop();
  4129. listen_thread.join();
  4130. ASSERT_FALSE(svr.is_running());
  4131. });
  4132. svr.wait_until_ready();
  4133. {
  4134. Client cli(HOST, port);
  4135. cli.set_read_timeout(5, 0);
  4136. EXPECT_FALSE(cli.Get("/throw"));
  4137. }
  4138. EXPECT_TRUE(svr.is_running());
  4139. EXPECT_EQ(1, reported.load());
  4140. {
  4141. Client cli(HOST, port);
  4142. auto res = cli.Get("/ok");
  4143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4144. EXPECT_EQ(StatusCode::OK_200, res->status);
  4145. EXPECT_EQ("ok", res->body);
  4146. }
  4147. }
  4148. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4149. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4150. // so the exception unwinds through the ws::WebSocket object on its way to
  4151. // the guard. None of the HTTP cases above cross that.
  4152. Server svr;
  4153. svr.new_task_queue = [] { return new ThreadPool(1); };
  4154. std::atomic<int> reported{0};
  4155. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4156. if (err == Error::UserCallbackException) { reported++; }
  4157. });
  4158. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4159. throw std::runtime_error("from the WebSocket handler");
  4160. });
  4161. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4162. res.set_content("ok", "text/plain");
  4163. });
  4164. auto port = svr.bind_to_any_port(HOST);
  4165. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4166. auto se = detail::scope_exit([&] {
  4167. svr.stop();
  4168. listen_thread.join();
  4169. ASSERT_FALSE(svr.is_running());
  4170. });
  4171. svr.wait_until_ready();
  4172. {
  4173. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4174. "/ws");
  4175. auto res = client.connect();
  4176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4177. // The server dropped the connection instead of dying.
  4178. std::string msg;
  4179. EXPECT_FALSE(client.read(msg));
  4180. client.close();
  4181. }
  4182. EXPECT_TRUE(svr.is_running());
  4183. EXPECT_EQ(1, reported.load());
  4184. {
  4185. Client cli(HOST, port);
  4186. auto res = cli.Get("/ok");
  4187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ("ok", res->body);
  4190. }
  4191. }
  4192. #ifdef CPPHTTPLIB_SSL_ENABLED
  4193. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4194. // SSLServer::process_and_close_socket() is a separate overload with its own
  4195. // guard, so it is exercised on its own.
  4196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4197. ASSERT_TRUE(svr.is_valid());
  4198. svr.new_task_queue = [] { return new ThreadPool(1); };
  4199. std::atomic<int> reported{0};
  4200. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4201. if (err == Error::UserCallbackException) { reported++; }
  4202. });
  4203. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4204. res.set_content_provider(
  4205. 1024, "text/plain",
  4206. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4207. sink.write("hello", 5);
  4208. throw std::runtime_error("from the content provider");
  4209. });
  4210. });
  4211. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4212. res.set_content("ok", "text/plain");
  4213. });
  4214. auto port = svr.bind_to_any_port(HOST);
  4215. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4216. auto se = detail::scope_exit([&] {
  4217. svr.stop();
  4218. listen_thread.join();
  4219. ASSERT_FALSE(svr.is_running());
  4220. });
  4221. svr.wait_until_ready();
  4222. {
  4223. SSLClient cli(HOST, port);
  4224. cli.enable_server_certificate_verification(false);
  4225. cli.set_read_timeout(5, 0);
  4226. EXPECT_FALSE(cli.Get("/throw"));
  4227. }
  4228. EXPECT_TRUE(svr.is_running());
  4229. EXPECT_EQ(1, reported.load());
  4230. {
  4231. SSLClient cli(HOST, port);
  4232. cli.enable_server_certificate_verification(false);
  4233. auto res = cli.Get("/ok");
  4234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ("ok", res->body);
  4237. }
  4238. }
  4239. #endif
  4240. #endif
  4241. TEST(NoContentTest, ContentLength) {
  4242. Server svr;
  4243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4244. res.status = StatusCode::NoContent_204;
  4245. });
  4246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4247. auto se = detail::scope_exit([&] {
  4248. svr.stop();
  4249. thread.join();
  4250. ASSERT_FALSE(svr.is_running());
  4251. });
  4252. svr.wait_until_ready();
  4253. {
  4254. Client cli(HOST, PORT);
  4255. auto res = cli.Get("/hi");
  4256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4259. }
  4260. }
  4261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4262. #ifdef CPPHTTPLIB_SSL_ENABLED
  4263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4264. ASSERT_TRUE(svr.is_valid());
  4265. #else
  4266. Server svr;
  4267. #endif
  4268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4269. if (req.path == "/routing_handler") {
  4270. res.set_header("PRE_ROUTING", "on");
  4271. res.set_content("Routing Handler", "text/plain");
  4272. return httplib::Server::HandlerResponse::Handled;
  4273. }
  4274. return httplib::Server::HandlerResponse::Unhandled;
  4275. });
  4276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4277. res.set_content("Error", "text/html");
  4278. });
  4279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4280. if (req.path == "/routing_handler") {
  4281. res.set_header("POST_ROUTING", "on");
  4282. }
  4283. });
  4284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4285. res.set_content("Hello World!\n", "text/plain");
  4286. });
  4287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4288. auto se = detail::scope_exit([&] {
  4289. svr.stop();
  4290. thread.join();
  4291. ASSERT_FALSE(svr.is_running());
  4292. });
  4293. svr.wait_until_ready();
  4294. {
  4295. #ifdef CPPHTTPLIB_SSL_ENABLED
  4296. SSLClient cli(HOST, PORT);
  4297. cli.enable_server_certificate_verification(false);
  4298. #else
  4299. Client cli(HOST, PORT);
  4300. #endif
  4301. auto res = cli.Get("/routing_handler");
  4302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("Routing Handler", res->body);
  4305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4309. }
  4310. {
  4311. #ifdef CPPHTTPLIB_SSL_ENABLED
  4312. SSLClient cli(HOST, PORT);
  4313. cli.enable_server_certificate_verification(false);
  4314. #else
  4315. Client cli(HOST, PORT);
  4316. #endif
  4317. auto res = cli.Get("/hi");
  4318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4319. EXPECT_EQ(StatusCode::OK_200, res->status);
  4320. EXPECT_EQ("Hello World!\n", res->body);
  4321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4323. }
  4324. {
  4325. #ifdef CPPHTTPLIB_SSL_ENABLED
  4326. SSLClient cli(HOST, PORT);
  4327. cli.enable_server_certificate_verification(false);
  4328. #else
  4329. Client cli(HOST, PORT);
  4330. #endif
  4331. auto res = cli.Get("/aaa");
  4332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4334. EXPECT_EQ("Error", res->body);
  4335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4337. }
  4338. }
  4339. TEST(RequestHandlerTest, PreRequestHandler) {
  4340. auto route_path = "/user/:user";
  4341. Server svr;
  4342. svr.Get("/hi", [](const Request &, Response &res) {
  4343. res.set_content("hi", "text/plain");
  4344. });
  4345. svr.Get(route_path, [](const Request &req, Response &res) {
  4346. res.set_content(req.path_params.at("user"), "text/plain");
  4347. });
  4348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4349. if (req.matched_route == route_path) {
  4350. auto user = req.path_params.at("user");
  4351. if (user != "john") {
  4352. res.status = StatusCode::Forbidden_403;
  4353. res.set_content("error", "text/html");
  4354. return Server::HandlerResponse::Handled;
  4355. }
  4356. }
  4357. return Server::HandlerResponse::Unhandled;
  4358. });
  4359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4360. auto se = detail::scope_exit([&] {
  4361. svr.stop();
  4362. thread.join();
  4363. ASSERT_FALSE(svr.is_running());
  4364. });
  4365. svr.wait_until_ready();
  4366. Client cli(HOST, PORT);
  4367. {
  4368. auto res = cli.Get("/hi");
  4369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. EXPECT_EQ("hi", res->body);
  4372. }
  4373. {
  4374. auto res = cli.Get("/user/john");
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::OK_200, res->status);
  4377. EXPECT_EQ("john", res->body);
  4378. }
  4379. {
  4380. auto res = cli.Get("/user/invalid-user");
  4381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4383. EXPECT_EQ("error", res->body);
  4384. }
  4385. }
  4386. // The pre-request handler must run before the request body is read, so a
  4387. // rejected request never forces the server to buffer a (potentially large)
  4388. // body. Here the posted body is larger than the payload limit: if the body
  4389. // were read first the server would answer 413, but because the pre-request
  4390. // handler runs first it answers 403 and the body is never read.
  4391. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4392. Server svr;
  4393. svr.set_payload_max_length(8);
  4394. auto handler_ran = false;
  4395. svr.Post("/reject", [&](const Request &req, Response &res) {
  4396. handler_ran = true;
  4397. res.set_content(req.body, "text/plain");
  4398. });
  4399. svr.Post("/accept", [](const Request &req, Response &res) {
  4400. res.set_content(req.body, "text/plain");
  4401. });
  4402. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4403. if (req.matched_route == "/reject") {
  4404. res.status = StatusCode::Forbidden_403;
  4405. res.set_content("denied", "text/plain");
  4406. return Server::HandlerResponse::Handled;
  4407. }
  4408. return Server::HandlerResponse::Unhandled;
  4409. });
  4410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4411. auto se = detail::scope_exit([&] {
  4412. svr.stop();
  4413. thread.join();
  4414. ASSERT_FALSE(svr.is_running());
  4415. });
  4416. svr.wait_until_ready();
  4417. Client cli(HOST, PORT);
  4418. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4419. // rejects with 403 before the body is read, so 413 is never reached.
  4420. {
  4421. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4424. EXPECT_EQ("denied", res->body);
  4425. EXPECT_FALSE(handler_ran);
  4426. }
  4427. // An approved route still reads the body and enforces the payload limit.
  4428. {
  4429. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4432. }
  4433. }
  4434. TEST(UserDataTest, BasicOperations) {
  4435. httplib::UserData ud;
  4436. // Initially empty
  4437. EXPECT_FALSE(ud.has("key"));
  4438. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4439. // set and get
  4440. ud.set("key", 42);
  4441. EXPECT_TRUE(ud.has("key"));
  4442. auto *p = ud.get<int>("key");
  4443. ASSERT_NE(nullptr, p);
  4444. EXPECT_EQ(42, *p);
  4445. // Type mismatch → nullptr
  4446. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4447. // Overwrite with different type
  4448. ud.set("key", std::string("hello"));
  4449. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4450. auto *s = ud.get<std::string>("key");
  4451. ASSERT_NE(nullptr, s);
  4452. EXPECT_EQ("hello", *s);
  4453. // erase
  4454. ud.erase("key");
  4455. EXPECT_FALSE(ud.has("key"));
  4456. // clear
  4457. ud.set("a", 1);
  4458. ud.set("b", 2);
  4459. ud.clear();
  4460. EXPECT_FALSE(ud.has("a"));
  4461. EXPECT_FALSE(ud.has("b"));
  4462. }
  4463. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4464. struct AuthCtx {
  4465. std::string user_id;
  4466. };
  4467. Server svr;
  4468. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4469. res.user_data.set("auth", AuthCtx{"alice"});
  4470. return Server::HandlerResponse::Unhandled;
  4471. });
  4472. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4473. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4474. ASSERT_NE(nullptr, ctx);
  4475. res.set_content("Hello " + ctx->user_id, "text/plain");
  4476. });
  4477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4478. auto se = detail::scope_exit([&] {
  4479. svr.stop();
  4480. thread.join();
  4481. ASSERT_FALSE(svr.is_running());
  4482. });
  4483. svr.wait_until_ready();
  4484. Client cli(HOST, PORT);
  4485. auto res = cli.Get("/me");
  4486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4487. EXPECT_EQ(StatusCode::OK_200, res->status);
  4488. EXPECT_EQ("Hello alice", res->body);
  4489. }
  4490. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4491. struct RoleCtx {
  4492. std::string role;
  4493. };
  4494. Server svr;
  4495. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4496. res.user_data.set("role", RoleCtx{"admin"});
  4497. return Server::HandlerResponse::Unhandled;
  4498. });
  4499. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4500. auto *ctx = res.user_data.get<RoleCtx>("role");
  4501. ASSERT_NE(nullptr, ctx);
  4502. res.set_content(ctx->role, "text/plain");
  4503. });
  4504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4505. auto se = detail::scope_exit([&] {
  4506. svr.stop();
  4507. thread.join();
  4508. ASSERT_FALSE(svr.is_running());
  4509. });
  4510. svr.wait_until_ready();
  4511. Client cli(HOST, PORT);
  4512. auto res = cli.Get("/role");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ(StatusCode::OK_200, res->status);
  4515. EXPECT_EQ("admin", res->body);
  4516. }
  4517. TEST(InvalidFormatTest, StatusCode) {
  4518. Server svr;
  4519. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4520. res.set_content("Hello World!\n", "text/plain");
  4521. res.status = 9999; // Status should be a three-digit code...
  4522. });
  4523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4524. auto se = detail::scope_exit([&] {
  4525. svr.stop();
  4526. thread.join();
  4527. ASSERT_FALSE(svr.is_running());
  4528. });
  4529. svr.wait_until_ready();
  4530. {
  4531. Client cli(HOST, PORT);
  4532. auto res = cli.Get("/hi");
  4533. ASSERT_FALSE(res);
  4534. }
  4535. }
  4536. TEST(URLFragmentTest, WithFragment) {
  4537. Server svr;
  4538. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4539. EXPECT_TRUE(req.target == "/hi");
  4540. });
  4541. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4542. auto se = detail::scope_exit([&] {
  4543. svr.stop();
  4544. thread.join();
  4545. ASSERT_FALSE(svr.is_running());
  4546. });
  4547. svr.wait_until_ready();
  4548. {
  4549. Client cli(HOST, PORT);
  4550. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4551. EXPECT_TRUE(res);
  4552. EXPECT_EQ(StatusCode::OK_200, res->status);
  4553. res = cli.Get("/hi%23key1=val1=key2=val2");
  4554. EXPECT_TRUE(res);
  4555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4556. }
  4557. }
  4558. TEST(HeaderWriter, SetHeaderWriter) {
  4559. Server svr;
  4560. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4561. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4562. return detail::write_headers(strm, hdrs);
  4563. });
  4564. svr.Get("/hi", [](const Request &req, Response &res) {
  4565. auto it = req.headers.find("CustomClientHeader");
  4566. EXPECT_TRUE(it != req.headers.end());
  4567. EXPECT_EQ(it->second, "CustomClientValue");
  4568. res.set_content("Hello World!\n", "text/plain");
  4569. });
  4570. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4571. auto se = detail::scope_exit([&] {
  4572. svr.stop();
  4573. thread.join();
  4574. ASSERT_FALSE(svr.is_running());
  4575. });
  4576. svr.wait_until_ready();
  4577. {
  4578. Client cli(HOST, PORT);
  4579. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4580. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4581. return detail::write_headers(strm, hdrs);
  4582. });
  4583. auto res = cli.Get("/hi");
  4584. EXPECT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. auto it = res->headers.find("CustomServerHeader");
  4587. EXPECT_TRUE(it != res->headers.end());
  4588. EXPECT_EQ(it->second, "CustomServerValue");
  4589. }
  4590. }
  4591. class ServerTest : public ::testing::Test {
  4592. protected:
  4593. ServerTest()
  4594. : cli_(HOST, PORT)
  4595. #ifdef CPPHTTPLIB_SSL_ENABLED
  4596. ,
  4597. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4598. #endif
  4599. {
  4600. #ifdef CPPHTTPLIB_SSL_ENABLED
  4601. cli_.enable_server_certificate_verification(false);
  4602. #endif
  4603. // Allow LARGE_DATA (100MB) responses
  4604. cli_.set_payload_max_length(200 * 1024 * 1024);
  4605. }
  4606. virtual void SetUp() {
  4607. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4608. svr_.set_payload_max_length(200 * 1024 * 1024);
  4609. svr_.set_mount_point("/", "./www");
  4610. svr_.set_mount_point("/mount", "./www2");
  4611. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4612. svr_.Get("/hi",
  4613. [&](const Request & /*req*/, Response &res) {
  4614. res.set_content("Hello World!", "text/plain");
  4615. })
  4616. .Get("/file_content",
  4617. [&](const Request & /*req*/, Response &res) {
  4618. res.set_file_content("./www/dir/test.html");
  4619. })
  4620. .Get("/file_content_with_content_type",
  4621. [&](const Request & /*req*/, Response &res) {
  4622. res.set_file_content("./www/file", "text/plain");
  4623. })
  4624. .Get("/invalid_file_content",
  4625. [&](const Request & /*req*/, Response &res) {
  4626. res.set_file_content("./www/dir/invalid_file_path");
  4627. })
  4628. .Get("/http_response_splitting",
  4629. [&](const Request & /*req*/, Response &res) {
  4630. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4631. EXPECT_EQ(0U, res.headers.size());
  4632. EXPECT_FALSE(res.has_header("a"));
  4633. res.set_header("a", "1\nSet-Cookie: a=1");
  4634. EXPECT_EQ(0U, res.headers.size());
  4635. EXPECT_FALSE(res.has_header("a"));
  4636. res.set_header("a", "1\rSet-Cookie: a=1");
  4637. EXPECT_EQ(0U, res.headers.size());
  4638. EXPECT_FALSE(res.has_header("a"));
  4639. res.set_header("a\r\nb", "0");
  4640. EXPECT_EQ(0U, res.headers.size());
  4641. EXPECT_FALSE(res.has_header("a"));
  4642. res.set_header("a\rb", "0");
  4643. EXPECT_EQ(0U, res.headers.size());
  4644. EXPECT_FALSE(res.has_header("a"));
  4645. res.set_header("a\nb", "0");
  4646. EXPECT_EQ(0U, res.headers.size());
  4647. EXPECT_FALSE(res.has_header("a"));
  4648. res.set_redirect("1\r\nSet-Cookie: a=1");
  4649. EXPECT_EQ(0U, res.headers.size());
  4650. EXPECT_FALSE(res.has_header("Location"));
  4651. })
  4652. .Get("/slow",
  4653. [&](const Request & /*req*/, Response &res) {
  4654. std::this_thread::sleep_for(std::chrono::seconds(4));
  4655. res.set_content("slow", "text/plain");
  4656. })
  4657. #if 0
  4658. .Post("/slowpost",
  4659. [&](const Request & /*req*/, Response &res) {
  4660. std::this_thread::sleep_for(std::chrono::seconds(2));
  4661. res.set_content("slow", "text/plain");
  4662. })
  4663. #endif
  4664. .Get("/remote_addr",
  4665. [&](const Request &req, Response &res) {
  4666. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4667. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4668. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4669. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4670. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4671. #endif
  4672. res.set_content(req.remote_addr, "text/plain");
  4673. })
  4674. .Get("/local_addr",
  4675. [&](const Request &req, Response &res) {
  4676. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4677. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4678. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4679. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4680. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4681. #endif
  4682. auto local_addr = req.local_addr;
  4683. auto local_port = std::to_string(req.local_port);
  4684. res.set_content(local_addr.append(":").append(local_port),
  4685. "text/plain");
  4686. })
  4687. .Get("/endwith%",
  4688. [&](const Request & /*req*/, Response &res) {
  4689. res.set_content("Hello World!", "text/plain");
  4690. })
  4691. .Get("/a\\+\\+b",
  4692. [&](const Request &req, Response &res) {
  4693. ASSERT_TRUE(req.has_param("a +b"));
  4694. auto val = req.get_param_value("a +b");
  4695. res.set_content(val, "text/plain");
  4696. })
  4697. .Get("/", [&](const Request & /*req*/,
  4698. Response &res) { res.set_redirect("/hi"); })
  4699. .Post("/1",
  4700. [](const Request & /*req*/, Response &res) {
  4701. res.set_redirect("/2", StatusCode::SeeOther_303);
  4702. })
  4703. .Get("/2",
  4704. [](const Request & /*req*/, Response &res) {
  4705. res.set_content("redirected.", "text/plain");
  4706. res.status = StatusCode::OK_200;
  4707. })
  4708. .Post("/person",
  4709. [&](const Request &req, Response &res) {
  4710. if (req.has_param("name") && req.has_param("note")) {
  4711. persons_[req.get_param_value("name")] =
  4712. req.get_param_value("note");
  4713. } else {
  4714. res.status = StatusCode::BadRequest_400;
  4715. }
  4716. })
  4717. .Put("/person",
  4718. [&](const Request &req, Response &res) {
  4719. if (req.has_param("name") && req.has_param("note")) {
  4720. persons_[req.get_param_value("name")] =
  4721. req.get_param_value("note");
  4722. } else {
  4723. res.status = StatusCode::BadRequest_400;
  4724. }
  4725. })
  4726. .Get("/person/(.*)",
  4727. [&](const Request &req, Response &res) {
  4728. string name = req.matches[1];
  4729. if (persons_.find(name) != persons_.end()) {
  4730. auto note = persons_[name];
  4731. res.set_content(note, "text/plain");
  4732. } else {
  4733. res.status = StatusCode::NotFound_404;
  4734. }
  4735. })
  4736. .Delete("/person",
  4737. [&](const Request &req, Response &res) {
  4738. if (req.has_param("name")) {
  4739. string name = req.get_param_value("name");
  4740. if (persons_.find(name) != persons_.end()) {
  4741. persons_.erase(name);
  4742. res.set_content("DELETED", "text/plain");
  4743. } else {
  4744. res.status = StatusCode::NotFound_404;
  4745. }
  4746. } else {
  4747. res.status = StatusCode::BadRequest_400;
  4748. }
  4749. })
  4750. .Post("/x-www-form-urlencoded-json",
  4751. [&](const Request &req, Response &res) {
  4752. auto json = req.get_param_value("json");
  4753. ASSERT_EQ(JSON_DATA, json);
  4754. res.set_content(json, "appliation/json");
  4755. res.status = StatusCode::OK_200;
  4756. })
  4757. .Get("/streamed-chunked",
  4758. [&](const Request & /*req*/, Response &res) {
  4759. res.set_chunked_content_provider(
  4760. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4761. sink.os << "123";
  4762. sink.os << "456";
  4763. sink.os << "789";
  4764. sink.done();
  4765. return true;
  4766. });
  4767. })
  4768. .Get("/streamed-chunked-with-prohibited-trailer",
  4769. [&](const Request & /*req*/, Response &res) {
  4770. auto i = new int(0);
  4771. // Declare both a prohibited trailer (Content-Length) and an
  4772. // allowed one
  4773. res.set_header("Trailer", "Content-Length, X-Allowed");
  4774. res.set_chunked_content_provider(
  4775. "text/plain",
  4776. [i](size_t /*offset*/, DataSink &sink) {
  4777. switch (*i) {
  4778. case 0: sink.os << "123"; break;
  4779. case 1: sink.os << "456"; break;
  4780. case 2: sink.os << "789"; break;
  4781. case 3: {
  4782. sink.done_with_trailer(
  4783. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4784. } break;
  4785. }
  4786. (*i)++;
  4787. return true;
  4788. },
  4789. [i](bool success) {
  4790. EXPECT_TRUE(success);
  4791. delete i;
  4792. });
  4793. })
  4794. .Get("/streamed-chunked2",
  4795. [&](const Request & /*req*/, Response &res) {
  4796. auto i = new int(0);
  4797. res.set_chunked_content_provider(
  4798. "text/plain",
  4799. [i](size_t /*offset*/, DataSink &sink) {
  4800. switch (*i) {
  4801. case 0: sink.os << "123"; break;
  4802. case 1: sink.os << "456"; break;
  4803. case 2: sink.os << "789"; break;
  4804. case 3: sink.done(); break;
  4805. }
  4806. (*i)++;
  4807. return true;
  4808. },
  4809. [i](bool success) {
  4810. EXPECT_TRUE(success);
  4811. delete i;
  4812. });
  4813. })
  4814. .Get("/streamed-chunked-with-trailer",
  4815. [&](const Request & /*req*/, Response &res) {
  4816. auto i = new int(0);
  4817. res.set_header("Trailer", "Dummy1, Dummy2");
  4818. res.set_chunked_content_provider(
  4819. "text/plain",
  4820. [i](size_t /*offset*/, DataSink &sink) {
  4821. switch (*i) {
  4822. case 0: sink.os << "123"; break;
  4823. case 1: sink.os << "456"; break;
  4824. case 2: sink.os << "789"; break;
  4825. case 3: {
  4826. sink.done_with_trailer(
  4827. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4828. } break;
  4829. }
  4830. (*i)++;
  4831. return true;
  4832. },
  4833. [i](bool success) {
  4834. EXPECT_TRUE(success);
  4835. delete i;
  4836. });
  4837. })
  4838. .Get("/streamed",
  4839. [&](const Request & /*req*/, Response &res) {
  4840. res.set_content_provider(
  4841. 6, "text/plain",
  4842. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4843. sink.os << (offset < 3 ? "a" : "b");
  4844. return true;
  4845. });
  4846. })
  4847. .Get("/streamed-without-length",
  4848. [&](const Request & /*req*/, Response &res) {
  4849. auto data = new std::string("abcdefg");
  4850. res.set_content_provider(
  4851. "text/plain",
  4852. [data](size_t offset, DataSink &sink) {
  4853. if (offset < data->size()) {
  4854. sink.os << data->substr(offset);
  4855. }
  4856. sink.done();
  4857. return true;
  4858. },
  4859. [data](bool success) {
  4860. EXPECT_TRUE(success);
  4861. delete data;
  4862. });
  4863. })
  4864. .Get("/streamed-with-range",
  4865. [&](const Request &req, Response &res) {
  4866. auto data = new std::string("abcdefg");
  4867. // An explicit status keeps the server from picking the 206 it
  4868. // would otherwise choose for a ranged request, so the response
  4869. // is not a partial representation.
  4870. auto status = req.get_param_value("status");
  4871. if (status == "200") {
  4872. res.status = StatusCode::OK_200;
  4873. } else if (status == "403") {
  4874. res.status = StatusCode::Forbidden_403;
  4875. }
  4876. res.set_content_provider(
  4877. data->size(), "text/plain",
  4878. [data](size_t offset, size_t length, DataSink &sink) {
  4879. size_t DATA_CHUNK_SIZE = 4;
  4880. const auto &d = *data;
  4881. auto out_len =
  4882. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4883. auto ret =
  4884. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4885. EXPECT_TRUE(ret);
  4886. return true;
  4887. },
  4888. [data, &req](bool success) {
  4889. EXPECT_EQ(success, !req.has_param("error"));
  4890. delete data;
  4891. });
  4892. })
  4893. .Get("/streamed-cancel",
  4894. [&](const Request & /*req*/, Response &res) {
  4895. res.set_content_provider(
  4896. size_t(-1), "text/plain",
  4897. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4898. sink.os << "data_chunk";
  4899. return true;
  4900. });
  4901. })
  4902. .Get("/regex-with-delimiter",
  4903. [&](const Request &req, Response & /*res*/) {
  4904. ASSERT_TRUE(req.has_param("key"));
  4905. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4906. })
  4907. .Get("/with-range",
  4908. [&](const Request & /*req*/, Response &res) {
  4909. res.set_content("abcdefg", "text/plain");
  4910. })
  4911. .Get("/test-start-time",
  4912. [&](const Request &req, Response & /*res*/) {
  4913. EXPECT_NE(req.start_time_,
  4914. std::chrono::steady_clock::time_point::min());
  4915. })
  4916. .Get("/with-range-customized-response",
  4917. [&](const Request & /*req*/, Response &res) {
  4918. res.status = StatusCode::BadRequest_400;
  4919. res.set_content(JSON_DATA, "application/json");
  4920. })
  4921. .Post("/chunked",
  4922. [&](const Request &req, Response & /*res*/) {
  4923. EXPECT_EQ(req.body, "dechunked post body");
  4924. })
  4925. .Post("/large-chunked",
  4926. [&](const Request &req, Response & /*res*/) {
  4927. std::string expected(6 * 30 * 1024u, 'a');
  4928. EXPECT_EQ(req.body, expected);
  4929. })
  4930. .Post("/multipart",
  4931. [&](const Request &req, Response & /*res*/) {
  4932. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4933. req.form.get_field_count("text2") +
  4934. req.form.get_field_count("file3") +
  4935. req.form.get_field_count("file4"));
  4936. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4937. req.form.get_file_count("file2"));
  4938. ASSERT_TRUE(!req.form.has_file("???"));
  4939. ASSERT_TRUE(!req.form.has_field("???"));
  4940. ASSERT_TRUE(req.body.empty());
  4941. {
  4942. const auto &text = req.form.get_field("text1");
  4943. EXPECT_EQ("text default", text);
  4944. }
  4945. {
  4946. const auto &text = req.form.get_field("text2");
  4947. EXPECT_EQ("aωb", text);
  4948. }
  4949. {
  4950. const auto &file = req.form.get_file("file1");
  4951. EXPECT_EQ("hello.txt", file.filename);
  4952. EXPECT_EQ("text/plain", file.content_type);
  4953. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4954. }
  4955. {
  4956. const auto &file = req.form.get_file("file2");
  4957. EXPECT_EQ("world.json", file.filename);
  4958. EXPECT_EQ("application/json", file.content_type);
  4959. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4960. }
  4961. {
  4962. const auto &text = req.form.get_field("file3");
  4963. EXPECT_EQ(0u, text.size());
  4964. }
  4965. {
  4966. const auto &text = req.form.get_field("file4");
  4967. EXPECT_EQ(0u, text.size());
  4968. }
  4969. })
  4970. .Post("/multipart/multi_file_values",
  4971. [&](const Request &req, Response & /*res*/) {
  4972. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4973. req.form.get_field_count("multi_text1"));
  4974. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4975. ASSERT_TRUE(!req.form.has_file("???"));
  4976. ASSERT_TRUE(!req.form.has_field("???"));
  4977. ASSERT_TRUE(req.body.empty());
  4978. {
  4979. const auto &text = req.form.get_field("text");
  4980. EXPECT_EQ("default text", text);
  4981. }
  4982. {
  4983. const auto &text1_values = req.form.get_fields("multi_text1");
  4984. EXPECT_EQ(2u, text1_values.size());
  4985. EXPECT_EQ("aaaaa", text1_values[0]);
  4986. EXPECT_EQ("bbbbb", text1_values[1]);
  4987. }
  4988. {
  4989. const auto &file1_values = req.form.get_files("multi_file1");
  4990. EXPECT_EQ(2u, file1_values.size());
  4991. auto file1 = file1_values[0];
  4992. EXPECT_EQ(file1.filename, "hello.txt");
  4993. EXPECT_EQ(file1.content_type, "text/plain");
  4994. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4995. auto file2 = file1_values[1];
  4996. EXPECT_EQ(file2.filename, "world.json");
  4997. EXPECT_EQ(file2.content_type, "application/json");
  4998. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4999. }
  5000. })
  5001. .Post("/empty",
  5002. [&](const Request &req, Response &res) {
  5003. EXPECT_EQ(req.body, "");
  5004. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5005. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5006. res.set_content("empty", "text/plain");
  5007. })
  5008. .Post("/empty-no-content-type",
  5009. [&](const Request &req, Response &res) {
  5010. EXPECT_EQ(req.body, "");
  5011. EXPECT_FALSE(req.has_header("Content-Type"));
  5012. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5013. res.set_content("empty-no-content-type", "text/plain");
  5014. })
  5015. .Post("/path-only",
  5016. [&](const Request &req, Response &res) {
  5017. EXPECT_EQ(req.body, "");
  5018. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5019. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5020. res.set_content("path-only", "text/plain");
  5021. })
  5022. .Post("/path-headers-only",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(req.body, "");
  5025. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5026. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5027. EXPECT_EQ("world", req.get_header_value("hello"));
  5028. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5029. res.set_content("path-headers-only", "text/plain");
  5030. })
  5031. .Post("/post-large",
  5032. [&](const Request &req, Response &res) {
  5033. EXPECT_EQ(req.body, LARGE_DATA);
  5034. res.set_content(req.body, "text/plain");
  5035. })
  5036. .Post("/post-loopback",
  5037. [&](const Request &, Response &res,
  5038. ContentReader const &content_reader) {
  5039. std::string body;
  5040. content_reader([&](const char *data, size_t data_length) {
  5041. body.append(data, data_length);
  5042. return true;
  5043. });
  5044. res.set_content(body, "text/plain");
  5045. })
  5046. .Put("/put-loopback",
  5047. [&](const Request &, Response &res,
  5048. ContentReader const &content_reader) {
  5049. std::string body;
  5050. content_reader([&](const char *data, size_t data_length) {
  5051. body.append(data, data_length);
  5052. return true;
  5053. });
  5054. res.set_content(body, "text/plain");
  5055. })
  5056. .Patch("/patch-loopback",
  5057. [&](const Request &, Response &res,
  5058. ContentReader const &content_reader) {
  5059. std::string body;
  5060. content_reader([&](const char *data, size_t data_length) {
  5061. body.append(data, data_length);
  5062. return true;
  5063. });
  5064. res.set_content(body, "text/plain");
  5065. })
  5066. .Put("/empty-no-content-type",
  5067. [&](const Request &req, Response &res) {
  5068. EXPECT_EQ(req.body, "");
  5069. EXPECT_FALSE(req.has_header("Content-Type"));
  5070. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5071. res.set_content("empty-no-content-type", "text/plain");
  5072. })
  5073. .Put("/put",
  5074. [&](const Request &req, Response &res) {
  5075. EXPECT_EQ(req.body, "PUT");
  5076. res.set_content(req.body, "text/plain");
  5077. })
  5078. .Put("/put-large",
  5079. [&](const Request &req, Response &res) {
  5080. EXPECT_EQ(req.body, LARGE_DATA);
  5081. res.set_content(req.body, "text/plain");
  5082. })
  5083. .Patch("/patch",
  5084. [&](const Request &req, Response &res) {
  5085. EXPECT_EQ(req.body, "PATCH");
  5086. res.set_content(req.body, "text/plain");
  5087. })
  5088. .Delete("/delete",
  5089. [&](const Request & /*req*/, Response &res) {
  5090. res.set_content("DELETE", "text/plain");
  5091. })
  5092. .Delete("/delete-body",
  5093. [&](const Request &req, Response &res) {
  5094. EXPECT_EQ(req.body, "content");
  5095. res.set_content(req.body, "text/plain");
  5096. })
  5097. .Options(R"(\*)",
  5098. [&](const Request & /*req*/, Response &res) {
  5099. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5100. })
  5101. .CustomRoute("PROPFIND", "/dav/:id",
  5102. [&](const Request &req, Response &res) {
  5103. res.set_header("x-body-size",
  5104. std::to_string(req.body.size()));
  5105. res.set_header("x-matched-route", req.matched_route);
  5106. res.set_header("x-dav-id", req.path_params.at("id"));
  5107. res.status = StatusCode::MultiStatus_207;
  5108. res.set_content(req.body, "application/xml");
  5109. })
  5110. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5111. [&](const Request &req, Response &res) {
  5112. res.set_header("x-dav-match", req.matches[1]);
  5113. res.status = StatusCode::MultiStatus_207;
  5114. })
  5115. .CustomRoute("MKCOL", "/dav-mkcol",
  5116. [&](const Request &req, Response &res) {
  5117. EXPECT_TRUE(req.body.empty());
  5118. res.status = StatusCode::Created_201;
  5119. })
  5120. .CustomRoute(
  5121. "REPORT", "/dav-report",
  5122. [&](const Request & /*req*/, Response &res,
  5123. const ContentReader &content_reader) {
  5124. std::string body;
  5125. content_reader([&](const char *data, size_t data_length) {
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. res.set_header("x-body-size", std::to_string(body.size()));
  5130. res.status = StatusCode::MultiStatus_207;
  5131. res.set_content(body, "application/xml");
  5132. })
  5133. .Get("/request-target",
  5134. [&](const Request &req, Response & /*res*/) {
  5135. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5136. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5137. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5138. })
  5139. .Get("/long-query-value",
  5140. [&](const Request &req, Response & /*res*/) {
  5141. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5142. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5143. })
  5144. .Get("/too-long-query-value",
  5145. [&](const Request &req, Response & /*res*/) {
  5146. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5147. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5148. })
  5149. .Get("/array-param",
  5150. [&](const Request &req, Response & /*res*/) {
  5151. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5152. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5153. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5154. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5155. })
  5156. .Get("/array-param-values",
  5157. [&](const Request &req, Response & /*res*/) {
  5158. auto values = req.get_param_values("array");
  5159. EXPECT_EQ(3u, values.size());
  5160. EXPECT_EQ("value1", values[0]);
  5161. EXPECT_EQ("value2", values[1]);
  5162. EXPECT_EQ("value3", values[2]);
  5163. auto empty = req.get_param_values("nonexistent");
  5164. EXPECT_TRUE(empty.empty());
  5165. })
  5166. .Post("/validate-no-multiple-headers",
  5167. [&](const Request &req, Response & /*res*/) {
  5168. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5169. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5170. })
  5171. .Post("/content_receiver",
  5172. [&](const Request &req, Response &res,
  5173. const ContentReader &content_reader) {
  5174. if (req.is_multipart_form_data()) {
  5175. std::vector<FormData> items;
  5176. content_reader(
  5177. [&](const FormData &file) {
  5178. items.push_back(file);
  5179. return true;
  5180. },
  5181. [&](const char *data, size_t data_length) {
  5182. items.back().content.append(data, data_length);
  5183. return true;
  5184. });
  5185. EXPECT_EQ(5u, items.size());
  5186. {
  5187. const auto &file = get_file_value(items, "text1");
  5188. EXPECT_TRUE(file.filename.empty());
  5189. EXPECT_EQ("text default", file.content);
  5190. }
  5191. {
  5192. const auto &file = get_file_value(items, "text2");
  5193. EXPECT_TRUE(file.filename.empty());
  5194. EXPECT_EQ("aωb", file.content);
  5195. }
  5196. {
  5197. const auto &file = get_file_value(items, "file1");
  5198. EXPECT_EQ("hello.txt", file.filename);
  5199. EXPECT_EQ("text/plain", file.content_type);
  5200. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5201. }
  5202. {
  5203. const auto &file = get_file_value(items, "file2");
  5204. EXPECT_EQ("world.json", file.filename);
  5205. EXPECT_EQ("application/json", file.content_type);
  5206. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5207. }
  5208. {
  5209. const auto &file = get_file_value(items, "file3");
  5210. EXPECT_TRUE(file.filename.empty());
  5211. EXPECT_EQ("application/octet-stream", file.content_type);
  5212. EXPECT_EQ(0u, file.content.size());
  5213. }
  5214. } else {
  5215. std::string body;
  5216. content_reader([&](const char *data, size_t data_length) {
  5217. EXPECT_EQ(7U, data_length);
  5218. body.append(data, data_length);
  5219. return true;
  5220. });
  5221. EXPECT_EQ(body, "content");
  5222. res.set_content(body, "text/plain");
  5223. }
  5224. })
  5225. .Put("/content_receiver",
  5226. [&](const Request & /*req*/, Response &res,
  5227. const ContentReader &content_reader) {
  5228. std::string body;
  5229. content_reader([&](const char *data, size_t data_length) {
  5230. body.append(data, data_length);
  5231. return true;
  5232. });
  5233. EXPECT_EQ(body, "content");
  5234. res.set_content(body, "text/plain");
  5235. })
  5236. .Patch("/content_receiver",
  5237. [&](const Request & /*req*/, Response &res,
  5238. const ContentReader &content_reader) {
  5239. std::string body;
  5240. content_reader([&](const char *data, size_t data_length) {
  5241. body.append(data, data_length);
  5242. return true;
  5243. });
  5244. EXPECT_EQ(body, "content");
  5245. res.set_content(body, "text/plain");
  5246. })
  5247. .Post("/query-string-and-body",
  5248. [&](const Request &req, Response & /*res*/) {
  5249. ASSERT_TRUE(req.has_param("key"));
  5250. EXPECT_EQ(req.get_param_value("key"), "value");
  5251. EXPECT_EQ(req.body, "content");
  5252. })
  5253. .Get("/last-request",
  5254. [&](const Request &req, Response & /*res*/) {
  5255. EXPECT_EQ("close", req.get_header_value("Connection"));
  5256. })
  5257. .Get(R"(/redirect/(\d+))",
  5258. [&](const Request &req, Response &res) {
  5259. auto num = std::stoi(req.matches[1]) + 1;
  5260. std::string url = "/redirect/" + std::to_string(num);
  5261. res.set_redirect(url);
  5262. })
  5263. .Post("/binary",
  5264. [&](const Request &req, Response &res) {
  5265. EXPECT_EQ(4U, req.body.size());
  5266. EXPECT_EQ("application/octet-stream",
  5267. req.get_header_value("Content-Type"));
  5268. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5269. res.set_content(req.body, "application/octet-stream");
  5270. })
  5271. .Put("/binary",
  5272. [&](const Request &req, Response &res) {
  5273. EXPECT_EQ(4U, req.body.size());
  5274. EXPECT_EQ("application/octet-stream",
  5275. req.get_header_value("Content-Type"));
  5276. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5277. res.set_content(req.body, "application/octet-stream");
  5278. })
  5279. .Patch("/binary",
  5280. [&](const Request &req, Response &res) {
  5281. EXPECT_EQ(4U, req.body.size());
  5282. EXPECT_EQ("application/octet-stream",
  5283. req.get_header_value("Content-Type"));
  5284. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5285. res.set_content(req.body, "application/octet-stream");
  5286. })
  5287. .Delete("/binary",
  5288. [&](const Request &req, Response &res) {
  5289. EXPECT_EQ(4U, req.body.size());
  5290. EXPECT_EQ("application/octet-stream",
  5291. req.get_header_value("Content-Type"));
  5292. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5293. res.set_content(req.body, "application/octet-stream");
  5294. })
  5295. .Get("/issue1772",
  5296. [&](const Request & /*req*/, Response &res) {
  5297. res.status = 401;
  5298. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5299. })
  5300. .Delete("/issue609",
  5301. [](const httplib::Request &, httplib::Response &res,
  5302. const httplib::ContentReader &) {
  5303. res.set_content("ok", "text/plain");
  5304. })
  5305. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5306. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5307. .Get("/compress",
  5308. [&](const Request & /*req*/, Response &res) {
  5309. res.set_content(
  5310. "12345678901234567890123456789012345678901234567890123456789"
  5311. "01234567890123456789012345678901234567890",
  5312. "text/plain");
  5313. })
  5314. .Get("/compress-with-charset",
  5315. [&](const Request & /*req*/, Response &res) {
  5316. res.set_content(
  5317. "12345678901234567890123456789012345678901234567890123456789"
  5318. "01234567890123456789012345678901234567890",
  5319. "application/json; charset=utf-8");
  5320. })
  5321. .Get("/nocompress",
  5322. [&](const Request & /*req*/, Response &res) {
  5323. res.set_content(
  5324. "12345678901234567890123456789012345678901234567890123456789"
  5325. "01234567890123456789012345678901234567890",
  5326. "application/octet-stream");
  5327. })
  5328. .Post("/compress-multipart",
  5329. [&](const Request &req, Response & /*res*/) {
  5330. EXPECT_EQ(2u, req.form.fields.size());
  5331. ASSERT_TRUE(!req.form.has_field("???"));
  5332. {
  5333. const auto &text = req.form.get_field("key1");
  5334. EXPECT_EQ("test", text);
  5335. }
  5336. {
  5337. const auto &text = req.form.get_field("key2");
  5338. EXPECT_EQ("--abcdefg123", text);
  5339. }
  5340. })
  5341. #endif
  5342. ;
  5343. persons_["john"] = "programmer";
  5344. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5345. svr_.wait_until_ready();
  5346. }
  5347. virtual void TearDown() {
  5348. svr_.stop();
  5349. if (!request_threads_.empty()) {
  5350. std::this_thread::sleep_for(std::chrono::seconds(1));
  5351. for (auto &t : request_threads_) {
  5352. t.join();
  5353. }
  5354. }
  5355. t_.join();
  5356. }
  5357. map<string, string> persons_;
  5358. #ifdef CPPHTTPLIB_SSL_ENABLED
  5359. SSLClient cli_;
  5360. SSLServer svr_;
  5361. #else
  5362. Client cli_;
  5363. Server svr_;
  5364. #endif
  5365. thread t_;
  5366. std::vector<thread> request_threads_;
  5367. };
  5368. TEST_F(ServerTest, GetMethod200) {
  5369. auto res = cli_.Get("/hi");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ("HTTP/1.1", res->version);
  5372. EXPECT_EQ(StatusCode::OK_200, res->status);
  5373. EXPECT_EQ("OK", res->reason);
  5374. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5375. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5376. EXPECT_EQ("Hello World!", res->body);
  5377. }
  5378. TEST_F(ServerTest, GetEmptyFile) {
  5379. auto res = cli_.Get("/empty_file");
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5383. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5384. EXPECT_EQ("", res->body);
  5385. }
  5386. TEST_F(ServerTest, GetFileContent) {
  5387. auto res = cli_.Get("/file_content");
  5388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5389. EXPECT_EQ(StatusCode::OK_200, res->status);
  5390. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5391. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5392. EXPECT_EQ("test.html", res->body);
  5393. }
  5394. TEST_F(ServerTest, GetFileContentWithRange) {
  5395. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5397. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5398. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5399. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5400. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5401. EXPECT_EQ("est", res->body);
  5402. }
  5403. TEST_F(ServerTest, GetFileContentWithContentType) {
  5404. auto res = cli_.Get("/file_content_with_content_type");
  5405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5406. EXPECT_EQ(StatusCode::OK_200, res->status);
  5407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5408. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5409. EXPECT_EQ("file\n", res->body);
  5410. }
  5411. TEST_F(ServerTest, GetInvalidFileContent) {
  5412. auto res = cli_.Get("/invalid_file_content");
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5415. }
  5416. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5417. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5419. EXPECT_EQ("HTTP/1.1", res->version);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5423. EXPECT_EQ("Hello World!", res->body);
  5424. }
  5425. TEST_F(ServerTest, GetMethod302) {
  5426. auto res = cli_.Get("/");
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. EXPECT_EQ(StatusCode::Found_302, res->status);
  5429. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5430. }
  5431. TEST_F(ServerTest, GetMethod302Redirect) {
  5432. cli_.set_follow_location(true);
  5433. auto res = cli_.Get("/");
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("Hello World!", res->body);
  5437. EXPECT_EQ("/hi", res->location);
  5438. }
  5439. TEST_F(ServerTest, GetMethod404) {
  5440. auto res = cli_.Get("/invalid");
  5441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5442. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5443. }
  5444. TEST_F(ServerTest, HeadMethod200) {
  5445. auto res = cli_.Head("/hi");
  5446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5449. EXPECT_TRUE(res->body.empty());
  5450. }
  5451. TEST_F(ServerTest, HeadMethod200Static) {
  5452. auto res = cli_.Head("/mount/dir/index.html");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5456. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5457. EXPECT_TRUE(res->body.empty());
  5458. }
  5459. TEST_F(ServerTest, HeadMethod404) {
  5460. auto res = cli_.Head("/invalid");
  5461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5462. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5463. EXPECT_TRUE(res->body.empty());
  5464. }
  5465. TEST_F(ServerTest, GetMethodPersonJohn) {
  5466. auto res = cli_.Get("/person/john");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::OK_200, res->status);
  5469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5470. EXPECT_EQ("programmer", res->body);
  5471. }
  5472. TEST_F(ServerTest, PostMethod1) {
  5473. auto res = cli_.Get("/person/john1");
  5474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5475. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5476. res = cli_.Post("/person", "name=john1&note=coder",
  5477. "application/x-www-form-urlencoded");
  5478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5479. ASSERT_EQ(StatusCode::OK_200, res->status);
  5480. res = cli_.Get("/person/john1");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5484. ASSERT_EQ("coder", res->body);
  5485. }
  5486. TEST_F(ServerTest, PostMethod2) {
  5487. auto res = cli_.Get("/person/john2");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5490. Params params;
  5491. params.emplace("name", "john2");
  5492. params.emplace("note", "coder");
  5493. res = cli_.Post("/person", params);
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. ASSERT_EQ(StatusCode::OK_200, res->status);
  5496. res = cli_.Get("/person/john2");
  5497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5498. ASSERT_EQ(StatusCode::OK_200, res->status);
  5499. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5500. ASSERT_EQ("coder", res->body);
  5501. }
  5502. TEST_F(ServerTest, PutMethod3) {
  5503. auto res = cli_.Get("/person/john3");
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5506. Params params;
  5507. params.emplace("name", "john3");
  5508. params.emplace("note", "coder");
  5509. res = cli_.Put("/person", params);
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. ASSERT_EQ(StatusCode::OK_200, res->status);
  5512. res = cli_.Get("/person/john3");
  5513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5514. ASSERT_EQ(StatusCode::OK_200, res->status);
  5515. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5516. ASSERT_EQ("coder", res->body);
  5517. }
  5518. TEST_F(ServerTest, DeleteMethod1) {
  5519. auto res = cli_.Get("/person/john4");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5522. Params params;
  5523. params.emplace("name", "john4");
  5524. params.emplace("note", "coder");
  5525. res = cli_.Post("/person", params);
  5526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5527. ASSERT_EQ(StatusCode::OK_200, res->status);
  5528. res = cli_.Get("/person/john4");
  5529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5530. ASSERT_EQ(StatusCode::OK_200, res->status);
  5531. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5532. ASSERT_EQ("coder", res->body);
  5533. Params delete_params;
  5534. delete_params.emplace("name", "john4");
  5535. res = cli_.Delete("/person", delete_params);
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. ASSERT_EQ(StatusCode::OK_200, res->status);
  5538. ASSERT_EQ("DELETED", res->body);
  5539. res = cli_.Get("/person/john4");
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5542. }
  5543. TEST_F(ServerTest, DeleteMethod2) {
  5544. auto res = cli_.Get("/person/john5");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5547. Params params;
  5548. params.emplace("name", "john5");
  5549. params.emplace("note", "developer");
  5550. res = cli_.Post("/person", params);
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. ASSERT_EQ(StatusCode::OK_200, res->status);
  5553. res = cli_.Get("/person/john5");
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. ASSERT_EQ(StatusCode::OK_200, res->status);
  5556. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5557. ASSERT_EQ("developer", res->body);
  5558. Params delete_params;
  5559. delete_params.emplace("name", "john5");
  5560. Headers headers;
  5561. headers.emplace("Custom-Header", "test-value");
  5562. res = cli_.Delete("/person", headers, delete_params);
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. ASSERT_EQ(StatusCode::OK_200, res->status);
  5565. ASSERT_EQ("DELETED", res->body);
  5566. res = cli_.Get("/person/john5");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, DeleteMethod3) {
  5571. auto res = cli_.Get("/person/john6");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5574. Params params;
  5575. params.emplace("name", "john6");
  5576. params.emplace("note", "tester");
  5577. res = cli_.Post("/person", params);
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. res = cli_.Get("/person/john6");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. ASSERT_EQ(StatusCode::OK_200, res->status);
  5583. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5584. ASSERT_EQ("tester", res->body);
  5585. Params delete_params;
  5586. delete_params.emplace("name", "john6");
  5587. Headers headers;
  5588. headers.emplace("Custom-Header", "test-value");
  5589. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5591. ASSERT_EQ(StatusCode::OK_200, res->status);
  5592. ASSERT_EQ("DELETED", res->body);
  5593. res = cli_.Get("/person/john6");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5596. }
  5597. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5598. Params params;
  5599. params.emplace("json", JSON_DATA);
  5600. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. ASSERT_EQ(StatusCode::OK_200, res->status);
  5603. ASSERT_EQ(JSON_DATA, res->body);
  5604. }
  5605. TEST_F(ServerTest, PostEmptyContent) {
  5606. auto res = cli_.Post("/empty", "", "text/plain");
  5607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5608. ASSERT_EQ(StatusCode::OK_200, res->status);
  5609. ASSERT_EQ("empty", res->body);
  5610. }
  5611. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5612. auto res = cli_.Post("/empty-no-content-type");
  5613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5614. ASSERT_EQ(StatusCode::OK_200, res->status);
  5615. ASSERT_EQ("empty-no-content-type", res->body);
  5616. }
  5617. TEST_F(ServerTest, PostPathOnly) {
  5618. auto res = cli_.Post("/path-only");
  5619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5620. ASSERT_EQ(StatusCode::OK_200, res->status);
  5621. ASSERT_EQ("path-only", res->body);
  5622. }
  5623. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5624. auto res = cli_.Post("/path-headers-only",
  5625. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. ASSERT_EQ(StatusCode::OK_200, res->status);
  5628. ASSERT_EQ("path-headers-only", res->body);
  5629. }
  5630. TEST_F(ServerTest, PostLarge) {
  5631. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. ASSERT_EQ(StatusCode::OK_200, res->status);
  5634. EXPECT_EQ(LARGE_DATA, res->body);
  5635. }
  5636. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5637. auto res = cli_.Put("/empty-no-content-type");
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. ASSERT_EQ(StatusCode::OK_200, res->status);
  5640. ASSERT_EQ("empty-no-content-type", res->body);
  5641. }
  5642. TEST_F(ServerTest, GetMethodDir) {
  5643. auto res = cli_.Get("/dir/");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. EXPECT_EQ(StatusCode::OK_200, res->status);
  5646. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5647. auto body = R"(<html>
  5648. <head>
  5649. </head>
  5650. <body>
  5651. <a href="/dir/test.html">Test</a>
  5652. <a href="/hi">hi</a>
  5653. </body>
  5654. </html>
  5655. )";
  5656. EXPECT_EQ(body, res->body);
  5657. }
  5658. TEST_F(ServerTest, GetMethodDirTest) {
  5659. auto res = cli_.Get("/dir/test.html");
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. EXPECT_EQ(StatusCode::OK_200, res->status);
  5662. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5663. EXPECT_EQ("test.html", res->body);
  5664. }
  5665. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5666. auto res = cli_.Get("/dir/../dir/test.html");
  5667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5668. EXPECT_EQ(StatusCode::OK_200, res->status);
  5669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5670. EXPECT_EQ("test.html", res->body);
  5671. }
  5672. TEST_F(ServerTest, GetMethodInvalidPath) {
  5673. auto res = cli_.Get("/dir/../test.html");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5676. }
  5677. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5678. auto res = cli_.Get("/../www/dir/test.html");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5681. }
  5682. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5683. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5686. }
  5687. TEST_F(ServerTest, GetMethodDirMountTest) {
  5688. auto res = cli_.Get("/mount/dir/test.html");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. EXPECT_EQ(StatusCode::OK_200, res->status);
  5691. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5692. EXPECT_EQ("test.html", res->body);
  5693. }
  5694. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5695. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. EXPECT_EQ(StatusCode::OK_200, res->status);
  5698. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5699. EXPECT_EQ("test.html", res->body);
  5700. }
  5701. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5702. auto res = cli_.Get("/mount/dir/../test.html");
  5703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5705. }
  5706. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5707. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5710. }
  5711. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5712. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. }
  5716. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5717. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5720. }
  5721. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5722. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5725. }
  5726. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5727. auto res = cli_.Get("/mount/dir");
  5728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5730. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5731. }
  5732. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5733. auto res = cli_.Get("//dir");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5736. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5737. }
  5738. TEST_F(ServerTest, PostMethod303) {
  5739. auto res = cli_.Post("/1", "body", "text/plain");
  5740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5741. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5742. EXPECT_EQ("/2", res->get_header_value("Location"));
  5743. }
  5744. TEST_F(ServerTest, PostMethod303Redirect) {
  5745. cli_.set_follow_location(true);
  5746. auto res = cli_.Post("/1", "body", "text/plain");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. EXPECT_EQ(StatusCode::OK_200, res->status);
  5749. EXPECT_EQ("redirected.", res->body);
  5750. EXPECT_EQ("/2", res->location);
  5751. }
  5752. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5753. auto res = cli_.Get("/dir/test.abcde");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::OK_200, res->status);
  5756. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5757. EXPECT_EQ("abcde", res->body);
  5758. }
  5759. TEST_F(ServerTest, StaticFileRange) {
  5760. auto res =
  5761. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5763. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5764. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5765. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5766. EXPECT_EQ(true, res->has_header("Content-Range"));
  5767. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5768. EXPECT_EQ(std::string("cd"), res->body);
  5769. }
  5770. TEST_F(ServerTest, StaticFileRanges) {
  5771. auto res = cli_.Get("/dir/test.abcde",
  5772. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5775. EXPECT_TRUE(
  5776. res->get_header_value("Content-Type")
  5777. .find(
  5778. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5779. 0);
  5780. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5781. }
  5782. TEST_F(ServerTest, StaticFileRangeHead) {
  5783. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5786. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5787. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5788. EXPECT_EQ(true, res->has_header("Content-Range"));
  5789. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5790. }
  5791. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5792. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5795. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5796. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5797. EXPECT_EQ(true, res->has_header("Content-Range"));
  5798. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5799. res->get_header_value("Content-Range"));
  5800. EXPECT_EQ("LAST\n", res->body);
  5801. }
  5802. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5803. auto res =
  5804. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5808. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5809. EXPECT_EQ(true, res->has_header("Content-Range"));
  5810. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5811. }
  5812. TEST_F(ServerTest, StaticFileBigFile) {
  5813. auto res = cli_.Get("/dir/1MB.txt");
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5817. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5818. }
  5819. TEST_F(ServerTest, InvalidBaseDirMount) {
  5820. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5821. }
  5822. TEST_F(ServerTest, Binary) {
  5823. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5824. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5825. "application/octet-stream");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. ASSERT_EQ(StatusCode::OK_200, res->status);
  5828. ASSERT_EQ(4U, res->body.size());
  5829. res = cli_.Put("/binary", binary.data(), binary.size(),
  5830. "application/octet-stream");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. ASSERT_EQ(StatusCode::OK_200, res->status);
  5833. ASSERT_EQ(4U, res->body.size());
  5834. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5835. "application/octet-stream");
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. ASSERT_EQ(StatusCode::OK_200, res->status);
  5838. ASSERT_EQ(4U, res->body.size());
  5839. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5840. "application/octet-stream");
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. ASSERT_EQ(StatusCode::OK_200, res->status);
  5843. ASSERT_EQ(4U, res->body.size());
  5844. }
  5845. TEST_F(ServerTest, BinaryString) {
  5846. auto binary = std::string("\x00\x01\x02\x03", 4);
  5847. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. ASSERT_EQ(StatusCode::OK_200, res->status);
  5850. ASSERT_EQ(4U, res->body.size());
  5851. res = cli_.Put("/binary", binary, "application/octet-stream");
  5852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5853. ASSERT_EQ(StatusCode::OK_200, res->status);
  5854. ASSERT_EQ(4U, res->body.size());
  5855. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. ASSERT_EQ(StatusCode::OK_200, res->status);
  5858. ASSERT_EQ(4U, res->body.size());
  5859. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5861. ASSERT_EQ(StatusCode::OK_200, res->status);
  5862. ASSERT_EQ(4U, res->body.size());
  5863. }
  5864. TEST_F(ServerTest, EmptyRequest) {
  5865. auto res = cli_.Get("");
  5866. ASSERT_TRUE(!res);
  5867. EXPECT_EQ(Error::Connection, res.error());
  5868. }
  5869. TEST_F(ServerTest, LongRequest) {
  5870. std::string request;
  5871. for (size_t i = 0; i < 545; i++) {
  5872. request += "/TooLongRequest";
  5873. }
  5874. request += "OK";
  5875. auto res = cli_.Get(request.c_str());
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5878. }
  5879. TEST_F(ServerTest, TooLongRequest) {
  5880. std::string request;
  5881. for (size_t i = 0; i < 546; i++) {
  5882. request += "/TooLongRequest";
  5883. }
  5884. request += "_NG";
  5885. auto start = std::chrono::high_resolution_clock::now();
  5886. cli_.set_keep_alive(true);
  5887. auto res = cli_.Get(request.c_str());
  5888. auto end = std::chrono::high_resolution_clock::now();
  5889. auto elapsed =
  5890. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5891. .count();
  5892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5893. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5894. EXPECT_LE(elapsed, 1000);
  5895. EXPECT_EQ("close", res->get_header_value("Connection"));
  5896. EXPECT_FALSE(cli_.is_socket_open());
  5897. }
  5898. TEST_F(ServerTest, AlmostTooLongRequest) {
  5899. // test for #2046 - URI length check shouldn't include other content on req
  5900. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5901. // leading /, space, HTTP/1.1)
  5902. std::string request =
  5903. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5904. auto res = cli_.Get(request.c_str());
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5907. }
  5908. TEST_F(ServerTest, LongHeader) {
  5909. Request req;
  5910. req.method = "GET";
  5911. req.path = "/hi";
  5912. std::string host_and_port;
  5913. host_and_port += HOST;
  5914. host_and_port += ":";
  5915. host_and_port += std::to_string(PORT);
  5916. req.headers.emplace("Host", host_and_port.c_str());
  5917. req.headers.emplace("Accept", "*/*");
  5918. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5919. req.headers.emplace(
  5920. "Header-Name",
  5921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5927. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5928. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5929. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5930. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5931. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5932. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5933. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5934. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5935. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5949. "@@@@@@@@@@@@@@@@");
  5950. auto res = std::make_shared<Response>();
  5951. auto error = Error::Success;
  5952. auto ret = cli_.send(req, *res, error);
  5953. ASSERT_TRUE(ret);
  5954. EXPECT_EQ(StatusCode::OK_200, res->status);
  5955. }
  5956. TEST_F(ServerTest, LongQueryValue) {
  5957. auto start = std::chrono::high_resolution_clock::now();
  5958. cli_.set_keep_alive(true);
  5959. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5960. auto end = std::chrono::high_resolution_clock::now();
  5961. auto elapsed =
  5962. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5963. .count();
  5964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5965. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5966. EXPECT_LE(elapsed, 1000);
  5967. EXPECT_EQ("close", res->get_header_value("Connection"));
  5968. EXPECT_FALSE(cli_.is_socket_open());
  5969. }
  5970. TEST_F(ServerTest, TooLongQueryValue) {
  5971. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5972. ASSERT_FALSE(res);
  5973. EXPECT_EQ(Error::Read, res.error());
  5974. }
  5975. TEST_F(ServerTest, TooLongHeader) {
  5976. Request req;
  5977. req.method = "GET";
  5978. req.path = "/hi";
  5979. std::string host_and_port;
  5980. host_and_port += HOST;
  5981. host_and_port += ":";
  5982. host_and_port += std::to_string(PORT);
  5983. req.headers.emplace("Host", host_and_port.c_str());
  5984. req.headers.emplace("Accept", "*/*");
  5985. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5986. req.headers.emplace(
  5987. "Header-Name",
  5988. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5989. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5990. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6016. "@@@@@@@@@@@@@@@@@");
  6017. auto res = std::make_shared<Response>();
  6018. auto error = Error::Success;
  6019. auto ret = cli_.send(req, *res, error);
  6020. ASSERT_TRUE(ret);
  6021. EXPECT_EQ(StatusCode::OK_200, res->status);
  6022. }
  6023. TEST_F(ServerTest, HeaderCountAtLimit) {
  6024. // Test with headers just under the 100 limit
  6025. httplib::Headers headers;
  6026. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6027. // This should keep us just under the 100 header limit
  6028. for (int i = 0; i < 95; i++) {
  6029. std::string name = "X-Test-Header-" + std::to_string(i);
  6030. std::string value = "value" + std::to_string(i);
  6031. headers.emplace(name, value);
  6032. }
  6033. // This should work fine as we're under the limit
  6034. auto res = cli_.Get("/hi", headers);
  6035. EXPECT_TRUE(res);
  6036. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6037. }
  6038. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6039. // Test with many headers to exceed the 100 limit
  6040. httplib::Headers headers;
  6041. // Add 150 headers to definitely exceed the 100 limit
  6042. for (int i = 0; i < 150; i++) {
  6043. std::string name = "X-Test-Header-" + std::to_string(i);
  6044. std::string value = "value" + std::to_string(i);
  6045. headers.emplace(name, value);
  6046. }
  6047. // This should fail due to exceeding header count limit
  6048. cli_.set_keep_alive(true);
  6049. auto res = cli_.Get("/hi", headers);
  6050. // The server should respond with 400 Bad Request
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6053. EXPECT_EQ("close", res->get_header_value("Connection"));
  6054. EXPECT_FALSE(cli_.is_socket_open());
  6055. }
  6056. TEST_F(ServerTest, PercentEncoding) {
  6057. auto res = cli_.Get("/e%6edwith%");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::OK_200, res->status);
  6060. }
  6061. TEST_F(ServerTest, PercentEncodingUnicode) {
  6062. auto res = cli_.Get("/e%u006edwith%");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. }
  6066. TEST_F(ServerTest, InvalidPercentEncoding) {
  6067. auto res = cli_.Get("/%endwith%");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6070. }
  6071. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6072. auto res = cli_.Get("/%uendwith%");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6075. }
  6076. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6077. auto res = cli_.Get("/hello?aaa=bbb%");
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6080. }
  6081. TEST_F(ServerTest, PlusSignEncoding) {
  6082. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6084. EXPECT_EQ(StatusCode::OK_200, res->status);
  6085. EXPECT_EQ("a +b", res->body);
  6086. }
  6087. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6088. // This test simulates a potential DoS attack using many headers
  6089. // to verify our security fix prevents memory exhaustion
  6090. httplib::Headers attack_headers;
  6091. // Attempt to add many headers like an attacker would (200 headers to far
  6092. // exceed limit)
  6093. for (int i = 0; i < 200; i++) {
  6094. std::string name = "X-Attack-Header-" + std::to_string(i);
  6095. std::string value = "attack_payload_" + std::to_string(i);
  6096. attack_headers.emplace(name, value);
  6097. }
  6098. // Try to POST with excessive headers
  6099. cli_.set_keep_alive(true);
  6100. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6101. // Should either fail or return 400 Bad Request due to security limit
  6102. if (res) {
  6103. // If we get a response, it should be 400 Bad Request
  6104. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6105. EXPECT_EQ("close", res->get_header_value("Connection"));
  6106. }
  6107. EXPECT_FALSE(cli_.is_socket_open());
  6108. }
  6109. TEST_F(ServerTest, MultipartFormData) {
  6110. UploadFormDataItems items = {
  6111. {"text1", "text default", "", ""},
  6112. {"text2", "aωb", "", ""},
  6113. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6114. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6115. {"file3", "", "", "application/octet-stream"},
  6116. {"file4", "", "", " application/json tmp-string "}};
  6117. auto res = cli_.Post("/multipart", items);
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::OK_200, res->status);
  6120. }
  6121. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6122. UploadFormDataItems items = {
  6123. {"text", "default text", "", ""},
  6124. {"multi_text1", "aaaaa", "", ""},
  6125. {"multi_text1", "bbbbb", "", ""},
  6126. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6127. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6128. "application/json"},
  6129. };
  6130. auto res = cli_.Post("/multipart/multi_file_values", items);
  6131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6132. EXPECT_EQ(StatusCode::OK_200, res->status);
  6133. }
  6134. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6135. auto res = cli_.Get("/hi");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6139. EXPECT_EQ("Hello World!", res->body);
  6140. }
  6141. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6142. Request req;
  6143. req.method = "POST";
  6144. req.path = "/chunked";
  6145. std::string host_and_port;
  6146. host_and_port += HOST;
  6147. host_and_port += ":";
  6148. host_and_port += std::to_string(PORT);
  6149. req.headers.emplace("Host", host_and_port.c_str());
  6150. req.headers.emplace("Accept", "*/*");
  6151. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6152. req.headers.emplace("Content-Type", "text/plain");
  6153. req.headers.emplace("Content-Length", "0");
  6154. req.headers.emplace(
  6155. "Transfer-Encoding",
  6156. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6157. // Client does not chunk, so make a chunked body manually.
  6158. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6159. auto res = std::make_shared<Response>();
  6160. auto error = Error::Success;
  6161. auto ret = cli_.send(req, *res, error);
  6162. ASSERT_TRUE(ret);
  6163. EXPECT_EQ(StatusCode::OK_200, res->status);
  6164. }
  6165. template <typename ClientT>
  6166. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6167. int expected_status) {
  6168. Request req;
  6169. req.method = "POST";
  6170. req.path = "/chunked";
  6171. std::string host_and_port;
  6172. host_and_port += HOST;
  6173. host_and_port += ":";
  6174. host_and_port += std::to_string(PORT);
  6175. req.headers.emplace("Host", host_and_port.c_str());
  6176. req.headers.emplace("Content-Length", "0");
  6177. req.headers.emplace("Transfer-Encoding", "chunked");
  6178. req.body = body;
  6179. auto res = std::make_shared<Response>();
  6180. auto error = Error::Success;
  6181. ASSERT_TRUE(cli.send(req, *res, error));
  6182. EXPECT_EQ(expected_status, res->status);
  6183. }
  6184. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6185. // rather than treat them as valid lengths.
  6186. template <typename ClientT>
  6187. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6188. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6189. }
  6190. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6191. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6192. }
  6193. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6194. expect_chunked_body_rejected(
  6195. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6196. }
  6197. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6198. // chunk-size line carries no CR, LF or other control character ahead of its
  6199. // terminator. Such a line must be refused rather than read as extension text.
  6200. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6201. expect_chunked_body_rejected(
  6202. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6203. }
  6204. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6205. expect_chunked_body_rejected(
  6206. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6207. }
  6208. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6209. expect_chunked_body_rejected(
  6210. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6211. }
  6212. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6213. // The literal stays split: a hex escape consumes every hex digit that
  6214. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6215. expect_chunked_body_rejected(
  6216. cli_, "4;a\x01"
  6217. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6218. }
  6219. TEST_F(ServerTest, AcceptsChunkExtension) {
  6220. expect_chunked_body_status(cli_,
  6221. "4;name=value\r\ndech\r\n"
  6222. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6223. "0;last\r\n\r\n",
  6224. StatusCode::OK_200);
  6225. }
  6226. TEST_F(ServerTest, GetStreamed2) {
  6227. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6230. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6231. EXPECT_EQ(true, res->has_header("Content-Range"));
  6232. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6233. EXPECT_EQ(std::string("ab"), res->body);
  6234. }
  6235. TEST_F(ServerTest, GetStreamed) {
  6236. auto res = cli_.Get("/streamed");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ(StatusCode::OK_200, res->status);
  6239. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6240. EXPECT_EQ(std::string("aaabbb"), res->body);
  6241. }
  6242. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6243. auto res = cli_.Get("/streamed-without-length",
  6244. Headers{make_range_header({{0, -1}})});
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. EXPECT_EQ(StatusCode::OK_200, res->status);
  6247. EXPECT_EQ(false, res->has_header("Content-Length"));
  6248. EXPECT_EQ(false, res->has_header("Content-Range"));
  6249. EXPECT_EQ(std::string("abcdefg"), res->body);
  6250. }
  6251. TEST_F(ServerTest, GetStreamedWithRange1) {
  6252. auto res =
  6253. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6256. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6257. EXPECT_EQ(true, res->has_header("Content-Range"));
  6258. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6259. EXPECT_EQ(std::string("def"), res->body);
  6260. }
  6261. TEST_F(ServerTest, GetStreamedWithRange2) {
  6262. auto res =
  6263. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6265. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6266. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6267. EXPECT_EQ(true, res->has_header("Content-Range"));
  6268. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6269. EXPECT_EQ(std::string("bcdefg"), res->body);
  6270. }
  6271. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6272. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6275. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6276. EXPECT_EQ(true, res->has_header("Content-Range"));
  6277. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6278. EXPECT_EQ(std::string("efg"), res->body);
  6279. }
  6280. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6281. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6282. // the entire representation.
  6283. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6284. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6287. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6288. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6289. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6290. }
  6291. }
  6292. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6293. auto res =
  6294. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6297. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6298. EXPECT_EQ(false, res->has_header("Content-Range"));
  6299. EXPECT_EQ(0U, res->body.size());
  6300. }
  6301. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6302. // Only a 206 is served as a partial representation. Under any other status
  6303. // `apply_ranges()` reported the full content length, so the body must match
  6304. // that header, and the content provider must never be asked for an offset
  6305. // outside the representation.
  6306. auto check = [&](int status, const char *range) {
  6307. auto path =
  6308. std::string("/streamed-with-range?status=") + std::to_string(status);
  6309. auto ctx = path + " Range: " + range;
  6310. auto res = cli_.Get(path, Headers{{"Range", range}});
  6311. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6312. EXPECT_EQ(status, res->status) << ctx;
  6313. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6315. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6316. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6317. };
  6318. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6319. check(403, "bytes=3-5");
  6320. // The offset is far past the representation.
  6321. check(403, "bytes=100000-100200");
  6322. // `first_pos` is still -1 here, and the bounds asserts in
  6323. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6324. check(403, "bytes=-3");
  6325. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6326. // multipart branch would have written one that is empty.
  6327. check(403, "bytes=1-2, 4-5");
  6328. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6329. // covers the whole representation.
  6330. check(200, "bytes=3-5");
  6331. check(200, "bytes=1-2, 4-5");
  6332. }
  6333. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6334. auto res =
  6335. cli_.Get("/streamed-with-range",
  6336. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6337. "92233720368547758079223372036854775807"}});
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6340. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6341. EXPECT_EQ(false, res->has_header("Content-Range"));
  6342. EXPECT_EQ(0U, res->body.size());
  6343. }
  6344. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6345. auto res = cli_.Get(
  6346. "/with-range",
  6347. Headers{{"Range",
  6348. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6349. {"Accept-Encoding", ""}});
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6352. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6353. EXPECT_EQ(true, res->has_header("Content-Range"));
  6354. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6355. EXPECT_EQ(std::string("abcdefg"), res->body);
  6356. }
  6357. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6358. auto res = cli_.Get("/with-range", Headers{
  6359. {"Range", "bytes=0-"},
  6360. {"Accept-Encoding", ""},
  6361. });
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6364. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6365. EXPECT_EQ(true, res->has_header("Content-Range"));
  6366. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6367. EXPECT_EQ(std::string("abcdefg"), res->body);
  6368. }
  6369. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6370. auto res = cli_.Get("/streamed-with-range",
  6371. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6374. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6375. EXPECT_EQ(false, res->has_header("Content-Range"));
  6376. EXPECT_EQ(267U, res->body.size());
  6377. // Check that both range contents are present
  6378. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6379. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6380. // Check that Content-Range headers are present for both ranges
  6381. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6382. std::string::npos);
  6383. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6384. std::string::npos);
  6385. }
  6386. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6387. Ranges ranges;
  6388. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6389. ranges.emplace_back(0, -1);
  6390. }
  6391. auto res = cli_.Get("/streamed-with-range?error",
  6392. Headers{{make_range_header(ranges)}});
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6395. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6396. EXPECT_EQ(false, res->has_header("Content-Range"));
  6397. EXPECT_EQ(0U, res->body.size());
  6398. }
  6399. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6400. auto res = cli_.Get("/streamed-with-range",
  6401. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6404. EXPECT_EQ(5U, res->body.size());
  6405. // Check that overlapping ranges are coalesced into a single range
  6406. EXPECT_EQ("bcdef", res->body);
  6407. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6408. // Should be single range, not multipart
  6409. EXPECT_TRUE(res->has_header("Content-Range"));
  6410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6411. }
  6412. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6413. auto res = cli_.Get("/streamed-with-range",
  6414. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6417. EXPECT_EQ(268U, res->body.size());
  6418. // Check that both range contents are present
  6419. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6420. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6421. // Check that Content-Range headers are present for both ranges
  6422. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6423. std::string::npos);
  6424. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6425. std::string::npos);
  6426. }
  6427. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6428. auto res = cli_.Get("/streamed-with-range",
  6429. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6432. EXPECT_EQ(269U, res->body.size());
  6433. // Check that both duplicate range contents are present
  6434. size_t first_abc = res->body.find("abc\r\n");
  6435. EXPECT_TRUE(first_abc != std::string::npos);
  6436. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6437. EXPECT_TRUE(second_abc != std::string::npos);
  6438. // Check that Content-Range headers are present for both ranges
  6439. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6440. EXPECT_TRUE(first_range != std::string::npos);
  6441. size_t second_range =
  6442. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6443. EXPECT_TRUE(second_range != std::string::npos);
  6444. }
  6445. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6446. auto res =
  6447. cli_.Get("/streamed-with-range?error",
  6448. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6451. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6452. EXPECT_EQ(false, res->has_header("Content-Range"));
  6453. EXPECT_EQ(0U, res->body.size());
  6454. }
  6455. TEST_F(ServerTest, GetStreamedEndless) {
  6456. uint64_t offset = 0;
  6457. auto res = cli_.Get("/streamed-cancel",
  6458. [&](const char * /*data*/, uint64_t data_length) {
  6459. if (offset < 100) {
  6460. offset += data_length;
  6461. return true;
  6462. }
  6463. return false;
  6464. });
  6465. ASSERT_TRUE(!res);
  6466. EXPECT_EQ(Error::Canceled, res.error());
  6467. }
  6468. TEST_F(ServerTest, ClientStop) {
  6469. std::atomic_size_t count{4};
  6470. std::vector<std::thread> threads;
  6471. for (auto i = count.load(); i != 0; --i) {
  6472. threads.emplace_back([&]() {
  6473. auto res = cli_.Get("/streamed-cancel",
  6474. [&](const char *, uint64_t) { return true; });
  6475. --count;
  6476. ASSERT_TRUE(!res);
  6477. EXPECT_TRUE(res.error() == Error::Canceled ||
  6478. res.error() == Error::Read || res.error() == Error::Write);
  6479. });
  6480. }
  6481. std::this_thread::sleep_for(std::chrono::seconds(2));
  6482. while (count != 0) {
  6483. cli_.stop();
  6484. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6485. }
  6486. for (auto &t : threads) {
  6487. t.join();
  6488. }
  6489. }
  6490. TEST_F(ServerTest, GetWithRange1) {
  6491. auto res = cli_.Get("/with-range", Headers{
  6492. make_range_header({{3, 5}}),
  6493. {"Accept-Encoding", ""},
  6494. });
  6495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6496. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6497. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6498. EXPECT_EQ(true, res->has_header("Content-Range"));
  6499. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6500. EXPECT_EQ(std::string("def"), res->body);
  6501. }
  6502. TEST_F(ServerTest, GetWithRange2) {
  6503. auto res = cli_.Get("/with-range", Headers{
  6504. make_range_header({{1, -1}}),
  6505. {"Accept-Encoding", ""},
  6506. });
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6509. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6510. EXPECT_EQ(true, res->has_header("Content-Range"));
  6511. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6512. EXPECT_EQ(std::string("bcdefg"), res->body);
  6513. }
  6514. TEST_F(ServerTest, GetWithRange3) {
  6515. auto res = cli_.Get("/with-range", Headers{
  6516. make_range_header({{0, 0}}),
  6517. {"Accept-Encoding", ""},
  6518. });
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6521. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6522. EXPECT_EQ(true, res->has_header("Content-Range"));
  6523. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6524. EXPECT_EQ(std::string("a"), res->body);
  6525. }
  6526. TEST_F(ServerTest, GetWithRange4) {
  6527. auto res = cli_.Get("/with-range", Headers{
  6528. make_range_header({{-1, 2}}),
  6529. {"Accept-Encoding", ""},
  6530. });
  6531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6533. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6534. EXPECT_EQ(true, res->has_header("Content-Range"));
  6535. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6536. EXPECT_EQ(std::string("fg"), res->body);
  6537. }
  6538. TEST_F(ServerTest, GetWithRange5) {
  6539. auto res = cli_.Get("/with-range", Headers{
  6540. make_range_header({{0, 5}}),
  6541. {"Accept-Encoding", ""},
  6542. });
  6543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6545. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6546. EXPECT_EQ(true, res->has_header("Content-Range"));
  6547. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6548. EXPECT_EQ(std::string("abcdef"), res->body);
  6549. }
  6550. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6551. auto res =
  6552. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6555. }
  6556. TEST_F(ServerTest, GetWithRangeMultipart) {
  6557. auto res =
  6558. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6560. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6561. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6562. EXPECT_EQ(false, res->has_header("Content-Range"));
  6563. EXPECT_EQ(267U, res->body.size());
  6564. }
  6565. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6566. auto res = cli_.Get("/with-range",
  6567. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6570. }
  6571. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6572. auto res = cli_.Get("/with-range-customized-response",
  6573. Headers{{make_range_header({{1, 2}})}});
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6576. EXPECT_EQ(true, res->has_header("Content-Length"));
  6577. EXPECT_EQ(false, res->has_header("Content-Range"));
  6578. EXPECT_EQ(JSON_DATA, res->body);
  6579. }
  6580. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6581. auto res = cli_.Get("/with-range-customized-response",
  6582. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6585. EXPECT_EQ(true, res->has_header("Content-Length"));
  6586. EXPECT_EQ(false, res->has_header("Content-Range"));
  6587. EXPECT_EQ(JSON_DATA, res->body);
  6588. }
  6589. TEST_F(ServerTest, Issue1772) {
  6590. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6593. }
  6594. TEST_F(ServerTest, Issue609) {
  6595. auto res = cli_.Delete("/issue609");
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. EXPECT_EQ(StatusCode::OK_200, res->status);
  6598. EXPECT_EQ(std::string("ok"), res->body);
  6599. }
  6600. TEST_F(ServerTest, GetStreamedChunked) {
  6601. auto res = cli_.Get("/streamed-chunked");
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::OK_200, res->status);
  6604. EXPECT_EQ(std::string("123456789"), res->body);
  6605. }
  6606. TEST_F(ServerTest, GetStreamedChunked2) {
  6607. auto res = cli_.Get("/streamed-chunked2");
  6608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6609. EXPECT_EQ(StatusCode::OK_200, res->status);
  6610. EXPECT_EQ(std::string("123456789"), res->body);
  6611. }
  6612. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6613. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::OK_200, res->status);
  6616. EXPECT_EQ(std::string("123456789"), res->body);
  6617. EXPECT_TRUE(res->has_header("Trailer"));
  6618. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6619. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6620. // Trailers are now stored separately from headers (security fix)
  6621. EXPECT_EQ(2U, res->trailers.size());
  6622. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6623. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6624. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6625. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6626. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6627. // Verify trailers are NOT in headers (security verification)
  6628. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6629. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6630. }
  6631. TEST_F(ServerTest, LargeChunkedPost) {
  6632. Request req;
  6633. req.method = "POST";
  6634. req.path = "/large-chunked";
  6635. std::string host_and_port;
  6636. host_and_port += HOST;
  6637. host_and_port += ":";
  6638. host_and_port += std::to_string(PORT);
  6639. req.headers.emplace("Host", host_and_port.c_str());
  6640. req.headers.emplace("Accept", "*/*");
  6641. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6642. req.headers.emplace("Content-Type", "text/plain");
  6643. req.headers.emplace("Content-Length", "0");
  6644. req.headers.emplace("Transfer-Encoding", "chunked");
  6645. std::string long_string(30 * 1024u, 'a');
  6646. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6647. // Attempt to make a large enough post to exceed OS buffers, to test that
  6648. // the server handles short reads if the full chunk data isn't available.
  6649. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6650. auto res = std::make_shared<Response>();
  6651. auto error = Error::Success;
  6652. auto ret = cli_.send(req, *res, error);
  6653. ASSERT_TRUE(ret);
  6654. EXPECT_EQ(StatusCode::OK_200, res->status);
  6655. }
  6656. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6657. auto res = cli_.Get("/remote_addr");
  6658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6659. EXPECT_EQ(StatusCode::OK_200, res->status);
  6660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6661. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6662. }
  6663. TEST_F(ServerTest, GetMethodLocalAddr) {
  6664. auto res = cli_.Get("/local_addr");
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::OK_200, res->status);
  6667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6668. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6669. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6670. }
  6671. TEST_F(ServerTest, HTTPResponseSplitting) {
  6672. auto res = cli_.Get("/http_response_splitting");
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::OK_200, res->status);
  6675. }
  6676. TEST_F(ServerTest, SlowRequest) {
  6677. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6678. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6679. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6680. }
  6681. #if 0
  6682. TEST_F(ServerTest, SlowPost) {
  6683. char buffer[64 * 1024];
  6684. memset(buffer, 0x42, sizeof(buffer));
  6685. auto res = cli_.Post(
  6686. "/slowpost", 64 * 1024 * 1024,
  6687. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6688. auto ret = sink.write(buffer, sizeof(buffer));
  6689. EXPECT_TRUE(ret);
  6690. return true;
  6691. },
  6692. "text/plain");
  6693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. }
  6696. TEST_F(ServerTest, SlowPostFail) {
  6697. char buffer[64 * 1024];
  6698. memset(buffer, 0x42, sizeof(buffer));
  6699. cli_.set_write_timeout(std::chrono::seconds(0));
  6700. auto res = cli_.Post(
  6701. "/slowpost", 64 * 1024 * 1024,
  6702. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6703. sink.write(buffer, sizeof(buffer));
  6704. return true;
  6705. },
  6706. "text/plain");
  6707. ASSERT_TRUE(!res);
  6708. EXPECT_EQ(Error::Write, res.error());
  6709. }
  6710. #endif
  6711. TEST_F(ServerTest, Put) {
  6712. auto res = cli_.Put("/put", "PUT", "text/plain");
  6713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6714. EXPECT_EQ(StatusCode::OK_200, res->status);
  6715. EXPECT_EQ("PUT", res->body);
  6716. }
  6717. TEST_F(ServerTest, PutWithContentProvider) {
  6718. auto res = cli_.Put(
  6719. "/put", 3,
  6720. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6721. sink.os << "PUT";
  6722. return true;
  6723. },
  6724. "text/plain");
  6725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6726. EXPECT_EQ(StatusCode::OK_200, res->status);
  6727. EXPECT_EQ("PUT", res->body);
  6728. }
  6729. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6730. auto res = cli_.Post(
  6731. "/post", 42,
  6732. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6733. return false;
  6734. },
  6735. "text/plain");
  6736. ASSERT_TRUE(!res);
  6737. EXPECT_EQ(Error::Canceled, res.error());
  6738. }
  6739. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6740. auto res = cli_.Put(
  6741. "/put",
  6742. [](size_t /*offset*/, DataSink &sink) {
  6743. sink.os << "PUT";
  6744. sink.done();
  6745. return true;
  6746. },
  6747. "text/plain");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ(StatusCode::OK_200, res->status);
  6750. EXPECT_EQ("PUT", res->body);
  6751. }
  6752. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6753. auto res = cli_.Post(
  6754. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6755. "text/plain");
  6756. ASSERT_TRUE(!res);
  6757. EXPECT_EQ(Error::Canceled, res.error());
  6758. }
  6759. TEST_F(ServerTest, PostLoopBack) {
  6760. std::string body;
  6761. auto res = cli_.Post(
  6762. "/post-loopback", 9,
  6763. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6764. EXPECT_EQ(9u, length);
  6765. sink.write("123", 3);
  6766. sink.write("456", 3);
  6767. sink.write("789", 3);
  6768. return true;
  6769. },
  6770. "text/plain",
  6771. [&body](const char *data, size_t data_length) {
  6772. body.append(data, data_length);
  6773. return true;
  6774. });
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::OK_200, res->status);
  6777. EXPECT_EQ("123456789", body);
  6778. }
  6779. TEST_F(ServerTest, PutLoopBack) {
  6780. std::string body;
  6781. auto res = cli_.Put(
  6782. "/put-loopback", 9,
  6783. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6784. EXPECT_EQ(9u, length);
  6785. sink.write("123", 3);
  6786. sink.write("456", 3);
  6787. sink.write("789", 3);
  6788. return true;
  6789. },
  6790. "text/plain",
  6791. [&body](const char *data, size_t data_length) {
  6792. body.append(data, data_length);
  6793. return true;
  6794. });
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. EXPECT_EQ("123456789", body);
  6798. }
  6799. TEST_F(ServerTest, PatchLoopBack) {
  6800. std::string body;
  6801. auto res = cli_.Patch(
  6802. "/patch-loopback", 9,
  6803. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6804. EXPECT_EQ(9u, length);
  6805. sink.write("123", 3);
  6806. sink.write("456", 3);
  6807. sink.write("789", 3);
  6808. return true;
  6809. },
  6810. "text/plain",
  6811. [&body](const char *data, size_t data_length) {
  6812. body.append(data, data_length);
  6813. return true;
  6814. });
  6815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6816. EXPECT_EQ(StatusCode::OK_200, res->status);
  6817. EXPECT_EQ("123456789", body);
  6818. }
  6819. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6820. std::string body;
  6821. auto res = cli_.Post(
  6822. "/post-loopback",
  6823. [](size_t /*offset*/, DataSink &sink) {
  6824. sink.write("123", 3);
  6825. sink.write("456", 3);
  6826. sink.write("789", 3);
  6827. sink.done();
  6828. return true;
  6829. },
  6830. "text/plain",
  6831. [&body](const char *data, size_t data_length) {
  6832. body.append(data, data_length);
  6833. return true;
  6834. });
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. EXPECT_EQ(StatusCode::OK_200, res->status);
  6837. EXPECT_EQ("123456789", body);
  6838. }
  6839. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6840. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6841. cli_.set_compress(true);
  6842. auto res = cli_.Put(
  6843. "/put", 3,
  6844. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6845. sink.os << "PUT";
  6846. return true;
  6847. },
  6848. "text/plain");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::OK_200, res->status);
  6851. EXPECT_EQ("PUT", res->body);
  6852. }
  6853. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6854. cli_.set_compress(true);
  6855. auto res = cli_.Post(
  6856. "/post", 42,
  6857. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6858. return false;
  6859. },
  6860. "text/plain");
  6861. ASSERT_TRUE(!res);
  6862. EXPECT_EQ(Error::Canceled, res.error());
  6863. }
  6864. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6865. cli_.set_compress(true);
  6866. auto res = cli_.Put(
  6867. "/put",
  6868. [](size_t /*offset*/, DataSink &sink) {
  6869. sink.os << "PUT";
  6870. sink.done();
  6871. return true;
  6872. },
  6873. "text/plain");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("PUT", res->body);
  6877. }
  6878. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6879. cli_.set_compress(true);
  6880. auto res = cli_.Post(
  6881. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6882. "text/plain");
  6883. ASSERT_TRUE(!res);
  6884. EXPECT_EQ(Error::Canceled, res.error());
  6885. }
  6886. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6887. cli_.set_compress(true);
  6888. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. EXPECT_EQ(LARGE_DATA, res->body);
  6892. }
  6893. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6894. #ifdef CPPHTTPLIB_SSL_ENABLED
  6895. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6896. Client cli(s.c_str());
  6897. cli.enable_server_certificate_verification(false);
  6898. #else
  6899. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6900. Client cli(s.c_str());
  6901. #endif
  6902. cli.set_compress(true);
  6903. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. EXPECT_EQ(StatusCode::OK_200, res->status);
  6906. EXPECT_EQ(LARGE_DATA, res->body);
  6907. // The compressed size should be less than a 10th of the original. May vary
  6908. // depending on the zlib library.
  6909. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6910. static_cast<uint64_t>(10 * 1024 * 1024));
  6911. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6912. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6913. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6914. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6915. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6916. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6917. #endif
  6918. }
  6919. TEST_F(ServerTest, PutContentWithDeflate) {
  6920. cli_.set_compress(false);
  6921. Headers headers;
  6922. headers.emplace("Content-Encoding", "deflate");
  6923. // PUT in deflate format:
  6924. auto res = cli_.Put("/put", headers,
  6925. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::OK_200, res->status);
  6928. EXPECT_EQ("PUT", res->body);
  6929. }
  6930. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6931. Headers headers;
  6932. headers.emplace("Accept-Encoding", "gzip, deflate");
  6933. auto res = cli_.Get("/streamed-chunked", headers);
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. EXPECT_EQ(std::string("123456789"), res->body);
  6937. }
  6938. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6939. Headers headers;
  6940. headers.emplace("Accept-Encoding", "gzip, deflate");
  6941. auto res = cli_.Get("/streamed-chunked2", headers);
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::OK_200, res->status);
  6944. EXPECT_EQ(std::string("123456789"), res->body);
  6945. }
  6946. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6947. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. }
  6951. TEST(GzipDecompressor, ChunkedDecompression) {
  6952. std::string data;
  6953. for (size_t i = 0; i < 32 * 1024; ++i) {
  6954. data.push_back(static_cast<char>('a' + i % 26));
  6955. }
  6956. std::string compressed_data;
  6957. {
  6958. httplib::detail::gzip_compressor compressor;
  6959. bool result = compressor.compress(
  6960. data.data(), data.size(),
  6961. /*last=*/true,
  6962. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6963. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6964. compressed_data_size);
  6965. return true;
  6966. });
  6967. ASSERT_TRUE(result);
  6968. }
  6969. std::string decompressed_data;
  6970. {
  6971. httplib::detail::gzip_decompressor decompressor;
  6972. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6973. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6974. size_t chunk_size = 130;
  6975. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6976. chunk_begin += chunk_size) {
  6977. size_t current_chunk_size =
  6978. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6979. bool result = decompressor.decompress(
  6980. compressed_data.data() + chunk_begin, current_chunk_size,
  6981. [&](const char *decompressed_data_chunk,
  6982. size_t decompressed_data_chunk_size) {
  6983. decompressed_data.insert(decompressed_data.size(),
  6984. decompressed_data_chunk,
  6985. decompressed_data_chunk_size);
  6986. return true;
  6987. });
  6988. ASSERT_TRUE(result);
  6989. }
  6990. }
  6991. ASSERT_EQ(data, decompressed_data);
  6992. }
  6993. TEST(GzipDecompressor, DeflateDecompression) {
  6994. std::string original_text = "Raw deflate without gzip";
  6995. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6996. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6997. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6998. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6999. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7000. std::string decompressed_data;
  7001. {
  7002. httplib::detail::gzip_decompressor decompressor;
  7003. bool result = decompressor.decompress(
  7004. compressed_data.data(), compressed_data.size(),
  7005. [&](const char *decompressed_data_chunk,
  7006. size_t decompressed_data_chunk_size) {
  7007. decompressed_data.insert(decompressed_data.size(),
  7008. decompressed_data_chunk,
  7009. decompressed_data_chunk_size);
  7010. return true;
  7011. });
  7012. ASSERT_TRUE(result);
  7013. }
  7014. ASSERT_EQ(original_text, decompressed_data);
  7015. }
  7016. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7017. std::string original_text = "Raw deflate without gzip";
  7018. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7019. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7020. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7021. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7022. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7023. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7024. std::string decompressed_data;
  7025. {
  7026. httplib::detail::gzip_decompressor decompressor;
  7027. bool result = decompressor.decompress(
  7028. compressed_data.data(), compressed_data.size(),
  7029. [&](const char *decompressed_data_chunk,
  7030. size_t decompressed_data_chunk_size) {
  7031. decompressed_data.insert(decompressed_data.size(),
  7032. decompressed_data_chunk,
  7033. decompressed_data_chunk_size);
  7034. return true;
  7035. });
  7036. ASSERT_TRUE(result);
  7037. }
  7038. ASSERT_EQ(original_text, decompressed_data);
  7039. }
  7040. #endif
  7041. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7042. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7043. Headers headers;
  7044. headers.emplace("Accept-Encoding", "br");
  7045. auto res = cli_.Get("/streamed-chunked", headers);
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. EXPECT_EQ(StatusCode::OK_200, res->status);
  7048. EXPECT_EQ(std::string("123456789"), res->body);
  7049. }
  7050. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7051. Headers headers;
  7052. headers.emplace("Accept-Encoding", "br");
  7053. auto res = cli_.Get("/streamed-chunked2", headers);
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::OK_200, res->status);
  7056. EXPECT_EQ(std::string("123456789"), res->body);
  7057. }
  7058. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7059. cli_.set_compress(true);
  7060. auto res = cli_.Put(
  7061. "/put", 3,
  7062. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7063. sink.os << "PUT";
  7064. return true;
  7065. },
  7066. "text/plain");
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. EXPECT_EQ("PUT", res->body);
  7070. }
  7071. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7072. cli_.set_compress(true);
  7073. auto res = cli_.Put(
  7074. "/put",
  7075. [](size_t /*offset*/, DataSink &sink) {
  7076. sink.os << "PUT";
  7077. sink.done();
  7078. return true;
  7079. },
  7080. "text/plain");
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. EXPECT_EQ("PUT", res->body);
  7084. }
  7085. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7086. cli_.set_compress(true);
  7087. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::OK_200, res->status);
  7090. EXPECT_EQ(LARGE_DATA, res->body);
  7091. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7092. }
  7093. #endif
  7094. TEST_F(ServerTest, Patch) {
  7095. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7097. EXPECT_EQ(StatusCode::OK_200, res->status);
  7098. EXPECT_EQ("PATCH", res->body);
  7099. }
  7100. TEST_F(ServerTest, Delete) {
  7101. auto res = cli_.Delete("/delete");
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. EXPECT_EQ("DELETE", res->body);
  7105. }
  7106. TEST_F(ServerTest, DeleteContentReceiver) {
  7107. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7109. EXPECT_EQ(StatusCode::OK_200, res->status);
  7110. EXPECT_EQ("content", res->body);
  7111. }
  7112. TEST_F(ServerTest, Options) {
  7113. auto res = cli_.Options("*");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7117. EXPECT_TRUE(res->body.empty());
  7118. }
  7119. TEST_F(ServerTest, URL) {
  7120. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7122. EXPECT_EQ(StatusCode::OK_200, res->status);
  7123. }
  7124. TEST_F(ServerTest, ArrayParam) {
  7125. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. EXPECT_EQ(StatusCode::OK_200, res->status);
  7128. }
  7129. TEST_F(ServerTest, ArrayParamValues) {
  7130. auto res =
  7131. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ(StatusCode::OK_200, res->status);
  7134. }
  7135. TEST_F(ServerTest, NoMultipleHeaders) {
  7136. Headers headers = {{"Content-Length", "5"}};
  7137. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7138. "text/plain");
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. TEST_F(ServerTest, PostContentReceiver) {
  7143. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7145. ASSERT_EQ(StatusCode::OK_200, res->status);
  7146. ASSERT_EQ("content", res->body);
  7147. }
  7148. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7149. UploadFormDataItems items = {
  7150. {"text1", "text default", "", ""},
  7151. {"text2", "aωb", "", ""},
  7152. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7153. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7154. {"file3", "", "", "application/octet-stream"},
  7155. };
  7156. auto res = cli_.Post("/content_receiver", items);
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7161. UploadFormDataItems items = {
  7162. {"text1", "text default", "", ""},
  7163. {"text2", "aωb", "", ""},
  7164. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7165. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7166. {"file3", "", "", "application/octet-stream"},
  7167. };
  7168. auto boundary = std::string("+++++");
  7169. std::string body;
  7170. for (const auto &item : items) {
  7171. body += "--" + boundary + "\r\n";
  7172. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7173. if (!item.filename.empty()) {
  7174. body += "; filename=\"" + item.filename + "\"";
  7175. }
  7176. body += "\r\n";
  7177. if (!item.content_type.empty()) {
  7178. body += "Content-Type: " + item.content_type + "\r\n";
  7179. }
  7180. body += "\r\n";
  7181. body += item.content + "\r\n";
  7182. }
  7183. body += "--" + boundary + "--\r\n";
  7184. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7185. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7187. EXPECT_EQ(StatusCode::OK_200, res->status);
  7188. }
  7189. TEST(MultipartFormDataTest, FieldEscaping) {
  7190. Server svr;
  7191. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7192. const ContentReader &content_reader) {
  7193. ASSERT_TRUE(req.is_multipart_form_data());
  7194. std::vector<FormData> received;
  7195. content_reader(
  7196. [&](const FormData &file) {
  7197. received.push_back(file);
  7198. return true;
  7199. },
  7200. [&](const char *data, size_t data_length) {
  7201. received.back().content.append(data, data_length);
  7202. return true;
  7203. });
  7204. // '"', CR and LF in names and filenames are escaped following the
  7205. // WHATWG HTML standard, so each part still parses as a single part
  7206. // with no injected headers. Content types get CR/LF escaped too,
  7207. // while '"' (legal there, e.g. quoted charset) is preserved.
  7208. ASSERT_EQ(4U, received.size());
  7209. EXPECT_EQ("na%22me", received[0].name);
  7210. EXPECT_EQ("quoted name", received[0].content);
  7211. EXPECT_EQ("file", received[1].name);
  7212. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7213. received[1].filename);
  7214. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7215. EXPECT_EQ("injected", received[1].content);
  7216. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7217. EXPECT_EQ("my%22file.txt", received[2].filename);
  7218. EXPECT_EQ("cr lf name", received[2].content);
  7219. EXPECT_EQ("typed", received[3].name);
  7220. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7221. received[3].content_type);
  7222. EXPECT_EQ("typed content", received[3].content);
  7223. });
  7224. auto port = svr.bind_to_any_port("localhost");
  7225. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7226. auto se = detail::scope_exit([&] {
  7227. svr.stop();
  7228. t.join();
  7229. ASSERT_FALSE(svr.is_running());
  7230. });
  7231. svr.wait_until_ready();
  7232. Client cli("localhost", port);
  7233. UploadFormDataItems items = {
  7234. {"na\"me", "quoted name", "", ""},
  7235. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7236. "application/octet-stream"},
  7237. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7238. {"typed", "typed content", "",
  7239. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7240. };
  7241. auto res = cli.Post("/post", items);
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. EXPECT_EQ(StatusCode::OK_200, res->status);
  7244. }
  7245. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7246. const UploadFormDataItems items = {
  7247. {"name1", "Content 1", "", ""},
  7248. {"name2", "Content 2", "file2.txt", "text/plain"},
  7249. };
  7250. Server svr;
  7251. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7252. const ContentReader &content_reader) {
  7253. ASSERT_TRUE(req.is_multipart_form_data());
  7254. std::vector<FormData> received;
  7255. content_reader(
  7256. [&](const FormData &file) {
  7257. received.push_back(file);
  7258. return true;
  7259. },
  7260. [&](const char *data, size_t data_length) {
  7261. received.back().content.append(data, data_length);
  7262. return true;
  7263. });
  7264. ASSERT_EQ(2U, received.size());
  7265. EXPECT_EQ("name1", received[0].name);
  7266. EXPECT_EQ("Content 1", received[0].content);
  7267. EXPECT_EQ("name2", received[1].name);
  7268. EXPECT_EQ("Content 2", received[1].content);
  7269. EXPECT_EQ("file2.txt", received[1].filename);
  7270. EXPECT_EQ("text/plain", received[1].content_type);
  7271. });
  7272. auto port = svr.bind_to_any_port("localhost");
  7273. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7274. auto se = detail::scope_exit([&] {
  7275. svr.stop();
  7276. t.join();
  7277. ASSERT_FALSE(svr.is_running());
  7278. });
  7279. svr.wait_until_ready();
  7280. Client cli("localhost", port);
  7281. // Whole-body serialization with a generated boundary
  7282. {
  7283. MultipartFormDataWriter writer;
  7284. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7285. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7286. writer.content_type());
  7287. auto body = writer.serialize(items);
  7288. EXPECT_EQ(body.size(), writer.content_length(items));
  7289. auto res = cli.Post("/post", body, writer.content_type());
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. }
  7293. // Per-part framing with a custom boundary via a content provider
  7294. {
  7295. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7296. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7297. MultipartFormDataWriter writer("custom-boundary_123");
  7298. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7299. std::string body;
  7300. for (const auto &item : items) {
  7301. body += writer.item_begin(item);
  7302. body += item.content;
  7303. body += MultipartFormDataWriter::item_end();
  7304. }
  7305. body += writer.finish();
  7306. EXPECT_EQ(body.size(), writer.content_length(items));
  7307. auto res = cli.Post(
  7308. "/post", body.size(),
  7309. [&](size_t offset, size_t length, DataSink &sink) {
  7310. sink.write(body.data() + offset, length);
  7311. return true;
  7312. },
  7313. writer.content_type());
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. }
  7317. }
  7318. TEST_F(ServerTest, PostContentReceiverGzip) {
  7319. cli_.set_compress(true);
  7320. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. ASSERT_EQ(StatusCode::OK_200, res->status);
  7323. ASSERT_EQ("content", res->body);
  7324. }
  7325. TEST_F(ServerTest, PutContentReceiver) {
  7326. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. ASSERT_EQ(StatusCode::OK_200, res->status);
  7329. ASSERT_EQ("content", res->body);
  7330. }
  7331. TEST_F(ServerTest, PatchContentReceiver) {
  7332. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. ASSERT_EQ(StatusCode::OK_200, res->status);
  7335. ASSERT_EQ("content", res->body);
  7336. }
  7337. template <typename ClientType>
  7338. void TestWithHeadersAndContentReceiver(
  7339. ClientType &cli,
  7340. std::function<Result(ClientType &, const std::string &, const Headers &,
  7341. const std::string &, const std::string &,
  7342. ContentReceiver, DownloadProgress)>
  7343. request_func) {
  7344. Headers headers;
  7345. headers.emplace("X-Custom-Header", "test-value");
  7346. std::string received_body;
  7347. auto res = request_func(
  7348. cli, "/content_receiver", headers, "content", "application/json",
  7349. [&](const char *data, size_t data_length) {
  7350. received_body.append(data, data_length);
  7351. return true;
  7352. },
  7353. nullptr);
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("content", received_body);
  7357. }
  7358. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7359. #ifdef CPPHTTPLIB_SSL_ENABLED
  7360. using ClientT = SSLClient;
  7361. #else
  7362. using ClientT = Client;
  7363. #endif
  7364. TestWithHeadersAndContentReceiver<ClientT>(
  7365. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7366. const std::string &body, const std::string &content_type,
  7367. ContentReceiver receiver, DownloadProgress progress) {
  7368. return cli.Post(path, headers, body, content_type, receiver, progress);
  7369. });
  7370. }
  7371. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7372. #ifdef CPPHTTPLIB_SSL_ENABLED
  7373. using ClientT = SSLClient;
  7374. #else
  7375. using ClientT = Client;
  7376. #endif
  7377. TestWithHeadersAndContentReceiver<ClientT>(
  7378. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7379. const std::string &body, const std::string &content_type,
  7380. ContentReceiver receiver, DownloadProgress progress) {
  7381. return cli.Put(path, headers, body, content_type, receiver, progress);
  7382. });
  7383. }
  7384. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7385. #ifdef CPPHTTPLIB_SSL_ENABLED
  7386. using ClientT = SSLClient;
  7387. #else
  7388. using ClientT = Client;
  7389. #endif
  7390. TestWithHeadersAndContentReceiver<ClientT>(
  7391. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7392. const std::string &body, const std::string &content_type,
  7393. ContentReceiver receiver, DownloadProgress progress) {
  7394. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7395. });
  7396. }
  7397. template <typename ClientType>
  7398. void TestWithHeadersAndContentReceiverWithProgress(
  7399. ClientType &cli,
  7400. std::function<Result(ClientType &, const std::string &, const Headers &,
  7401. const std::string &, const std::string &,
  7402. ContentReceiver, DownloadProgress)>
  7403. request_func) {
  7404. Headers headers;
  7405. headers.emplace("X-Test-Header", "progress-test");
  7406. std::string received_body;
  7407. auto progress_called = false;
  7408. auto res = request_func(
  7409. cli, "/content_receiver", headers, "content", "text/plain",
  7410. [&](const char *data, size_t data_length) {
  7411. received_body.append(data, data_length);
  7412. return true;
  7413. },
  7414. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7415. progress_called = true;
  7416. return true;
  7417. });
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ(StatusCode::OK_200, res->status);
  7420. EXPECT_EQ("content", received_body);
  7421. EXPECT_TRUE(progress_called);
  7422. }
  7423. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7424. #ifdef CPPHTTPLIB_SSL_ENABLED
  7425. using ClientT = SSLClient;
  7426. #else
  7427. using ClientT = Client;
  7428. #endif
  7429. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7430. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7431. const std::string &body, const std::string &content_type,
  7432. ContentReceiver receiver, DownloadProgress progress) {
  7433. return cli.Post(path, headers, body, content_type, receiver, progress);
  7434. });
  7435. }
  7436. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7437. #ifdef CPPHTTPLIB_SSL_ENABLED
  7438. using ClientT = SSLClient;
  7439. #else
  7440. using ClientT = Client;
  7441. #endif
  7442. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7443. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7444. const std::string &body, const std::string &content_type,
  7445. ContentReceiver receiver, DownloadProgress progress) {
  7446. return cli.Put(path, headers, body, content_type, receiver, progress);
  7447. });
  7448. }
  7449. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7450. #ifdef CPPHTTPLIB_SSL_ENABLED
  7451. using ClientT = SSLClient;
  7452. #else
  7453. using ClientT = Client;
  7454. #endif
  7455. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7456. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7457. const std::string &body, const std::string &content_type,
  7458. ContentReceiver receiver, DownloadProgress progress) {
  7459. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7460. });
  7461. }
  7462. template <typename ClientType>
  7463. void TestWithHeadersAndContentReceiverError(
  7464. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7465. const Headers &, const std::string &,
  7466. const std::string &, ContentReceiver)>
  7467. request_func) {
  7468. Headers headers;
  7469. headers.emplace("X-Error-Test", "true");
  7470. std::string received_body;
  7471. auto receiver_failed = false;
  7472. auto res =
  7473. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7474. [&](const char *data, size_t data_length) {
  7475. received_body.append(data, data_length);
  7476. receiver_failed = true;
  7477. return false;
  7478. });
  7479. ASSERT_FALSE(res);
  7480. EXPECT_TRUE(receiver_failed);
  7481. }
  7482. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7483. #ifdef CPPHTTPLIB_SSL_ENABLED
  7484. using ClientT = SSLClient;
  7485. #else
  7486. using ClientT = Client;
  7487. #endif
  7488. TestWithHeadersAndContentReceiverError<ClientT>(
  7489. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7490. const std::string &body, const std::string &content_type,
  7491. ContentReceiver receiver) {
  7492. return cli.Post(path, headers, body, content_type, receiver);
  7493. });
  7494. }
  7495. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7496. #ifdef CPPHTTPLIB_SSL_ENABLED
  7497. using ClientT = SSLClient;
  7498. #else
  7499. using ClientT = Client;
  7500. #endif
  7501. TestWithHeadersAndContentReceiverError<ClientT>(
  7502. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7503. const std::string &body, const std::string &content_type,
  7504. ContentReceiver receiver) {
  7505. return cli.Put(path, headers, body, content_type, receiver);
  7506. });
  7507. }
  7508. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7509. #ifdef CPPHTTPLIB_SSL_ENABLED
  7510. using ClientT = SSLClient;
  7511. #else
  7512. using ClientT = Client;
  7513. #endif
  7514. TestWithHeadersAndContentReceiverError<ClientT>(
  7515. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7516. const std::string &body, const std::string &content_type,
  7517. ContentReceiver receiver) {
  7518. return cli.Patch(path, headers, body, content_type, receiver);
  7519. });
  7520. }
  7521. TEST_F(ServerTest, PostQueryStringAndBody) {
  7522. auto res =
  7523. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. ASSERT_EQ(StatusCode::OK_200, res->status);
  7526. }
  7527. TEST_F(ServerTest, HTTP2Magic) {
  7528. Request req;
  7529. req.method = "PRI";
  7530. req.path = "*";
  7531. req.body = "SM";
  7532. auto res = std::make_shared<Response>();
  7533. auto error = Error::Success;
  7534. auto ret = cli_.send(req, *res, error);
  7535. ASSERT_TRUE(ret);
  7536. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7537. }
  7538. TEST_F(ServerTest, KeepAlive) {
  7539. auto res = cli_.Get("/hi");
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7543. EXPECT_EQ("Hello World!", res->body);
  7544. res = cli_.Get("/hi");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7548. EXPECT_EQ("Hello World!", res->body);
  7549. res = cli_.Get("/hi");
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::OK_200, res->status);
  7552. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7553. EXPECT_EQ("Hello World!", res->body);
  7554. res = cli_.Get("/not-exist");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7557. res = cli_.Post("/empty", "", "text/plain");
  7558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7561. EXPECT_EQ("empty", res->body);
  7562. EXPECT_EQ("close", res->get_header_value("Connection"));
  7563. res = cli_.Post(
  7564. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7565. "text/plain");
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::OK_200, res->status);
  7568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7569. EXPECT_EQ("empty", res->body);
  7570. cli_.set_keep_alive(false);
  7571. res = cli_.Get("/last-request");
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. EXPECT_EQ("close", res->get_header_value("Connection"));
  7575. }
  7576. TEST_F(ServerTest, TooManyRedirect) {
  7577. cli_.set_follow_location(true);
  7578. auto res = cli_.Get("/redirect/0");
  7579. ASSERT_TRUE(!res);
  7580. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7581. }
  7582. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7583. Request req;
  7584. req.method = "FOOBAR";
  7585. req.path = "/hi";
  7586. cli_.set_keep_alive(true);
  7587. auto res = cli_.send(req);
  7588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7589. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7590. EXPECT_EQ("close", res->get_header_value("Connection"));
  7591. EXPECT_FALSE(cli_.is_socket_open());
  7592. }
  7593. TEST_F(ServerTest, CustomRouteReadsBody) {
  7594. const std::string xml =
  7595. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7596. Request req;
  7597. req.method = "PROPFIND";
  7598. req.path = "/dav/dir";
  7599. req.set_header("Depth", "1");
  7600. req.body = xml;
  7601. auto res = cli_.send(req);
  7602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7603. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7604. EXPECT_EQ(xml, res->body);
  7605. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7606. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7607. }
  7608. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7609. Request req;
  7610. req.method = "PROPFIND";
  7611. req.path = "/dav/42";
  7612. auto res = cli_.send(req);
  7613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7614. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7615. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7616. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7617. }
  7618. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7619. Request req;
  7620. req.method = "PROPFIND";
  7621. req.path = "/dav-re/123";
  7622. auto res = cli_.send(req);
  7623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7624. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7625. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7626. }
  7627. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7628. Request req;
  7629. req.method = "MKCOL";
  7630. req.path = "/dav-mkcol";
  7631. auto res = cli_.send(req);
  7632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7633. EXPECT_EQ(StatusCode::Created_201, res->status);
  7634. }
  7635. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7636. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7637. Request req;
  7638. req.method = "REPORT";
  7639. req.path = "/dav-report";
  7640. req.body = xml;
  7641. auto res = cli_.send(req);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7644. EXPECT_EQ(xml, res->body);
  7645. }
  7646. // A content reader route must fire even when the request carries no body,
  7647. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7648. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7649. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7650. Request req;
  7651. req.method = "REPORT";
  7652. req.path = "/dav-report";
  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("0", res->get_header_value("x-body-size"));
  7657. }
  7658. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7659. Request req;
  7660. req.method = "PROPFIND";
  7661. req.path = "/not-dav";
  7662. auto res = cli_.send(req);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7665. }
  7666. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7667. Request req;
  7668. req.method = "UNLOCK";
  7669. req.path = "/dav/dir";
  7670. cli_.set_keep_alive(true);
  7671. auto res = cli_.send(req);
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7674. EXPECT_EQ("close", res->get_header_value("Connection"));
  7675. EXPECT_FALSE(cli_.is_socket_open());
  7676. }
  7677. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7678. // The mount point serves this path, but only for GET and HEAD.
  7679. auto get_res = cli_.Get("/dir/index.html");
  7680. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7681. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7682. Request req;
  7683. req.method = "PROPFIND";
  7684. req.path = "/dir/index.html";
  7685. auto res = cli_.send(req);
  7686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7688. }
  7689. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7690. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7691. cli_.set_keep_alive(true);
  7692. for (auto i = 0; i < 2; i++) {
  7693. Request req;
  7694. req.method = "PROPFIND";
  7695. req.path = "/dav/dir";
  7696. req.body = xml;
  7697. auto res = cli_.send(req);
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7700. EXPECT_EQ(xml, res->body);
  7701. EXPECT_TRUE(cli_.is_socket_open());
  7702. }
  7703. // A built-in method must still be served on the same connection.
  7704. cli_.set_keep_alive(false);
  7705. auto res = cli_.Get("/hi");
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::OK_200, res->status);
  7708. EXPECT_EQ("close", res->get_header_value("Connection"));
  7709. }
  7710. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7711. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7712. Request req;
  7713. req.method = "PROPFIND";
  7714. req.path = "/dav/dir";
  7715. req.set_header("Expect", "100-continue");
  7716. req.body = xml;
  7717. auto res = cli_.send(req);
  7718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7719. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7720. EXPECT_EQ(xml, res->body);
  7721. }
  7722. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7723. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7724. TEST_F(ServerTest, Gzip) {
  7725. Headers headers;
  7726. headers.emplace("Accept-Encoding", "gzip, deflate");
  7727. auto res = cli_.Get("/compress", headers);
  7728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7729. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7731. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7732. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7733. "7890123456789012345678901234567890",
  7734. res->body);
  7735. EXPECT_EQ(StatusCode::OK_200, res->status);
  7736. }
  7737. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7738. Headers headers;
  7739. headers.emplace("Accept-Encoding", "gzip, deflate");
  7740. auto res = cli_.Get("/compress-with-charset", headers);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7743. EXPECT_EQ("application/json; charset=utf-8",
  7744. res->get_header_value("Content-Type"));
  7745. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7746. "7890123456789012345678901234567890",
  7747. res->body);
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7751. Headers headers;
  7752. headers.emplace("Accept-Encoding", "");
  7753. auto res = cli_.Get("/compress", headers);
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7756. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7757. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7758. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7759. "7890123456789012345678901234567890",
  7760. res->body);
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. }
  7763. TEST_F(ServerTest, GzipWithContentReceiver) {
  7764. Headers headers;
  7765. headers.emplace("Accept-Encoding", "gzip, deflate");
  7766. std::string body;
  7767. auto res = cli_.Get("/compress", headers,
  7768. [&](const char *data, uint64_t data_length) {
  7769. EXPECT_EQ(100U, data_length);
  7770. body.append(data, data_length);
  7771. return true;
  7772. });
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7775. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7776. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7777. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7778. "7890123456789012345678901234567890",
  7779. body);
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. }
  7782. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7783. Headers headers;
  7784. headers.emplace("Accept-Encoding", "gzip, deflate");
  7785. cli_.set_decompress(false);
  7786. auto res = cli_.Get("/compress", headers);
  7787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7788. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7789. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7790. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7791. EXPECT_EQ(33U, res->body.size());
  7792. EXPECT_EQ(StatusCode::OK_200, res->status);
  7793. }
  7794. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7795. Headers headers;
  7796. headers.emplace("Accept-Encoding", "");
  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_TRUE(res->get_header_value("Content-Encoding").empty());
  7806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7807. EXPECT_EQ("100", 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, NoGzip) {
  7814. Headers headers;
  7815. headers.emplace("Accept-Encoding", "gzip, deflate");
  7816. auto res = cli_.Get("/nocompress", headers);
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7819. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7820. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7821. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7822. "7890123456789012345678901234567890",
  7823. res->body);
  7824. EXPECT_EQ(StatusCode::OK_200, res->status);
  7825. }
  7826. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7827. Headers headers;
  7828. headers.emplace("Accept-Encoding", "gzip, deflate");
  7829. std::string body;
  7830. auto res = cli_.Get("/nocompress", headers,
  7831. [&](const char *data, uint64_t data_length) {
  7832. EXPECT_EQ(100U, data_length);
  7833. body.append(data, data_length);
  7834. return true;
  7835. });
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7838. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7839. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7840. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7841. "7890123456789012345678901234567890",
  7842. body);
  7843. EXPECT_EQ(StatusCode::OK_200, res->status);
  7844. }
  7845. TEST_F(ServerTest, MultipartFormDataGzip) {
  7846. UploadFormDataItems items = {
  7847. {"key1", "test", "", ""},
  7848. {"key2", "--abcdefg123", "", ""},
  7849. };
  7850. cli_.set_compress(true);
  7851. auto res = cli_.Post("/compress-multipart", items);
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. }
  7855. #endif
  7856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7857. // Static file compression is opt-in, so these run their own server rather than
  7858. // flipping it on for the shared ServerTest fixture, which would silently
  7859. // rewrite what every other static file test is asserting.
  7860. class StaticFileCompressionTest : public ::testing::Test {
  7861. protected:
  7862. void TearDown() override {
  7863. if (t_.joinable()) {
  7864. svr_.stop();
  7865. t_.join();
  7866. }
  7867. }
  7868. int start(const std::function<void(Server &)> &configure = nullptr) {
  7869. // Serves the same tree as a directory of build-time compressed assets
  7870. // would be served: the mount point names the coding the files are already
  7871. // stored in. Registered before "/" so it is the one that matches.
  7872. svr_.set_mount_point("/pre-encoded", "./www",
  7873. {{"Content-Encoding", "gzip"}});
  7874. svr_.set_mount_point("/", "./www");
  7875. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7876. res.set_file_content("./www/dir/index.html", "text/html");
  7877. });
  7878. svr_.Get("/pre-encoded-file-content",
  7879. [](const Request & /*req*/, Response &res) {
  7880. res.set_header("Content-Encoding", "gzip");
  7881. res.set_file_content("./www/dir/index.html", "text/html");
  7882. });
  7883. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7884. res.set_content_provider(
  7885. 6, "text/plain",
  7886. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7887. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7888. return true;
  7889. });
  7890. });
  7891. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7892. res.set_content_provider(
  7893. 1000, "text/plain",
  7894. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7895. if (offset < 100) {
  7896. std::string data(100, 'A');
  7897. sink.write(data.data(), data.size());
  7898. return true;
  7899. }
  7900. std::this_thread::sleep_for(std::chrono::seconds(2));
  7901. std::string data(900, 'B');
  7902. sink.write(data.data(), data.size());
  7903. return true;
  7904. });
  7905. });
  7906. if (configure) { configure(svr_); }
  7907. auto port = svr_.bind_to_any_port(HOST);
  7908. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7909. svr_.wait_until_ready();
  7910. return port;
  7911. }
  7912. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7913. // Every file under ./www except 1MB.txt is smaller than the default
  7914. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7915. // it out of the way.
  7916. static void enable_without_floor(Server &svr) {
  7917. svr.set_static_file_compression(true);
  7918. svr.set_static_file_compression_min_length(0);
  7919. }
  7920. Server svr_;
  7921. std::thread t_;
  7922. };
  7923. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7924. auto port = start();
  7925. Client cli(HOST, port);
  7926. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7930. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7931. EXPECT_EQ(1048576U, res->body.size());
  7932. }
  7933. TEST_F(StaticFileCompressionTest, MountPoint) {
  7934. auto port = start(enable);
  7935. Client cli(HOST, port);
  7936. cli.set_decompress(false);
  7937. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7943. // The response stays self-delimiting: a length, not a chunked body.
  7944. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7945. EXPECT_EQ(std::to_string(res->body.size()),
  7946. res->get_header_value("Content-Length"));
  7947. EXPECT_LT(res->body.size(), 1048576U);
  7948. EXPECT_FALSE(res->body.empty());
  7949. }
  7950. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7951. auto port = start(enable);
  7952. Client cli(HOST, port);
  7953. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7957. EXPECT_EQ(1048576U, res->body.size());
  7958. }
  7959. TEST_F(StaticFileCompressionTest, FileContent) {
  7960. auto port = start(enable_without_floor);
  7961. Client cli(HOST, port);
  7962. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7966. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7967. EXPECT_EQ(104U, res->body.size());
  7968. }
  7969. // A handler that serves an already-encoded file names the coding itself. The
  7970. // file-backed path decided its coding from Accept-Encoding and the content
  7971. // type alone, so it compressed the stored bytes a second time and appended a
  7972. // second Content-Encoding field line.
  7973. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7974. auto port = start(enable_without_floor);
  7975. Client cli(HOST, port);
  7976. cli.set_decompress(false);
  7977. auto res = cli.Get("/pre-encoded-file-content",
  7978. Headers{{"Accept-Encoding", "gzip"}});
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ(StatusCode::OK_200, res->status);
  7981. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7983. // Vary belongs to a coding the server chose, and it chose none here.
  7984. EXPECT_FALSE(res->has_header("Vary"));
  7985. // The file travels exactly as it is stored on disk.
  7986. EXPECT_EQ(104U, res->body.size());
  7987. }
  7988. // The 1MB file clears the default floor, so this one runs the configuration a
  7989. // deployment would actually have.
  7990. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7991. auto port = start(enable);
  7992. Client cli(HOST, port);
  7993. cli.set_decompress(false);
  7994. auto res =
  7995. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7999. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8000. EXPECT_FALSE(res->has_header("Vary"));
  8001. EXPECT_EQ(1048576U, res->body.size());
  8002. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8003. }
  8004. TEST_F(StaticFileCompressionTest, Head) {
  8005. auto port = start(enable);
  8006. Client cli(HOST, port);
  8007. cli.set_decompress(false);
  8008. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8009. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8010. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. EXPECT_EQ(StatusCode::OK_200, res->status);
  8013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8014. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8015. // HEAD still reports the size a GET would return.
  8016. EXPECT_EQ(get->get_header_value("Content-Length"),
  8017. res->get_header_value("Content-Length"));
  8018. EXPECT_TRUE(res->body.empty());
  8019. }
  8020. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8021. auto port = start(enable);
  8022. Client cli(HOST, port);
  8023. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8024. {"Accept-Encoding", "gzip"}});
  8025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8027. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8028. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8029. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8030. EXPECT_EQ("cd", res->body);
  8031. }
  8032. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8033. auto port = start(enable);
  8034. Client cli(HOST, port);
  8035. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8039. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8040. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8041. }
  8042. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8043. auto port = start(enable);
  8044. Client cli(HOST, port);
  8045. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(StatusCode::OK_200, res->status);
  8048. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8049. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8050. EXPECT_TRUE(res->body.empty());
  8051. }
  8052. TEST_F(StaticFileCompressionTest, MinLength) {
  8053. auto port = start(enable);
  8054. Client cli(HOST, port);
  8055. // 104 bytes, well under the default floor. Compressing it would add the
  8056. // gzip header and trailer to a body that already fits in one packet.
  8057. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8061. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8062. }
  8063. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8064. auto port = start([](Server &svr) {
  8065. svr.set_static_file_compression(true);
  8066. svr.set_static_file_compression_min_length(1);
  8067. });
  8068. Client cli(HOST, port);
  8069. cli.set_decompress(false);
  8070. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8072. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8073. // A 9-byte file comes back larger than it went in, because gzip's header and
  8074. // trailer outweigh anything deflate can save. That is the end of the range
  8075. // the floor exists to keep out.
  8076. EXPECT_GT(res->body.size(), 9U);
  8077. }
  8078. TEST_F(StaticFileCompressionTest, MaxLength) {
  8079. auto port = start([](Server &svr) {
  8080. svr.set_static_file_compression(true);
  8081. svr.set_static_file_compression_min_length(0);
  8082. svr.set_static_file_compression_max_length(1024);
  8083. });
  8084. Client cli(HOST, port);
  8085. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8086. // defines `small` as a macro on Windows.
  8087. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8088. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8089. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8090. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8091. // Under it: compressed.
  8092. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8093. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8094. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8095. }
  8096. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8097. auto port = start(enable_without_floor);
  8098. Client cli(HOST, port);
  8099. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8100. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8101. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8102. auto identity_etag = identity->get_header_value("ETag");
  8103. ASSERT_FALSE(identity_etag.empty());
  8104. auto gzipped =
  8105. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8106. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8107. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8108. auto gzip_etag = gzipped->get_header_value("ETag");
  8109. ASSERT_FALSE(gzip_etag.empty());
  8110. // Two representations, two validators.
  8111. EXPECT_NE(identity_etag, gzip_etag);
  8112. // Each one revalidates against the request that would produce it...
  8113. auto fresh =
  8114. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8115. {"If-None-Match", gzip_etag}});
  8116. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8117. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8118. auto fresh_identity =
  8119. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8120. {"If-None-Match", identity_etag}});
  8121. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8122. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8123. // ...and not against the other representation.
  8124. auto crossed =
  8125. cli.Get("/dir/index.html",
  8126. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8127. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8128. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8129. }
  8130. // The opt-in covers responses the server reads off disk itself. A caller's own
  8131. // known-length provider keeps its Content-Length and, more importantly, keeps
  8132. // delivering incrementally: routing it through a compressor would hold every
  8133. // write back until zlib's window filled.
  8134. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8135. auto port = start(enable);
  8136. Client cli(HOST, port);
  8137. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8139. EXPECT_EQ(StatusCode::OK_200, res->status);
  8140. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8141. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8142. EXPECT_EQ("aaabbb", res->body);
  8143. }
  8144. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8145. auto port = start(enable);
  8146. Client cli(HOST, port);
  8147. cli.set_read_timeout(1, 0);
  8148. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8149. Headers{{"Accept-Encoding", "gzip"}});
  8150. ASSERT_TRUE(handle.is_valid());
  8151. // The provider writes 100 bytes and then stalls for longer than the read
  8152. // timeout. Those first bytes have to arrive anyway: run the response through
  8153. // a compressor and zlib holds them until its window fills, so the read would
  8154. // come back empty instead.
  8155. char buf[256];
  8156. auto n = handle.read(buf, sizeof(buf));
  8157. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8158. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8159. }
  8160. #endif
  8161. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8162. TEST_F(ServerTest, Brotli) {
  8163. Headers headers;
  8164. headers.emplace("Accept-Encoding", "br");
  8165. auto res = cli_.Get("/compress", headers);
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8169. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8170. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8171. "7890123456789012345678901234567890",
  8172. res->body);
  8173. EXPECT_EQ(StatusCode::OK_200, res->status);
  8174. }
  8175. #endif
  8176. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8177. TEST_F(ServerTest, Zstd) {
  8178. Headers headers;
  8179. headers.emplace("Accept-Encoding", "zstd");
  8180. auto res = cli_.Get("/compress", headers);
  8181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8182. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8184. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8185. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8186. "7890123456789012345678901234567890",
  8187. res->body);
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. }
  8190. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8191. Headers headers;
  8192. headers.emplace("Accept-Encoding", "");
  8193. auto res = cli_.Get("/compress", headers);
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8197. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8198. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8199. "7890123456789012345678901234567890",
  8200. res->body);
  8201. EXPECT_EQ(StatusCode::OK_200, res->status);
  8202. }
  8203. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8204. Headers headers;
  8205. headers.emplace("Accept-Encoding", "zstd");
  8206. std::string body;
  8207. auto res = cli_.Get("/compress", headers,
  8208. [&](const char *data, uint64_t data_length) {
  8209. EXPECT_EQ(100U, data_length);
  8210. body.append(data, data_length);
  8211. return true;
  8212. });
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8216. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8217. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8218. "7890123456789012345678901234567890",
  8219. body);
  8220. EXPECT_EQ(StatusCode::OK_200, res->status);
  8221. }
  8222. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8223. Headers headers;
  8224. headers.emplace("Accept-Encoding", "zstd");
  8225. cli_.set_decompress(false);
  8226. auto res = cli_.Get("/compress", headers);
  8227. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8228. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8229. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8230. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8234. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8235. EXPECT_EQ(StatusCode::OK_200, res->status);
  8236. ASSERT_EQ(26U, res->body.size());
  8237. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8238. 0);
  8239. }
  8240. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8241. Headers headers;
  8242. headers.emplace("Accept-Encoding", "");
  8243. std::string body;
  8244. auto res = cli_.Get("/compress", headers,
  8245. [&](const char *data, uint64_t data_length) {
  8246. EXPECT_EQ(100U, data_length);
  8247. body.append(data, data_length);
  8248. return true;
  8249. });
  8250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8251. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8252. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8253. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8254. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8255. "7890123456789012345678901234567890",
  8256. body);
  8257. EXPECT_EQ(StatusCode::OK_200, res->status);
  8258. }
  8259. TEST_F(ServerTest, NoZstd) {
  8260. Headers headers;
  8261. headers.emplace("Accept-Encoding", "zstd");
  8262. auto res = cli_.Get("/nocompress", headers);
  8263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8264. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8265. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8266. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8267. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8268. "7890123456789012345678901234567890",
  8269. res->body);
  8270. EXPECT_EQ(StatusCode::OK_200, res->status);
  8271. }
  8272. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8273. Headers headers;
  8274. headers.emplace("Accept-Encoding", "zstd");
  8275. std::string body;
  8276. auto res = cli_.Get("/nocompress", headers,
  8277. [&](const char *data, uint64_t data_length) {
  8278. EXPECT_EQ(100U, data_length);
  8279. body.append(data, data_length);
  8280. return true;
  8281. });
  8282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8283. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8284. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8285. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8286. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8287. "7890123456789012345678901234567890",
  8288. body);
  8289. EXPECT_EQ(StatusCode::OK_200, res->status);
  8290. }
  8291. // TODO: How to enable zstd ??
  8292. TEST_F(ServerTest, MultipartFormDataZstd) {
  8293. UploadFormDataItems items = {
  8294. {"key1", "test", "", ""},
  8295. {"key2", "--abcdefg123", "", ""},
  8296. };
  8297. Headers headers;
  8298. headers.emplace("Accept-Encoding", "zstd");
  8299. cli_.set_compress(true);
  8300. auto res = cli_.Post("/compress-multipart", headers, items);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. }
  8304. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8305. Headers headers;
  8306. headers.emplace("Accept-Encoding", "zstd");
  8307. cli_.set_compress(true);
  8308. auto res = cli_.Put(
  8309. "/put", headers, 3,
  8310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8311. sink.os << "PUT";
  8312. return true;
  8313. },
  8314. "text/plain");
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::OK_200, res->status);
  8317. EXPECT_EQ("PUT", res->body);
  8318. }
  8319. // Pre-compression logging tests
  8320. TEST_F(ServerTest, PreCompressionLogging) {
  8321. // Test data for compression (matches the actual /compress endpoint content)
  8322. const std::string test_content =
  8323. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8324. "3456789012345678901234567890";
  8325. // Variables to capture logging data
  8326. std::string pre_compression_body;
  8327. std::string pre_compression_content_type;
  8328. std::string pre_compression_content_encoding;
  8329. std::string post_compression_body;
  8330. std::string post_compression_content_type;
  8331. std::string post_compression_content_encoding;
  8332. // Set up pre-compression logger
  8333. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8334. const Response &res) {
  8335. pre_compression_body = res.body;
  8336. pre_compression_content_type = res.get_header_value("Content-Type");
  8337. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8338. });
  8339. // Set up post-compression logger
  8340. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8341. post_compression_body = res.body;
  8342. post_compression_content_type = res.get_header_value("Content-Type");
  8343. post_compression_content_encoding =
  8344. res.get_header_value("Content-Encoding");
  8345. });
  8346. // Test with gzip compression
  8347. Headers headers;
  8348. headers.emplace("Accept-Encoding", "gzip");
  8349. auto res = cli_.Get("/compress", headers);
  8350. // Verify response was compressed
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8354. // Verify pre-compression logger captured uncompressed content
  8355. EXPECT_EQ(test_content, pre_compression_body);
  8356. EXPECT_EQ("text/plain", pre_compression_content_type);
  8357. EXPECT_TRUE(pre_compression_content_encoding
  8358. .empty()); // No encoding header before compression
  8359. // Verify post-compression logger captured compressed content
  8360. EXPECT_NE(test_content,
  8361. post_compression_body); // Should be different after compression
  8362. EXPECT_EQ("text/plain", post_compression_content_type);
  8363. EXPECT_EQ("gzip", post_compression_content_encoding);
  8364. // Verify compressed content is smaller
  8365. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8366. }
  8367. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8368. const std::string test_content =
  8369. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8370. "3456789012345678901234567890";
  8371. std::string pre_compression_body;
  8372. std::string post_compression_body;
  8373. svr_.set_pre_compression_logger(
  8374. [&](const Request & /*req*/, const Response &res) {
  8375. pre_compression_body = res.body;
  8376. });
  8377. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8378. post_compression_body = res.body;
  8379. });
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "br");
  8382. auto res = cli_.Get("/compress", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::OK_200, res->status);
  8385. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8386. // Verify pre-compression content is uncompressed
  8387. EXPECT_EQ(test_content, pre_compression_body);
  8388. // Verify post-compression content is compressed
  8389. EXPECT_NE(test_content, post_compression_body);
  8390. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8391. }
  8392. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8393. const std::string test_content =
  8394. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8395. "3456789012345678901234567890";
  8396. std::string pre_compression_body;
  8397. std::string post_compression_body;
  8398. svr_.set_pre_compression_logger(
  8399. [&](const Request & /*req*/, const Response &res) {
  8400. pre_compression_body = res.body;
  8401. });
  8402. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8403. post_compression_body = res.body;
  8404. });
  8405. // Request without compression (use /nocompress endpoint)
  8406. Headers headers;
  8407. auto res = cli_.Get("/nocompress", headers);
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8411. // Pre-compression logger should not be called when no compression is applied
  8412. EXPECT_TRUE(
  8413. pre_compression_body.empty()); // Pre-compression logger not called
  8414. EXPECT_EQ(
  8415. test_content,
  8416. post_compression_body); // Post-compression logger captures final content
  8417. }
  8418. TEST_F(ServerTest, LoggerSeesContentLength) {
  8419. size_t logged_content_length = 0;
  8420. std::string logged_content_length_header;
  8421. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8422. logged_content_length = res.content_length_;
  8423. logged_content_length_header = res.get_header_value("Content-Length");
  8424. });
  8425. auto res = cli_.Get("/nocompress");
  8426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8427. EXPECT_EQ(StatusCode::OK_200, res->status);
  8428. EXPECT_EQ(res->body.size(), logged_content_length);
  8429. EXPECT_EQ(std::to_string(logged_content_length),
  8430. logged_content_length_header);
  8431. }
  8432. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8433. const std::string test_content =
  8434. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8435. "3456789012345678901234567890";
  8436. std::string pre_compression_body;
  8437. bool pre_logger_called = false;
  8438. // Set only pre-compression logger
  8439. svr_.set_pre_compression_logger(
  8440. [&](const Request & /*req*/, const Response &res) {
  8441. pre_compression_body = res.body;
  8442. pre_logger_called = true;
  8443. });
  8444. Headers headers;
  8445. headers.emplace("Accept-Encoding", "gzip");
  8446. auto res = cli_.Get("/compress", headers);
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8450. // Verify pre-compression logger was called
  8451. EXPECT_TRUE(pre_logger_called);
  8452. EXPECT_EQ(test_content, pre_compression_body);
  8453. }
  8454. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8455. {
  8456. // Test with Expect: 100-continue header - success case
  8457. // Server returns 100 Continue, client sends body, server returns 200 OK
  8458. Request req;
  8459. req.method = "POST";
  8460. req.path = "/post-large";
  8461. req.set_header("Expect", "100-continue");
  8462. req.body = LARGE_DATA;
  8463. Response res;
  8464. auto error = Error::Success;
  8465. cli_.set_keep_alive(true);
  8466. auto ret = cli_.send(req, res, error);
  8467. EXPECT_TRUE(ret);
  8468. EXPECT_EQ(StatusCode::OK_200, res.status);
  8469. EXPECT_EQ(LARGE_DATA, res.body);
  8470. }
  8471. {
  8472. // Test with Expect: 100-continue header - error case
  8473. // Client should not send the body when server returns an error
  8474. Request req;
  8475. req.method = "POST";
  8476. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8477. req.set_header("Expect", "100-continue");
  8478. req.body = LARGE_DATA;
  8479. Response res;
  8480. auto error = Error::Success;
  8481. auto start = std::chrono::high_resolution_clock::now();
  8482. cli_.set_keep_alive(true);
  8483. auto ret = cli_.send(req, res, error);
  8484. auto end = std::chrono::high_resolution_clock::now();
  8485. auto elapsed =
  8486. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8487. .count();
  8488. // With Expect: 100-continue, request completes successfully but with error
  8489. EXPECT_TRUE(ret);
  8490. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8491. EXPECT_EQ("close", res.get_header_value("Connection"));
  8492. EXPECT_FALSE(cli_.is_socket_open());
  8493. EXPECT_LE(elapsed, 2000);
  8494. }
  8495. {
  8496. // Send an extra GET request to ensure error recovery without hanging
  8497. Request req;
  8498. req.method = "GET";
  8499. req.path = "/hi";
  8500. auto start = std::chrono::high_resolution_clock::now();
  8501. auto res = cli_.send(req);
  8502. auto end = std::chrono::high_resolution_clock::now();
  8503. auto elapsed =
  8504. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8505. .count();
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::OK_200, res->status);
  8508. EXPECT_EQ("Hello World!", res->body);
  8509. EXPECT_LE(elapsed, 500);
  8510. }
  8511. }
  8512. TEST(ZstdDecompressor, ChunkedDecompression) {
  8513. std::string data;
  8514. for (size_t i = 0; i < 32 * 1024; ++i) {
  8515. data.push_back(static_cast<char>('a' + i % 26));
  8516. }
  8517. std::string compressed_data;
  8518. {
  8519. httplib::detail::zstd_compressor compressor;
  8520. bool result = compressor.compress(
  8521. data.data(), data.size(),
  8522. /*last=*/true,
  8523. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8524. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8525. compressed_data_size);
  8526. return true;
  8527. });
  8528. ASSERT_TRUE(result);
  8529. }
  8530. std::string decompressed_data;
  8531. {
  8532. httplib::detail::zstd_decompressor decompressor;
  8533. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8534. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8535. size_t chunk_size = 130;
  8536. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8537. chunk_begin += chunk_size) {
  8538. size_t current_chunk_size =
  8539. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8540. bool result = decompressor.decompress(
  8541. compressed_data.data() + chunk_begin, current_chunk_size,
  8542. [&](const char *decompressed_data_chunk,
  8543. size_t decompressed_data_chunk_size) {
  8544. decompressed_data.insert(decompressed_data.size(),
  8545. decompressed_data_chunk,
  8546. decompressed_data_chunk_size);
  8547. return true;
  8548. });
  8549. ASSERT_TRUE(result);
  8550. }
  8551. }
  8552. ASSERT_EQ(data, decompressed_data);
  8553. }
  8554. TEST(ZstdDecompressor, Decompress) {
  8555. std::string original_text = "Compressed with ZSTD";
  8556. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8557. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8558. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8559. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8560. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8561. std::string decompressed_data;
  8562. {
  8563. httplib::detail::zstd_decompressor decompressor;
  8564. bool result = decompressor.decompress(
  8565. compressed_data.data(), compressed_data.size(),
  8566. [&](const char *decompressed_data_chunk,
  8567. size_t decompressed_data_chunk_size) {
  8568. decompressed_data.insert(decompressed_data.size(),
  8569. decompressed_data_chunk,
  8570. decompressed_data_chunk_size);
  8571. return true;
  8572. });
  8573. ASSERT_TRUE(result);
  8574. }
  8575. ASSERT_EQ(original_text, decompressed_data);
  8576. }
  8577. #endif
  8578. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8579. // separate chunks so that the server sees each part in its own read(). Used to
  8580. // place a read boundary at a specific offset of a request body.
  8581. static bool send_request_in_parts(time_t read_timeout_sec,
  8582. const std::vector<std::string> &parts,
  8583. std::string *resp = nullptr,
  8584. int port = PORT) {
  8585. auto error = Error::Success;
  8586. auto client_sock = detail::create_client_socket(
  8587. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8588. /*connection_timeout_sec=*/5, 0,
  8589. /*read_timeout_sec=*/5, 0,
  8590. /*write_timeout_sec=*/5, 0, std::string(), error);
  8591. if (client_sock == INVALID_SOCKET) { return false; }
  8592. auto ret = detail::process_client_socket(
  8593. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8594. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8595. for (size_t i = 0; i < parts.size(); i++) {
  8596. const auto &part = parts[i];
  8597. if (part.size() !=
  8598. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8599. return false;
  8600. }
  8601. if (i + 1 < parts.size()) {
  8602. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8603. }
  8604. }
  8605. char buf[512];
  8606. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8607. while (line_reader.getline()) {
  8608. if (resp) { *resp += line_reader.ptr(); }
  8609. }
  8610. return true;
  8611. });
  8612. detail::close_socket(client_sock);
  8613. return ret;
  8614. }
  8615. // Sends a raw request to a server listening at HOST:PORT.
  8616. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8617. std::string *resp = nullptr, int port = PORT) {
  8618. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8619. }
  8620. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8621. Server svr;
  8622. std::string header_value;
  8623. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8624. header_value = req.get_header_value("foo");
  8625. res.set_content("ok", "text/plain");
  8626. });
  8627. thread t = thread([&] { svr.listen(HOST, PORT); });
  8628. auto se = detail::scope_exit([&] {
  8629. svr.stop();
  8630. t.join();
  8631. ASSERT_FALSE(svr.is_running());
  8632. });
  8633. svr.wait_until_ready();
  8634. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8635. // like characters are not treated the same - use vertical tab and escape.
  8636. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8637. "foo: \t \v bar \x1B\t \r\n"
  8638. "Connection: close\r\n"
  8639. "\r\n";
  8640. std::string res;
  8641. ASSERT_TRUE(send_request(5, req, &res));
  8642. EXPECT_EQ(header_value, "");
  8643. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8644. }
  8645. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8646. Server svr;
  8647. std::string received;
  8648. svr.Get("/order", [&](const Request &req, Response &res) {
  8649. received = entries_to_string(req.headers);
  8650. res.set_content("ok", "text/plain");
  8651. });
  8652. auto port = svr.bind_to_any_port(HOST);
  8653. thread t = thread([&] { svr.listen_after_bind(); });
  8654. auto se = detail::scope_exit([&] {
  8655. svr.stop();
  8656. t.join();
  8657. ASSERT_FALSE(svr.is_running());
  8658. });
  8659. svr.wait_until_ready();
  8660. const std::string req = "GET /order HTTP/1.1\r\n"
  8661. "X-First: 1\r\n"
  8662. "X-Dup: a\r\n"
  8663. "X-Second: 2\r\n"
  8664. "X-Dup: b\r\n"
  8665. "Connection: close\r\n"
  8666. "\r\n";
  8667. std::string res;
  8668. ASSERT_TRUE(send_request(5, req, &res, port));
  8669. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8670. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8671. }
  8672. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8673. Server svr;
  8674. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8675. res.set_header("Set-Cookie", "first=1");
  8676. res.set_header("X-Between", "y");
  8677. res.set_header("Set-Cookie", "second=2");
  8678. res.set_content("ok", "text/plain");
  8679. });
  8680. auto port = svr.bind_to_any_port(HOST);
  8681. thread t = thread([&] { svr.listen_after_bind(); });
  8682. auto se = detail::scope_exit([&] {
  8683. svr.stop();
  8684. t.join();
  8685. ASSERT_FALSE(svr.is_running());
  8686. });
  8687. svr.wait_until_ready();
  8688. Client cli(HOST, port);
  8689. auto res = cli.Get("/cookies");
  8690. ASSERT_TRUE(res);
  8691. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8692. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8693. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8694. }
  8695. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8696. Server svr;
  8697. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8698. auto i = new int(0);
  8699. res.set_header("Trailer", "X-Safe, X-Reflected");
  8700. res.set_chunked_content_provider(
  8701. "text/plain",
  8702. [i](size_t /*offset*/, DataSink &sink) {
  8703. if (*i == 0) {
  8704. sink.os << "body";
  8705. } else {
  8706. Headers trailer;
  8707. // A valid trailer that must survive.
  8708. trailer.emplace("X-Safe", "safe");
  8709. // Attacker-controlled value carrying CR/LF (response splitting).
  8710. trailer.emplace("X-Reflected",
  8711. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8712. // Attacker-controlled name carrying CR/LF.
  8713. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8714. sink.done_with_trailer(trailer);
  8715. }
  8716. (*i)++;
  8717. return true;
  8718. },
  8719. [i](bool /*success*/) { delete i; });
  8720. });
  8721. thread t = thread([&] { svr.listen(HOST, PORT); });
  8722. auto se = detail::scope_exit([&] {
  8723. svr.stop();
  8724. t.join();
  8725. ASSERT_FALSE(svr.is_running());
  8726. });
  8727. svr.wait_until_ready();
  8728. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8729. "Host: " + HOST +
  8730. "\r\n"
  8731. "Connection: close\r\n"
  8732. "\r\n";
  8733. std::string res;
  8734. ASSERT_TRUE(send_request(5, req, &res));
  8735. // The injected fields must not appear anywhere in the raw response.
  8736. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8737. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8738. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8739. // Invalid trailers are dropped entirely, matching set_header().
  8740. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8741. // The valid trailer still passes through.
  8742. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8743. }
  8744. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8745. Server svr;
  8746. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8747. // res.headers is a public field an application can populate directly,
  8748. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8749. // A valid header that must survive.
  8750. res.headers.emplace("X-Safe", "safe");
  8751. // Attacker-controlled value carrying CR/LF (response splitting).
  8752. res.headers.emplace("X-Reflected",
  8753. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8754. // Attacker-controlled name carrying CR/LF.
  8755. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8756. res.set_content("body", "text/plain");
  8757. });
  8758. thread t = thread([&] { svr.listen(HOST, PORT); });
  8759. auto se = detail::scope_exit([&] {
  8760. svr.stop();
  8761. t.join();
  8762. ASSERT_FALSE(svr.is_running());
  8763. });
  8764. svr.wait_until_ready();
  8765. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8766. "Host: " + HOST +
  8767. "\r\n"
  8768. "Connection: close\r\n"
  8769. "\r\n";
  8770. std::string res;
  8771. ASSERT_TRUE(send_request(5, req, &res));
  8772. // The injected fields must not appear anywhere in the raw response.
  8773. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8774. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8775. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8776. // Invalid headers are dropped entirely, matching set_header().
  8777. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8778. // The valid header still passes through.
  8779. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8780. }
  8781. // Forward declaration: in split builds split.py strips `inline` and moves the
  8782. // definition into httplib.cc, so detail::write_request_line is not visible from
  8783. // the public httplib.h. Re-declaring it here lets the tests link against the
  8784. // symbol in both header-only and split builds.
  8785. namespace httplib {
  8786. namespace detail {
  8787. ssize_t write_request_line(Stream &strm, const std::string &method,
  8788. const std::string &path);
  8789. } // namespace detail
  8790. } // namespace httplib
  8791. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8792. // A well-formed target is written verbatim.
  8793. {
  8794. detail::BufferStream strm;
  8795. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8796. EXPECT_GT(n, 0);
  8797. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8798. }
  8799. // A target carrying CR/LF, SP or other control octets must be rejected
  8800. // before anything reaches the wire, otherwise it splits the request line and
  8801. // injects a header or a whole request.
  8802. const std::string evil_targets[] = {
  8803. "/a\r\nInjected: pwned",
  8804. "/a\rInjected",
  8805. "/a\nInjected",
  8806. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8807. "/a b",
  8808. "/a\tb",
  8809. "/a\x7f",
  8810. };
  8811. for (const auto &evil : evil_targets) {
  8812. detail::BufferStream strm;
  8813. auto n = detail::write_request_line(strm, "GET", evil);
  8814. EXPECT_LT(n, 0);
  8815. EXPECT_TRUE(strm.get_buffer().empty());
  8816. }
  8817. }
  8818. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8819. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8820. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8821. // target reaches write_request. The client must fail cleanly with
  8822. // Error::Write instead of putting a request-line-less, header-injecting
  8823. // request on the wire.
  8824. Server svr;
  8825. svr.Get("/a", [](const Request &, Response &res) {
  8826. res.set_content("ok", "text/plain");
  8827. });
  8828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8829. auto se = detail::scope_exit([&] {
  8830. svr.stop();
  8831. thread.join();
  8832. ASSERT_FALSE(svr.is_running());
  8833. });
  8834. svr.wait_until_ready();
  8835. {
  8836. Client cli(HOST, PORT);
  8837. cli.set_path_encode(false);
  8838. // The request is rejected before anything is written, so the connection
  8839. // stays silent and the subsequent response read would otherwise block for
  8840. // the full default read timeout. Shorten it -- the assertion is on the
  8841. // error, not the timeout.
  8842. cli.set_read_timeout(1, 0);
  8843. auto res = cli.Get("/a\r\nInjected: pwned");
  8844. EXPECT_FALSE(res);
  8845. EXPECT_EQ(Error::Write, res.error());
  8846. }
  8847. }
  8848. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8849. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8850. // including extension methods.
  8851. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8852. for (const auto &method : good_methods) {
  8853. detail::BufferStream strm;
  8854. auto n = detail::write_request_line(strm, method, "/");
  8855. EXPECT_GT(n, 0);
  8856. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8857. }
  8858. // A method carrying CR/LF would split the request line and smuggle a whole
  8859. // request ahead of the real one. A space or an empty method corrupts the
  8860. // request line. All must be rejected before anything reaches the wire.
  8861. const std::string evil_methods[] = {
  8862. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8863. "GET\r\nInjected: pwned",
  8864. "GET\r",
  8865. "GET\n",
  8866. "GE T",
  8867. "",
  8868. };
  8869. for (const auto &evil : evil_methods) {
  8870. detail::BufferStream strm;
  8871. auto n = detail::write_request_line(strm, evil, "/");
  8872. EXPECT_LT(n, 0);
  8873. EXPECT_TRUE(strm.get_buffer().empty());
  8874. }
  8875. }
  8876. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8877. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8878. // through Client::send must fail with Error::Write and no request, neither
  8879. // the smuggled one nor the real one, may reach the server.
  8880. Server svr;
  8881. std::atomic<int> request_count(0);
  8882. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8883. request_count++;
  8884. res.status = StatusCode::OK_200;
  8885. return Server::HandlerResponse::Handled;
  8886. });
  8887. auto port = svr.bind_to_any_port(HOST);
  8888. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. thread.join();
  8892. ASSERT_FALSE(svr.is_running());
  8893. });
  8894. svr.wait_until_ready();
  8895. {
  8896. Client cli(HOST, port);
  8897. const std::string evil_methods[] = {
  8898. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8899. "GE T",
  8900. "",
  8901. };
  8902. for (const auto &evil : evil_methods) {
  8903. Request req;
  8904. req.method = evil;
  8905. req.path = "/";
  8906. auto res = cli.send(req);
  8907. EXPECT_FALSE(res);
  8908. EXPECT_EQ(Error::Write, res.error());
  8909. }
  8910. auto handle =
  8911. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8912. EXPECT_FALSE(handle.is_valid());
  8913. EXPECT_EQ(Error::Write, handle.error);
  8914. // A valid request on the same client still goes through.
  8915. auto res = cli.Get("/");
  8916. ASSERT_TRUE(res);
  8917. EXPECT_EQ(StatusCode::OK_200, res->status);
  8918. }
  8919. EXPECT_EQ(1, request_count.load());
  8920. }
  8921. // Sends a raw request and verifies that there isn't a crash or exception.
  8922. static void test_raw_request(const std::string &req,
  8923. std::string *out = nullptr) {
  8924. Server svr;
  8925. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8926. res.set_content("ok", "text/plain");
  8927. });
  8928. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8929. res.set_content("ok", "text/plain");
  8930. });
  8931. svr.Get("/header_field_value_check",
  8932. [&](const Request & /*req*/, Response &res) {
  8933. res.set_content("ok", "text/plain");
  8934. });
  8935. svr.CustomRoute("PROPFIND", "/dav",
  8936. [&](const Request & /*req*/, Response &res) {
  8937. res.status = StatusCode::MultiStatus_207;
  8938. });
  8939. // Server read timeout must be longer than the client read timeout for the
  8940. // bug to reproduce, probably to force the server to process a request
  8941. // without a trailing blank line.
  8942. const time_t client_read_timeout_sec = 1;
  8943. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8944. bool listen_thread_ok = false;
  8945. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8946. auto se = detail::scope_exit([&] {
  8947. svr.stop();
  8948. t.join();
  8949. ASSERT_FALSE(svr.is_running());
  8950. EXPECT_TRUE(listen_thread_ok);
  8951. });
  8952. svr.wait_until_ready();
  8953. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8954. }
  8955. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8956. // A certain header line causes an exception if the header property is parsed
  8957. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8958. test_raw_request(
  8959. "GET /hi HTTP/1.1\r\n"
  8960. " : "
  8961. " "
  8962. " ");
  8963. }
  8964. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8965. // A certain header line causes an exception if the header property *name* is
  8966. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8967. // greedy matcher and requires backtracking when there are a lot of ":"
  8968. // characters.
  8969. // This occurs with libc++ but not libstdc++.
  8970. test_raw_request(
  8971. "GET /hi HTTP/1.1\r\n"
  8972. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8973. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8974. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8975. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8976. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8977. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8978. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8979. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8980. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8981. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8982. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8983. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8984. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8985. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8986. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8987. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8988. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8989. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8990. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8991. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8992. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8993. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8994. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8995. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8996. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8997. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8998. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8999. "&&&%%%");
  9000. }
  9001. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9002. // Make sure this doesn't crash the server.
  9003. // In a previous version of the header line regex, the "\r" rendered the line
  9004. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9005. // a new position where the leading white space ended and the field value
  9006. // began.
  9007. // The crash occurs with libc++ but not libstdc++.
  9008. test_raw_request("GET /hi HTTP/1.1\r\n"
  9009. "a:" +
  9010. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9011. "\r\n"
  9012. "\r\n");
  9013. }
  9014. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9015. std::string out;
  9016. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9017. "Content-Type: text/plain\r\n"
  9018. "Transfer-Encoding: chunked\r\n"
  9019. "\r\n"
  9020. "nothex\r\n",
  9021. &out);
  9022. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9023. }
  9024. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9025. std::string out;
  9026. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9027. "Content-Type: text/plain\r\n"
  9028. "Transfer-Encoding: chunked\r\n"
  9029. "\r\n"
  9030. "3\r\n"
  9031. "xyz\r\n"
  9032. "NaN\r\n",
  9033. &out);
  9034. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9035. }
  9036. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9037. std::string out;
  9038. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9039. "Content-Type: text/plain\r\n"
  9040. "Transfer-Encoding: chunked\r\n"
  9041. "\r\n"
  9042. // Length is too large for 64 bits.
  9043. "1ffffffffffffffff\r\n"
  9044. "xyz\r\n",
  9045. &out);
  9046. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9047. }
  9048. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9049. test_raw_request("GET /hi HTTP/1.1\r\n"
  9050. "Content-Type: text/plain\r\n\r");
  9051. }
  9052. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9053. std::string out;
  9054. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9056. }
  9057. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9058. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9059. std::string out;
  9060. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9061. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9062. }
  9063. }
  9064. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9065. std::string out;
  9066. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9067. "Connection: close\r\n\r\n",
  9068. &out);
  9069. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9070. }
  9071. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9072. Server svr;
  9073. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9074. EXPECT_TRUE(!req.remote_addr.empty());
  9075. });
  9076. thread t = thread([&] { svr.listen(HOST, PORT); });
  9077. auto se = detail::scope_exit([&] {
  9078. svr.stop();
  9079. t.join();
  9080. ASSERT_FALSE(svr.is_running());
  9081. });
  9082. svr.wait_until_ready();
  9083. // Send an invalid request line to trigger Bad Request
  9084. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9085. std::string out;
  9086. ASSERT_TRUE(send_request(5, bad_req, &out));
  9087. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9088. }
  9089. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9090. // answered right away rather than blocking on a read that waits for EOF.
  9091. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9092. std::string out;
  9093. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9094. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9095. }
  9096. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9097. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9098. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9099. for (const auto *method : methods) {
  9100. Server svr;
  9101. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9102. EXPECT_FALSE(svr.is_valid()) << method;
  9103. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9104. }
  9105. }
  9106. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9107. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9108. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9109. for (const auto *method : methods) {
  9110. Server svr;
  9111. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9112. EXPECT_FALSE(svr.is_valid()) << method;
  9113. }
  9114. }
  9115. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9116. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9117. "COPY", "MOVE", "LOCK",
  9118. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9119. Server svr;
  9120. for (const auto *method : methods) {
  9121. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9122. }
  9123. EXPECT_TRUE(svr.is_valid());
  9124. }
  9125. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9126. Server svr;
  9127. svr.CustomRoute("POST", "/x",
  9128. [](const Request &, Response &, const ContentReader &) {});
  9129. EXPECT_FALSE(svr.is_valid());
  9130. }
  9131. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9132. Server svr;
  9133. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9134. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9135. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9136. EXPECT_FALSE(svr.is_valid());
  9137. }
  9138. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9139. Server svr;
  9140. auto captured = Error::Success;
  9141. svr.set_error_logger(
  9142. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9143. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9144. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9145. }
  9146. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9147. std::string out;
  9148. std::string request(
  9149. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9150. test_raw_request(request, &out);
  9151. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9152. }
  9153. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9154. std::string out;
  9155. std::string request(
  9156. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9157. test_raw_request(request, &out);
  9158. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9159. }
  9160. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9161. std::string out;
  9162. std::string request(
  9163. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9164. test_raw_request(request, &out);
  9165. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9166. }
  9167. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9168. std::string out;
  9169. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9170. "Test: \r\n\r\n",
  9171. &out);
  9172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9173. }
  9174. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9175. Server svr;
  9176. std::string x_custom;
  9177. std::string cookie;
  9178. std::string xff;
  9179. std::string x_unicode;
  9180. std::string x_iis;
  9181. svr.Get("/check", [&](const Request &req, Response &res) {
  9182. x_custom = req.get_header_value("X-Custom");
  9183. cookie = req.get_header_value("Cookie");
  9184. xff = req.get_header_value("X-Forwarded-For");
  9185. x_unicode = req.get_header_value("X-Unicode");
  9186. x_iis = req.get_header_value("X-IIS");
  9187. res.set_content("ok", "text/plain");
  9188. });
  9189. thread t = thread([&] { svr.listen(HOST, PORT); });
  9190. auto se = detail::scope_exit([&] {
  9191. svr.stop();
  9192. t.join();
  9193. ASSERT_FALSE(svr.is_running());
  9194. });
  9195. svr.wait_until_ready();
  9196. const std::string req = "GET /check HTTP/1.1\r\n"
  9197. "Host: localhost\r\n"
  9198. "X-Custom: a%0D%0AInjected: b\r\n"
  9199. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9200. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9201. "X-Unicode: %E3%81%82\r\n"
  9202. "X-IIS: %u00E9\r\n"
  9203. "Connection: close\r\n"
  9204. "\r\n";
  9205. std::string res;
  9206. ASSERT_TRUE(send_request(5, req, &res));
  9207. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9208. // Every value must be returned verbatim (wire form), with no decoding.
  9209. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9210. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9211. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9212. EXPECT_EQ("%E3%81%82", x_unicode);
  9213. EXPECT_EQ("%u00E9", x_iis);
  9214. }
  9215. // Applications that previously relied on automatic percent-decoding can
  9216. // reproduce the old behavior by explicitly calling decode_path_component()
  9217. // or, for RFC 3986 conformance, decode_uri_component().
  9218. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9219. Server svr;
  9220. std::string decoded;
  9221. svr.Get("/check", [&](const Request &req, Response &res) {
  9222. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9223. res.set_content("ok", "text/plain");
  9224. });
  9225. thread t = thread([&] { svr.listen(HOST, PORT); });
  9226. auto se = detail::scope_exit([&] {
  9227. svr.stop();
  9228. t.join();
  9229. ASSERT_FALSE(svr.is_running());
  9230. });
  9231. svr.wait_until_ready();
  9232. const std::string req = "GET /check HTTP/1.1\r\n"
  9233. "Host: localhost\r\n"
  9234. "X-Custom: hello%20world\r\n"
  9235. "Connection: close\r\n"
  9236. "\r\n";
  9237. std::string res;
  9238. ASSERT_TRUE(send_request(5, req, &res));
  9239. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9240. EXPECT_EQ("hello world", decoded);
  9241. }
  9242. // Regression test for #2033. Browsers send Referer values that include
  9243. // percent-encoded characters such as %0A inside the URL. Decoding the
  9244. // header value would either trip the post-decode CR/LF/NUL guard (the
  9245. // original bug, returning 400) or, after that guard was relaxed, silently
  9246. // store a literal LF — both unacceptable. The wire form must round-trip.
  9247. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9248. Server svr;
  9249. std::string referer;
  9250. svr.Get("/check", [&](const Request &req, Response &res) {
  9251. referer = req.get_header_value("Referer");
  9252. res.set_content("ok", "text/plain");
  9253. });
  9254. thread t = thread([&] { svr.listen(HOST, PORT); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. const std::string req = "GET /check HTTP/1.1\r\n"
  9262. "Host: localhost\r\n"
  9263. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9264. "Connection: close\r\n"
  9265. "\r\n";
  9266. std::string res;
  9267. ASSERT_TRUE(send_request(5, req, &res));
  9268. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9269. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9270. }
  9271. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9272. Server svr;
  9273. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9274. res.set_header("Cache-Control", "no-cache");
  9275. res.set_chunked_content_provider(
  9276. "text/event-stream", [](size_t offset, DataSink &sink) {
  9277. std::string s = "data:";
  9278. s += std::to_string(offset);
  9279. s += "\n\n";
  9280. auto ret = sink.write(s.data(), s.size());
  9281. EXPECT_TRUE(ret);
  9282. std::this_thread::sleep_for(std::chrono::seconds(1));
  9283. return true;
  9284. });
  9285. });
  9286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9287. svr.wait_until_ready();
  9288. Client client(HOST, PORT);
  9289. const Headers headers = {{"Accept", "text/event-stream"}};
  9290. auto get_thread = std::thread([&client, &headers]() {
  9291. auto res = client.Get(
  9292. "/events", headers,
  9293. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9294. });
  9295. auto se = detail::scope_exit([&] {
  9296. svr.stop();
  9297. get_thread.join();
  9298. listen_thread.join();
  9299. ASSERT_FALSE(svr.is_running());
  9300. });
  9301. // Give GET time to get a few messages.
  9302. std::this_thread::sleep_for(std::chrono::seconds(2));
  9303. }
  9304. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9305. httplib::Server svr;
  9306. svr.Post("/hi",
  9307. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9308. res.status = StatusCode::OK_200;
  9309. });
  9310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9311. svr.wait_until_ready();
  9312. Client cli(HOST, PORT);
  9313. auto res = cli.Post("/hi", "data", "text/plain");
  9314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9315. EXPECT_EQ(StatusCode::OK_200, res->status);
  9316. svr.stop();
  9317. thread.join();
  9318. ASSERT_FALSE(svr.is_running());
  9319. res = cli.Post("/hi", "data", "text/plain");
  9320. ASSERT_FALSE(res);
  9321. }
  9322. TEST(ServerStopTest, ListenFailure) {
  9323. Server svr;
  9324. auto t = thread([&]() {
  9325. auto ret = svr.listen("????", PORT);
  9326. EXPECT_FALSE(ret);
  9327. });
  9328. svr.wait_until_ready();
  9329. svr.stop();
  9330. t.join();
  9331. }
  9332. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9333. TEST(ServerStopTest, Decommision) {
  9334. Server svr;
  9335. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9336. for (int i = 0; i < 4; i++) {
  9337. auto is_even = !(i % 2);
  9338. std::thread t{[&] {
  9339. try {
  9340. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9341. if (is_even) {
  9342. throw std::runtime_error("Some thing that happens to go wrong.");
  9343. }
  9344. svr.listen(HOST, PORT);
  9345. } catch (...) { svr.decommission(); }
  9346. }};
  9347. svr.wait_until_ready();
  9348. // Server is up
  9349. {
  9350. Client cli(HOST, PORT);
  9351. auto res = cli.Get("/hi");
  9352. if (is_even) {
  9353. EXPECT_FALSE(res);
  9354. } else {
  9355. EXPECT_TRUE(res);
  9356. EXPECT_EQ("hi...", res->body);
  9357. }
  9358. }
  9359. svr.stop();
  9360. t.join();
  9361. // Server is down...
  9362. {
  9363. Client cli(HOST, PORT);
  9364. auto res = cli.Get("/hi");
  9365. EXPECT_FALSE(res);
  9366. }
  9367. }
  9368. }
  9369. #endif
  9370. // Helper function for string body upload progress tests
  9371. template <typename SetupHandler, typename ClientCall>
  9372. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9373. ClientCall &&client_call,
  9374. const string &body) {
  9375. Server svr;
  9376. setup_handler(svr);
  9377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9378. auto se = detail::scope_exit([&] {
  9379. svr.stop();
  9380. t.join();
  9381. });
  9382. svr.wait_until_ready();
  9383. Client cli(HOST, PORT);
  9384. vector<uint64_t> progress_values;
  9385. bool progress_called = false;
  9386. auto res =
  9387. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9388. progress_values.push_back(current);
  9389. progress_called = true;
  9390. return true;
  9391. });
  9392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9393. EXPECT_EQ(200, res->status);
  9394. EXPECT_TRUE(progress_called);
  9395. }
  9396. TEST(UploadProgressTest, PostStringBodyBasic) {
  9397. TestStringBodyUploadProgress(
  9398. [](Server &svr) {
  9399. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9400. res.set_content("received", "text/plain");
  9401. });
  9402. },
  9403. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9404. return cli.Post("/test", body, "text/plain", progress_callback);
  9405. },
  9406. "test data for upload progress");
  9407. }
  9408. TEST(UploadProgressTest, PutStringBodyBasic) {
  9409. TestStringBodyUploadProgress(
  9410. [](Server &svr) {
  9411. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9412. res.set_content("put received", "text/plain");
  9413. });
  9414. },
  9415. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9416. return cli.Put("/test", body, "text/plain", progress_callback);
  9417. },
  9418. "put test data for upload progress");
  9419. }
  9420. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9421. TestStringBodyUploadProgress(
  9422. [](Server &svr) {
  9423. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9424. res.set_content("patch received", "text/plain");
  9425. });
  9426. },
  9427. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9428. return cli.Patch("/test", body, "text/plain", progress_callback);
  9429. },
  9430. "patch test data for upload progress");
  9431. }
  9432. // Helper function for content provider upload progress tests
  9433. template <typename SetupHandler, typename ClientCall>
  9434. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9435. ClientCall &&client_call) {
  9436. Server svr;
  9437. setup_handler(svr);
  9438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9439. auto se = detail::scope_exit([&] {
  9440. svr.stop();
  9441. t.join();
  9442. });
  9443. svr.wait_until_ready();
  9444. Client cli(HOST, PORT);
  9445. vector<uint64_t> progress_values;
  9446. auto res =
  9447. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9448. progress_values.push_back(current);
  9449. return true;
  9450. });
  9451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9452. EXPECT_EQ(200, res->status);
  9453. EXPECT_FALSE(progress_values.empty());
  9454. }
  9455. TEST(UploadProgressTest, PostContentProviderProgress) {
  9456. TestContentProviderUploadProgress(
  9457. [](Server &svr) {
  9458. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9459. res.set_content("provider received", "text/plain");
  9460. });
  9461. },
  9462. [](Client &cli, UploadProgress progress_callback) {
  9463. return cli.Post(
  9464. "/test", 10,
  9465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9466. sink.os << "test data";
  9467. return true;
  9468. },
  9469. "text/plain", progress_callback);
  9470. });
  9471. }
  9472. // Helper function for multipart upload progress tests
  9473. template <typename SetupHandler, typename ClientCall>
  9474. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9475. ClientCall &&client_call,
  9476. const string &endpoint) {
  9477. Server svr;
  9478. setup_handler(svr);
  9479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9480. auto se = detail::scope_exit([&] {
  9481. svr.stop();
  9482. t.join();
  9483. });
  9484. svr.wait_until_ready();
  9485. Client cli(HOST, PORT);
  9486. vector<uint64_t> progress_values;
  9487. UploadFormDataItems items = {
  9488. {"field1", "value1", "", ""},
  9489. {"field2", "longer value for progress tracking test", "", ""},
  9490. {"file1", "file content data for upload progress", "test.txt",
  9491. "text/plain"}};
  9492. auto res = client_call(cli, endpoint, items,
  9493. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9494. progress_values.push_back(current);
  9495. return true;
  9496. });
  9497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9498. EXPECT_EQ(200, res->status);
  9499. EXPECT_FALSE(progress_values.empty());
  9500. }
  9501. TEST(UploadProgressTest, PostMultipartProgress) {
  9502. TestMultipartUploadProgress(
  9503. [](Server &svr) {
  9504. svr.Post("/multipart", [](const Request &req, Response &res) {
  9505. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9506. res.set_content("multipart received", "text/plain");
  9507. });
  9508. },
  9509. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9510. UploadProgress progress_callback) {
  9511. return cli.Post(endpoint, items, progress_callback);
  9512. },
  9513. "/multipart");
  9514. }
  9515. // Helper function for basic download progress tests
  9516. template <typename SetupHandler, typename ClientCall>
  9517. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9518. ClientCall &&client_call, const string &endpoint,
  9519. size_t expected_content_size) {
  9520. Server svr;
  9521. setup_handler(svr);
  9522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9523. auto se = detail::scope_exit([&] {
  9524. svr.stop();
  9525. t.join();
  9526. });
  9527. svr.wait_until_ready();
  9528. Client cli(HOST, PORT);
  9529. vector<uint64_t> progress_values;
  9530. auto res = client_call(cli, endpoint,
  9531. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9532. progress_values.push_back(current);
  9533. return true;
  9534. });
  9535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9536. EXPECT_EQ(200, res->status);
  9537. EXPECT_FALSE(progress_values.empty());
  9538. EXPECT_EQ(expected_content_size, res->body.size());
  9539. }
  9540. TEST(DownloadProgressTest, GetBasic) {
  9541. TestBasicDownloadProgress(
  9542. [](Server &svr) {
  9543. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9544. string content(1000, 'D');
  9545. res.set_content(content, "text/plain");
  9546. });
  9547. },
  9548. [](Client &cli, const string &endpoint,
  9549. DownloadProgress progress_callback) {
  9550. return cli.Get(endpoint, progress_callback);
  9551. },
  9552. "/download", 1000u);
  9553. }
  9554. // Helper function for content receiver download progress tests
  9555. template <typename SetupHandler, typename ClientCall>
  9556. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9557. ClientCall &&client_call,
  9558. const string &endpoint,
  9559. size_t expected_content_size) {
  9560. Server svr;
  9561. setup_handler(svr);
  9562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9563. auto se = detail::scope_exit([&] {
  9564. svr.stop();
  9565. t.join();
  9566. });
  9567. svr.wait_until_ready();
  9568. Client cli(HOST, PORT);
  9569. vector<uint64_t> progress_values;
  9570. string received_body;
  9571. auto res = client_call(
  9572. cli, endpoint,
  9573. [&](const char *data, size_t data_length) -> bool {
  9574. received_body.append(data, data_length);
  9575. return true;
  9576. },
  9577. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9578. progress_values.push_back(current);
  9579. return true;
  9580. });
  9581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9582. EXPECT_EQ(200, res->status);
  9583. EXPECT_FALSE(progress_values.empty());
  9584. EXPECT_EQ(expected_content_size, received_body.size());
  9585. EXPECT_TRUE(res->body.empty());
  9586. }
  9587. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9588. TestContentReceiverDownloadProgress(
  9589. [](Server &svr) {
  9590. svr.Get("/download-receiver",
  9591. [](const Request & /*req*/, Response &res) {
  9592. string content(2000, 'R');
  9593. res.set_content(content, "text/plain");
  9594. });
  9595. },
  9596. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9597. DownloadProgress progress_callback) {
  9598. return cli.Get(endpoint, content_receiver, progress_callback);
  9599. },
  9600. "/download-receiver", 2000u);
  9601. }
  9602. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9603. // A provider reaching a pass with nothing to hand over - an empty buffer
  9604. // popped off a queue, say - must not be taken to mean the body is finished.
  9605. // It used to end the loop with the terminating chunk unwritten while the
  9606. // server still considered the response complete, so the peer waited for an
  9607. // end that never arrived.
  9608. Server svr;
  9609. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9610. auto step = std::make_shared<int>(0);
  9611. res.set_chunked_content_provider("text/plain",
  9612. [step](size_t /*offset*/, DataSink &sink) {
  9613. switch ((*step)++) {
  9614. case 0: sink.write("", 0); break;
  9615. case 1: sink.write("hello", 5); break;
  9616. default: sink.done(); break;
  9617. }
  9618. return true;
  9619. });
  9620. });
  9621. auto port = svr.bind_to_any_port(HOST);
  9622. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9623. auto listen_se = detail::scope_exit([&] {
  9624. svr.stop();
  9625. listen_thread.join();
  9626. ASSERT_FALSE(svr.is_running());
  9627. });
  9628. svr.wait_until_ready();
  9629. Client cli(HOST, port);
  9630. // Without the fix the body is never terminated, so bound the wait rather
  9631. // than letting the test hang on the default read timeout.
  9632. cli.set_read_timeout(5, 0);
  9633. auto res = cli.Get("/stream");
  9634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9635. EXPECT_EQ(StatusCode::OK_200, res->status);
  9636. EXPECT_EQ("hello", res->body);
  9637. }
  9638. TEST(StreamingTest, NoContentLengthStreaming) {
  9639. Server svr;
  9640. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9641. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9642. if (offset < 6) {
  9643. sink.os << (offset < 3 ? "a" : "b");
  9644. } else {
  9645. sink.done();
  9646. }
  9647. return true;
  9648. });
  9649. });
  9650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9651. auto listen_se = detail::scope_exit([&] {
  9652. svr.stop();
  9653. listen_thread.join();
  9654. ASSERT_FALSE(svr.is_running());
  9655. });
  9656. svr.wait_until_ready();
  9657. Client client(HOST, PORT);
  9658. auto get_thread = std::thread([&client]() {
  9659. std::string s;
  9660. auto res =
  9661. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9662. s += std::string(data, len);
  9663. return true;
  9664. });
  9665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9666. EXPECT_EQ(StatusCode::OK_200, res->status);
  9667. EXPECT_EQ("aaabbb", s);
  9668. });
  9669. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9670. // Give GET time to get a few messages.
  9671. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9672. }
  9673. TEST(MountTest, Unmount) {
  9674. Server svr;
  9675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9676. auto se = detail::scope_exit([&] {
  9677. svr.stop();
  9678. listen_thread.join();
  9679. ASSERT_FALSE(svr.is_running());
  9680. });
  9681. svr.wait_until_ready();
  9682. Client cli("localhost", PORT);
  9683. svr.set_mount_point("/mount2", "./www2");
  9684. auto res = cli.Get("/");
  9685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9687. res = cli.Get("/mount2/dir/test.html");
  9688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9689. EXPECT_EQ(StatusCode::OK_200, res->status);
  9690. svr.set_mount_point("/", "./www");
  9691. res = cli.Get("/dir/");
  9692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9693. EXPECT_EQ(StatusCode::OK_200, res->status);
  9694. svr.remove_mount_point("/");
  9695. res = cli.Get("/dir/");
  9696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9698. svr.remove_mount_point("/mount2");
  9699. res = cli.Get("/mount2/dir/test.html");
  9700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9702. }
  9703. TEST(MountTest, PathSegmentBoundary) {
  9704. Server svr;
  9705. svr.set_mount_point("/mount2", "./www2");
  9706. svr.set_mount_point("/", "./www");
  9707. auto port = svr.bind_to_any_port(HOST);
  9708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9709. auto se = detail::scope_exit([&] {
  9710. svr.stop();
  9711. listen_thread.join();
  9712. ASSERT_FALSE(svr.is_running());
  9713. });
  9714. svr.wait_until_ready();
  9715. Client cli(HOST, port);
  9716. auto res = cli.Get("/mount2/dir/test.html");
  9717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9718. EXPECT_EQ(StatusCode::OK_200, res->status);
  9719. // "/mount2" must not match part-way through a path segment.
  9720. res = cli.Get("/mount2dir/test.html");
  9721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9723. // A mount point ending in '/' keeps matching every path below it.
  9724. res = cli.Get("/dir/test.html");
  9725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9726. EXPECT_EQ(StatusCode::OK_200, res->status);
  9727. }
  9728. TEST(MountTest, Redicect) {
  9729. Server svr;
  9730. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9731. auto se = detail::scope_exit([&] {
  9732. svr.stop();
  9733. listen_thread.join();
  9734. ASSERT_FALSE(svr.is_running());
  9735. });
  9736. svr.set_mount_point("/", "./www");
  9737. svr.wait_until_ready();
  9738. Client cli("localhost", PORT);
  9739. auto res = cli.Get("/dir/");
  9740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9741. EXPECT_EQ(StatusCode::OK_200, res->status);
  9742. res = cli.Get("/dir");
  9743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9744. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9745. res = cli.Get("/file");
  9746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9747. EXPECT_EQ(StatusCode::OK_200, res->status);
  9748. res = cli.Get("/file/");
  9749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9751. cli.set_follow_location(true);
  9752. res = cli.Get("/dir");
  9753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9754. EXPECT_EQ(StatusCode::OK_200, res->status);
  9755. }
  9756. TEST(MountTest, MultibytesPathName) {
  9757. Server svr;
  9758. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9759. auto se = detail::scope_exit([&] {
  9760. svr.stop();
  9761. listen_thread.join();
  9762. ASSERT_FALSE(svr.is_running());
  9763. });
  9764. svr.set_mount_point("/", "./www");
  9765. svr.wait_until_ready();
  9766. Client cli("localhost", PORT);
  9767. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9769. EXPECT_EQ(StatusCode::OK_200, res->status);
  9770. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9771. }
  9772. #ifdef _WIN32
  9773. // Issue #2435: mmap::open() must succeed even when another handle holds
  9774. // the file open for writing (e.g. an active log file).
  9775. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9776. const char *path = "mmap_concurrent_writer_test.txt";
  9777. const char *content = "hello";
  9778. {
  9779. std::ofstream f(path, std::ios::binary);
  9780. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9781. }
  9782. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9783. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9784. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9785. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9786. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9787. detail::mmap m(path);
  9788. ASSERT_TRUE(m.is_open());
  9789. EXPECT_EQ(strlen(content), m.size());
  9790. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9791. }
  9792. #endif
  9793. #ifndef _WIN32
  9794. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9795. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9796. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9797. TEST(MmapTest, FailedMappingIsNotOpen) {
  9798. const char *path = "./mmap_failed_mapping_test_dir";
  9799. ASSERT_EQ(0, ::mkdir(path, 0755));
  9800. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9801. detail::mmap m(path);
  9802. EXPECT_FALSE(m.is_open());
  9803. EXPECT_EQ(0U, m.size());
  9804. EXPECT_NE(static_cast<const void *>(m.data()),
  9805. static_cast<const void *>(MAP_FAILED));
  9806. }
  9807. #endif
  9808. TEST(KeepAliveTest, ReadTimeout) {
  9809. Server svr;
  9810. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9811. std::this_thread::sleep_for(std::chrono::seconds(2));
  9812. res.set_content("a", "text/plain");
  9813. });
  9814. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9815. res.set_content("b", "text/plain");
  9816. });
  9817. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9818. auto se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. listen_thread.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. });
  9823. svr.wait_until_ready();
  9824. Client cli("localhost", PORT);
  9825. cli.set_keep_alive(true);
  9826. cli.set_read_timeout(std::chrono::seconds(1));
  9827. auto resa = cli.Get("/a");
  9828. ASSERT_FALSE(resa);
  9829. EXPECT_EQ(Error::Read, resa.error());
  9830. auto resb = cli.Get("/b");
  9831. ASSERT_TRUE(resb);
  9832. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9833. EXPECT_EQ("b", resb->body);
  9834. }
  9835. TEST(KeepAliveTest, MaxCount) {
  9836. size_t keep_alive_max_count = 3;
  9837. Server svr;
  9838. svr.set_keep_alive_max_count(keep_alive_max_count);
  9839. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9840. res.set_content("Hello World!", "text/plain");
  9841. });
  9842. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. listen_thread.join();
  9846. ASSERT_FALSE(svr.is_running());
  9847. });
  9848. svr.wait_until_ready();
  9849. Client cli(HOST, PORT);
  9850. cli.set_keep_alive(true);
  9851. for (size_t i = 0; i < 5; i++) {
  9852. auto result = cli.Get("/hi");
  9853. ASSERT_TRUE(result);
  9854. EXPECT_EQ(StatusCode::OK_200, result->status);
  9855. if (i == keep_alive_max_count - 1) {
  9856. EXPECT_EQ("close", result->get_header_value("Connection"));
  9857. } else {
  9858. EXPECT_FALSE(result->has_header("Connection"));
  9859. }
  9860. }
  9861. }
  9862. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9863. // can pull the next one into the server's buffer. The server must serve it
  9864. // without waiting for the socket to become readable again. The keep-alive
  9865. // timeout outlasts the client's read timeout, so a request left waiting for it
  9866. // shows up as a missing response.
  9867. static void serve_pipelining_routes(Server &svr,
  9868. const std::function<void(int)> &client) {
  9869. svr.set_keep_alive_timeout(5);
  9870. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9871. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9872. });
  9873. svr.Post("/echo", [](const Request &req, Response &res) {
  9874. res.set_content("echo " + req.body, "text/plain");
  9875. });
  9876. auto port = svr.bind_to_any_port(HOST);
  9877. thread t = thread([&] { svr.listen_after_bind(); });
  9878. auto se = detail::scope_exit([&] {
  9879. svr.stop();
  9880. t.join();
  9881. });
  9882. svr.wait_until_ready();
  9883. client(port);
  9884. }
  9885. static std::string
  9886. send_pipelined_requests(const std::vector<std::string> &parts) {
  9887. Server svr;
  9888. std::string res;
  9889. serve_pipelining_routes(svr, [&](int port) {
  9890. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9891. });
  9892. return res;
  9893. }
  9894. static void expect_in_order(const std::string &res,
  9895. const std::vector<std::string> &bodies) {
  9896. size_t pos = 0;
  9897. for (const auto &body : bodies) {
  9898. pos = res.find(body, pos);
  9899. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9900. pos += body.size();
  9901. }
  9902. }
  9903. TEST(KeepAliveTest, PipelinedRequests) {
  9904. auto res = send_pipelined_requests(
  9905. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9906. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9907. "Content-Length: 4\r\n\r\nbody"
  9908. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9909. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9910. }
  9911. // The second request starts in the server's buffer and ends on the socket.
  9912. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9913. auto res =
  9914. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9915. "GET /hi/2 HTTP/1.1\r\nHo",
  9916. "st: localhost\r\nConnection: close\r\n\r\n"});
  9917. expect_in_order(res, {"hi 1", "hi 2"});
  9918. }
  9919. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9920. // CRLF after a body does not turn into a 400 for the next request.
  9921. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9922. auto res = send_pipelined_requests(
  9923. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9924. "Content-Length: 4\r\n\r\nbody\r\n"
  9925. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9926. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9927. expect_in_order(res, {"echo body", "hi 2"});
  9928. }
  9929. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9930. // must not be served as the next request.
  9931. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9932. auto res = send_pipelined_requests(
  9933. {"INVALID REQUEST LINE\r\n\r\n"
  9934. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9936. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9937. }
  9938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9939. // Over TLS, the next request is held by the TLS library as already decrypted
  9940. // data rather than on the socket.
  9941. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9943. std::string res;
  9944. serve_pipelining_routes(svr, [&](int port) {
  9945. auto error = Error::Success;
  9946. auto sock = detail::create_client_socket(
  9947. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9948. /*connection_timeout_sec=*/5, 0,
  9949. /*read_timeout_sec=*/2, 0,
  9950. /*write_timeout_sec=*/5, 0, std::string(), error);
  9951. ASSERT_NE(INVALID_SOCKET, sock);
  9952. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9953. auto ctx = SSL_CTX_new(TLS_client_method());
  9954. auto ssl = SSL_new(ctx);
  9955. auto ssl_se = detail::scope_exit([&] {
  9956. SSL_free(ssl);
  9957. SSL_CTX_free(ctx);
  9958. });
  9959. SSL_set_fd(ssl, static_cast<int>(sock));
  9960. ASSERT_EQ(1, SSL_connect(ssl));
  9961. // One write, so all three requests arrive in one TLS record
  9962. const std::string req =
  9963. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9964. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9965. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9966. ASSERT_EQ(static_cast<int>(req.size()),
  9967. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9968. char buf[512];
  9969. int n;
  9970. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9971. res.append(buf, static_cast<size_t>(n));
  9972. }
  9973. });
  9974. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9975. }
  9976. #endif
  9977. TEST(KeepAliveTest, Issue1041) {
  9978. Server svr;
  9979. svr.set_keep_alive_timeout(3);
  9980. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9981. res.set_content("Hello World!", "text/plain");
  9982. });
  9983. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9984. auto se = detail::scope_exit([&] {
  9985. svr.stop();
  9986. listen_thread.join();
  9987. ASSERT_FALSE(svr.is_running());
  9988. });
  9989. svr.wait_until_ready();
  9990. Client cli(HOST, PORT);
  9991. cli.set_keep_alive(true);
  9992. auto result = cli.Get("/hi");
  9993. ASSERT_TRUE(result);
  9994. EXPECT_EQ(StatusCode::OK_200, result->status);
  9995. std::this_thread::sleep_for(std::chrono::seconds(5));
  9996. result = cli.Get("/hi");
  9997. ASSERT_TRUE(result);
  9998. EXPECT_EQ(StatusCode::OK_200, result->status);
  9999. }
  10000. TEST(KeepAliveTest, Issue1959) {
  10001. Server svr;
  10002. svr.set_keep_alive_timeout(5);
  10003. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10004. res.set_content("a", "text/plain");
  10005. });
  10006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10007. auto se = detail::scope_exit([&] {
  10008. if (!svr.is_running()) return;
  10009. svr.stop();
  10010. listen_thread.join();
  10011. ASSERT_FALSE(svr.is_running());
  10012. });
  10013. svr.wait_until_ready();
  10014. Client cli("localhost", PORT);
  10015. cli.set_keep_alive(true);
  10016. using namespace std::chrono;
  10017. auto start = steady_clock::now();
  10018. cli.Get("/a");
  10019. svr.stop();
  10020. listen_thread.join();
  10021. auto end = steady_clock::now();
  10022. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10023. EXPECT_LT(elapsed, 5000);
  10024. }
  10025. #ifdef CPPHTTPLIB_SSL_ENABLED
  10026. TEST(KeepAliveTest, SSLClientReconnection) {
  10027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10028. ASSERT_TRUE(svr.is_valid());
  10029. svr.set_keep_alive_timeout(1);
  10030. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10031. res.set_content("Hello World!", "text/plain");
  10032. });
  10033. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10034. auto se = detail::scope_exit([&] {
  10035. svr.stop();
  10036. listen_thread.join();
  10037. ASSERT_FALSE(svr.is_running());
  10038. });
  10039. svr.wait_until_ready();
  10040. SSLClient cli(HOST, PORT);
  10041. cli.enable_server_certificate_verification(false);
  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. result = cli.Get("/hi");
  10047. ASSERT_TRUE(result);
  10048. EXPECT_EQ(StatusCode::OK_200, result->status);
  10049. std::this_thread::sleep_for(std::chrono::seconds(2));
  10050. // Recoonect
  10051. result = cli.Get("/hi");
  10052. ASSERT_TRUE(result);
  10053. EXPECT_EQ(StatusCode::OK_200, result->status);
  10054. result = cli.Get("/hi");
  10055. ASSERT_TRUE(result);
  10056. EXPECT_EQ(StatusCode::OK_200, result->status);
  10057. }
  10058. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10060. ASSERT_TRUE(svr.is_valid());
  10061. svr.set_keep_alive_timeout(1);
  10062. std::string content = "reconnect";
  10063. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10064. res.set_content("Hello World!", "text/plain");
  10065. });
  10066. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10067. auto se = detail::scope_exit([&] {
  10068. svr.stop();
  10069. listen_thread.join();
  10070. ASSERT_FALSE(svr.is_running());
  10071. });
  10072. svr.wait_until_ready();
  10073. SSLClient cli(HOST, PORT);
  10074. cli.enable_server_certificate_verification(false);
  10075. cli.set_keep_alive(true);
  10076. auto result = cli.Post(
  10077. "/hi", content.size(),
  10078. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10079. sink.write(content.c_str(), content.size());
  10080. return true;
  10081. },
  10082. "text/plain");
  10083. ASSERT_TRUE(result);
  10084. EXPECT_EQ(200, result->status);
  10085. std::this_thread::sleep_for(std::chrono::seconds(2));
  10086. // Recoonect
  10087. result = cli.Post(
  10088. "/hi", content.size(),
  10089. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10090. sink.write(content.c_str(), content.size());
  10091. return true;
  10092. },
  10093. "text/plain");
  10094. ASSERT_TRUE(result);
  10095. EXPECT_EQ(200, result->status);
  10096. result = cli.Post(
  10097. "/hi", content.size(),
  10098. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10099. sink.write(content.c_str(), content.size());
  10100. return true;
  10101. },
  10102. "text/plain");
  10103. ASSERT_TRUE(result);
  10104. EXPECT_EQ(200, result->status);
  10105. }
  10106. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10107. using namespace httplib::tls;
  10108. {
  10109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10110. ASSERT_TRUE(svr.is_valid());
  10111. svr.Get("/sni", [&](const Request &req, Response &res) {
  10112. std::string expected = req.sni();
  10113. EXPECT_EQ(expected, req.get_param_value("expected"));
  10114. res.set_content("ok", "text/plain");
  10115. });
  10116. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10117. auto se = detail::scope_exit([&] {
  10118. svr.stop();
  10119. listen_thread.join();
  10120. ASSERT_FALSE(svr.is_running());
  10121. });
  10122. svr.wait_until_ready();
  10123. {
  10124. SSLClient cli("localhost", PORT);
  10125. cli.enable_server_certificate_verification(false);
  10126. auto res = cli.Get("/sni?expected=localhost");
  10127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10128. }
  10129. {
  10130. SSLClient cli("::1", PORT);
  10131. cli.enable_server_certificate_verification(false);
  10132. auto res = cli.Get("/sni?expected=");
  10133. // NOTE: This may fail if the server is listening on IPv4 only
  10134. // (e.g., when localhost resolves to 127.0.0.1 only)
  10135. if (res) {
  10136. EXPECT_EQ(StatusCode::OK_200, res->status);
  10137. } else {
  10138. EXPECT_EQ(Error::Connection, res.error());
  10139. }
  10140. }
  10141. }
  10142. }
  10143. #endif
  10144. TEST(ClientProblemDetectionTest, ContentProvider) {
  10145. Server svr;
  10146. size_t content_length = 1024 * 1024;
  10147. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10148. res.set_content_provider(
  10149. content_length, "text/plain",
  10150. [&](size_t offset, size_t length, DataSink &sink) {
  10151. auto out_len = std::min(length, static_cast<size_t>(1024));
  10152. std::string out(out_len, '@');
  10153. sink.write(out.data(), out_len);
  10154. return offset < 4096;
  10155. },
  10156. [](bool success) { ASSERT_FALSE(success); });
  10157. });
  10158. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10159. res.set_content_provider(
  10160. 0, "text/plain",
  10161. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10162. EXPECT_TRUE(false);
  10163. return true;
  10164. },
  10165. [](bool success) { ASSERT_FALSE(success); });
  10166. });
  10167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", 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. Client cli("localhost", PORT);
  10175. {
  10176. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10177. size_t /*data_length*/) { return false; });
  10178. ASSERT_FALSE(res);
  10179. }
  10180. {
  10181. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10182. size_t /*data_length*/) { return false; });
  10183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10184. }
  10185. }
  10186. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10187. // A provider that reports success without writing anything and without
  10188. // calling done() used to be handed the same offset and length again on every
  10189. // pass, so it spun for as long as the peer stayed connected.
  10190. Server svr;
  10191. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10192. res.set_content("ok", "text/plain");
  10193. });
  10194. auto port = svr.bind_to_any_port(HOST);
  10195. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. listen_thread.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. });
  10201. svr.wait_until_ready();
  10202. std::atomic<int> call_count{0};
  10203. Client cli(HOST, port);
  10204. auto res = cli.Post(
  10205. "/", 1024,
  10206. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10207. // Give up after enough passes to show the spin, so that losing the
  10208. // check below fails this test instead of hanging it.
  10209. return ++call_count < 100;
  10210. },
  10211. "text/plain");
  10212. ASSERT_FALSE(res);
  10213. EXPECT_EQ(Error::Write, res.error());
  10214. EXPECT_EQ(1, call_count.load());
  10215. }
  10216. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10217. // A writer only has to assign `write`. The other three used to be left as
  10218. // empty std::functions, so a provider calling one threw
  10219. // std::bad_function_call out of the thread running it and took the whole
  10220. // process down.
  10221. DataSink sink;
  10222. std::string written;
  10223. sink.write = [&](const char *data, size_t data_len) {
  10224. written.append(data, data_len);
  10225. return true;
  10226. };
  10227. EXPECT_TRUE(sink.is_writable());
  10228. sink.done();
  10229. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10230. EXPECT_TRUE(written.empty());
  10231. }
  10232. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10233. // A sink that cannot carry trailers still has to finish.
  10234. DataSink sink;
  10235. auto done_count = 0;
  10236. sink.done = [&]() { done_count++; };
  10237. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10238. EXPECT_EQ(1, done_count);
  10239. }
  10240. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10241. Server svr;
  10242. const std::string body(4096, 'x');
  10243. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10244. res.set_content_provider(body.size(), "text/plain",
  10245. [&](size_t offset, size_t length, DataSink &sink) {
  10246. sink.write(body.data() + offset, length);
  10247. sink.done();
  10248. return true;
  10249. });
  10250. });
  10251. auto port = svr.bind_to_any_port(HOST);
  10252. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. listen_thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. Client cli(HOST, port);
  10260. auto res = cli.Get("/");
  10261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10262. EXPECT_EQ(StatusCode::OK_200, res->status);
  10263. EXPECT_EQ(body, res->body);
  10264. }
  10265. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10266. Server svr;
  10267. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10268. res.set_content_provider(
  10269. 1024, "text/plain",
  10270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10271. sink.write("hello", 5);
  10272. sink.done(); // short of the 1024 bytes the response promised
  10273. return true;
  10274. });
  10275. });
  10276. auto port = svr.bind_to_any_port(HOST);
  10277. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10278. auto se = detail::scope_exit([&] {
  10279. svr.stop();
  10280. listen_thread.join();
  10281. ASSERT_FALSE(svr.is_running());
  10282. });
  10283. svr.wait_until_ready();
  10284. Client cli(HOST, port);
  10285. cli.set_read_timeout(5, 0);
  10286. // The response is short of its Content-Length, so the client cannot read a
  10287. // complete body. What matters is that this returns at all: a no-op done()
  10288. // would leave the writer looping over a provider that never makes progress.
  10289. auto res = cli.Get("/");
  10290. EXPECT_FALSE(res);
  10291. }
  10292. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10293. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10294. // The compressed path builds the whole body before connecting, so this
  10295. // fails client-side and never reaches a server.
  10296. Client cli(HOST, PORT);
  10297. cli.set_compress(true);
  10298. auto res = cli.Post(
  10299. "/", 1024,
  10300. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10301. sink.write("hello", 5);
  10302. sink.done(); // short of the 1024 bytes the request announced
  10303. return true;
  10304. },
  10305. "text/plain");
  10306. ASSERT_FALSE(res);
  10307. EXPECT_EQ(Error::Write, res.error());
  10308. }
  10309. #endif
  10310. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10311. Server svr;
  10312. svr.set_error_handler([](Request const &, Response &res) -> void {
  10313. res.set_chunked_content_provider(
  10314. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10315. sink.os << "hello";
  10316. sink.os << "world";
  10317. sink.done();
  10318. return true;
  10319. });
  10320. });
  10321. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10322. auto se = detail::scope_exit([&] {
  10323. svr.stop();
  10324. listen_thread.join();
  10325. ASSERT_FALSE(svr.is_running());
  10326. });
  10327. svr.wait_until_ready();
  10328. Client cli("localhost", PORT);
  10329. auto res = cli.Get("/");
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10332. EXPECT_EQ("helloworld", res->body);
  10333. }
  10334. // A body set after a content provider must replace it, not be sent through it.
  10335. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10336. Server svr;
  10337. svr.set_mount_point("/", "./www");
  10338. svr.set_file_request_handler([](const Request &req, Response &res) {
  10339. if (req.path == "/dir/test.html") {
  10340. res.status = StatusCode::Forbidden_403;
  10341. res.set_content(std::string(5000, 'D'), "text/plain");
  10342. } else if (req.path == "/file") {
  10343. res.status = StatusCode::Forbidden_403;
  10344. res.body = "Denied";
  10345. }
  10346. });
  10347. auto port = svr.bind_to_any_port(HOST);
  10348. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10349. auto se = detail::scope_exit([&] {
  10350. svr.stop();
  10351. t.join();
  10352. ASSERT_FALSE(svr.is_running());
  10353. });
  10354. svr.wait_until_ready();
  10355. Client cli(HOST, port);
  10356. {
  10357. auto res = cli.Get("/dir/test.html");
  10358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10359. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10360. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10361. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10362. }
  10363. {
  10364. auto res = cli.Get("/file");
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10367. EXPECT_EQ("Denied", res->body);
  10368. }
  10369. {
  10370. auto res = cli.Get("/dir/index.html");
  10371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10372. EXPECT_EQ(StatusCode::OK_200, res->status);
  10373. EXPECT_EQ(0U, res->body.find("<html>"));
  10374. }
  10375. }
  10376. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10377. Server svr;
  10378. std::vector<bool> released;
  10379. std::mutex released_mutex;
  10380. auto releaser = [&](bool success) {
  10381. std::lock_guard<std::mutex> guard(released_mutex);
  10382. released.push_back(success);
  10383. };
  10384. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10385. return sink.write(&"hello"[offset], length);
  10386. };
  10387. svr.Get("/sized", [&](const Request &, Response &res) {
  10388. res.status = StatusCode::NotFound_404;
  10389. res.set_content_provider(5, "text/plain", provider, releaser);
  10390. });
  10391. svr.Get("/chunked", [&](const Request &, Response &res) {
  10392. res.status = StatusCode::ServiceUnavailable_503;
  10393. res.set_chunked_content_provider(
  10394. "text/plain",
  10395. [](size_t, DataSink &sink) {
  10396. sink.os << "chunk";
  10397. sink.done();
  10398. return true;
  10399. },
  10400. releaser);
  10401. });
  10402. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10403. res.set_content_provider(5, "text/plain", provider, releaser);
  10404. throw std::runtime_error("after the provider");
  10405. });
  10406. svr.set_error_handler([](const Request &req, Response &res) {
  10407. // Leave the exception handler's content to it.
  10408. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10409. res.set_content(std::string(1000, 'E'), "text/html");
  10410. return Server::HandlerResponse::Handled;
  10411. });
  10412. svr.set_exception_handler(
  10413. [](const Request &, Response &res, std::exception_ptr) {
  10414. res.status = StatusCode::InternalServerError_500;
  10415. res.set_content(std::string(1000, 'X'), "text/html");
  10416. });
  10417. auto port = svr.bind_to_any_port(HOST);
  10418. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. t.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. Client cli(HOST, port);
  10426. {
  10427. auto res = cli.Get("/sized");
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10430. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10431. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10432. }
  10433. {
  10434. auto res = cli.Get("/chunked");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10437. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10438. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10439. }
  10440. {
  10441. auto res = cli.Get("/throw");
  10442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10443. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10444. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10445. }
  10446. std::lock_guard<std::mutex> guard(released_mutex);
  10447. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10448. }
  10449. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10450. Server svr;
  10451. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10452. return sink.write(&"abc"[offset], length);
  10453. };
  10454. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10455. res.set_file_content("./www/dir/test.html");
  10456. res.set_content("body", "text/plain");
  10457. });
  10458. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10459. res.set_content(std::string(100, 'B'), "text/plain");
  10460. res.set_file_content("./www/dir/test.html");
  10461. });
  10462. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10463. res.set_content(std::string(100, 'B'), "text/plain");
  10464. res.set_content_provider(3, "text/plain", abc);
  10465. });
  10466. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10467. res.set_content_provider(3, "text/plain", abc);
  10468. res.set_content(std::string(100, 'B'), "text/plain");
  10469. });
  10470. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10471. res.set_content_provider(3, "text/plain", abc);
  10472. res.body = "direct";
  10473. });
  10474. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10475. res.set_file_content("./www/dir/test.html");
  10476. res.body = "direct";
  10477. });
  10478. auto port = svr.bind_to_any_port(HOST);
  10479. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10480. auto se = detail::scope_exit([&] {
  10481. svr.stop();
  10482. t.join();
  10483. ASSERT_FALSE(svr.is_running());
  10484. });
  10485. svr.wait_until_ready();
  10486. Client cli(HOST, port);
  10487. auto expect_body = [&](const char *path, const std::string &body) {
  10488. // Uncompressed, so Content-Length can be compared with the body.
  10489. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10490. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10491. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10492. EXPECT_EQ(body, res->body) << path;
  10493. EXPECT_EQ(std::to_string(body.size()),
  10494. res->get_header_value("Content-Length"))
  10495. << path;
  10496. };
  10497. expect_body("/file-then-body", "body");
  10498. expect_body("/body-then-file", "test.html");
  10499. expect_body("/body-then-provider", "abc");
  10500. expect_body("/provider-then-body", std::string(100, 'B'));
  10501. expect_body("/provider-then-direct-body", "direct");
  10502. expect_body("/file-then-direct-body", "direct");
  10503. // Ranges are checked against the body, not the dropped provider.
  10504. {
  10505. auto res = cli.Get("/provider-then-direct-body",
  10506. Headers{{make_range_header({{1, 2}})}});
  10507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10508. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10509. EXPECT_EQ("ir", res->body);
  10510. }
  10511. {
  10512. auto res = cli.Get("/file-then-direct-body",
  10513. Headers{{make_range_header({{7, 8}})}});
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10516. }
  10517. }
  10518. // Forward declaration (see the base64_encode note).
  10519. namespace httplib {
  10520. namespace detail {
  10521. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10522. const std::string &content_type,
  10523. EncodingType encoding);
  10524. } // namespace detail
  10525. } // namespace httplib
  10526. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10527. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10528. ASSERT_TRUE(mm->is_open());
  10529. Response res;
  10530. detail::set_file_content_provider(res, mm, "text/html",
  10531. detail::EncodingType::None);
  10532. std::string out;
  10533. DataSink sink;
  10534. sink.write = [&](const char *d, size_t l) {
  10535. out.append(d, l);
  10536. return true;
  10537. };
  10538. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10539. EXPECT_EQ("test.html", out);
  10540. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10541. EXPECT_EQ("test.html", out);
  10542. }
  10543. TEST(LongPollingTest, ClientCloseDetection) {
  10544. Server svr;
  10545. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10546. res.set_chunked_content_provider(
  10547. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10548. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10549. sink.os << "hello";
  10550. auto count = 10;
  10551. while (count > 0 && sink.is_writable()) {
  10552. this_thread::sleep_for(chrono::milliseconds(10));
  10553. count--;
  10554. }
  10555. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10556. return true;
  10557. });
  10558. });
  10559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10560. auto se = detail::scope_exit([&] {
  10561. svr.stop();
  10562. listen_thread.join();
  10563. ASSERT_FALSE(svr.is_running());
  10564. });
  10565. svr.wait_until_ready();
  10566. Client cli("localhost", PORT);
  10567. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10568. EXPECT_EQ("hello", string(data, data_length));
  10569. return false; // close the socket immediately.
  10570. });
  10571. ASSERT_FALSE(res);
  10572. }
  10573. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10574. Server svr;
  10575. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10576. res.set_chunked_content_provider(
  10577. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10578. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10579. sink.os << "hello";
  10580. EXPECT_TRUE(sink.os.good());
  10581. // Wait for the client to close the connection
  10582. auto count = 10;
  10583. while (count > 0 && sink.is_writable()) {
  10584. this_thread::sleep_for(chrono::milliseconds(10));
  10585. count--;
  10586. }
  10587. // After client disconnect, write repeatedly until the socket
  10588. // write actually fails (small writes may be absorbed by the
  10589. // kernel buffer)
  10590. std::string chunk(1024, 'x');
  10591. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10592. sink.os << chunk;
  10593. }
  10594. EXPECT_TRUE(sink.os.fail());
  10595. return true;
  10596. });
  10597. });
  10598. auto port = svr.bind_to_any_port("localhost");
  10599. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10600. auto se = detail::scope_exit([&] {
  10601. svr.stop();
  10602. listen_thread.join();
  10603. ASSERT_FALSE(svr.is_running());
  10604. });
  10605. svr.wait_until_ready();
  10606. Client cli("localhost", port);
  10607. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10608. EXPECT_EQ("hello", string(data, data_length));
  10609. return false; // close the socket immediately.
  10610. });
  10611. ASSERT_FALSE(res);
  10612. }
  10613. TEST(GetWithParametersTest, GetWithParameters) {
  10614. Server svr;
  10615. svr.Get("/", [&](const Request &req, Response &) {
  10616. EXPECT_EQ("world", req.get_param_value("hello"));
  10617. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10618. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10619. });
  10620. svr.Get("/params", [&](const Request &req, Response &) {
  10621. EXPECT_EQ("world", req.get_param_value("hello"));
  10622. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10623. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10624. });
  10625. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10626. EXPECT_EQ("resource-id", req.matches[1]);
  10627. EXPECT_EQ("foo", req.get_param_value("param1"));
  10628. EXPECT_EQ("bar", req.get_param_value("param2"));
  10629. });
  10630. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10631. EXPECT_EQ("user-id", req.path_params.at("id"));
  10632. EXPECT_EQ("foo", req.get_param_value("param1"));
  10633. EXPECT_EQ("bar", req.get_param_value("param2"));
  10634. });
  10635. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10636. auto se = detail::scope_exit([&] {
  10637. svr.stop();
  10638. listen_thread.join();
  10639. ASSERT_FALSE(svr.is_running());
  10640. });
  10641. svr.wait_until_ready();
  10642. {
  10643. Client cli(HOST, PORT);
  10644. Params params;
  10645. params.emplace("hello", "world");
  10646. params.emplace("hello2", "world2");
  10647. params.emplace("hello3", "world3");
  10648. auto res = cli.Get("/", params, Headers{});
  10649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10650. EXPECT_EQ(StatusCode::OK_200, res->status);
  10651. }
  10652. {
  10653. Client cli(HOST, PORT);
  10654. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10656. EXPECT_EQ(StatusCode::OK_200, res->status);
  10657. }
  10658. {
  10659. Client cli(HOST, PORT);
  10660. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10662. EXPECT_EQ(StatusCode::OK_200, res->status);
  10663. }
  10664. {
  10665. Client cli(HOST, PORT);
  10666. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10668. EXPECT_EQ(StatusCode::OK_200, res->status);
  10669. }
  10670. }
  10671. TEST(GetWithParametersTest, GetWithParameters2) {
  10672. Server svr;
  10673. svr.Get("/", [&](const Request &req, Response &res) {
  10674. auto text = req.get_param_value("hello");
  10675. res.set_content(text, "text/plain");
  10676. });
  10677. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10678. auto se = detail::scope_exit([&] {
  10679. svr.stop();
  10680. listen_thread.join();
  10681. ASSERT_FALSE(svr.is_running());
  10682. });
  10683. svr.wait_until_ready();
  10684. Client cli("localhost", PORT);
  10685. Params params;
  10686. params.emplace("hello", "world");
  10687. std::string body;
  10688. auto res = cli.Get("/", params, Headers{},
  10689. [&](const char *data, size_t data_length) {
  10690. body.append(data, data_length);
  10691. return true;
  10692. });
  10693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10694. EXPECT_EQ(StatusCode::OK_200, res->status);
  10695. EXPECT_EQ("world", body);
  10696. }
  10697. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10698. Server svr;
  10699. svr.Get("/search", [&](const Request &req, Response &res) {
  10700. auto q = req.get_param_value("q");
  10701. res.set_content(q, "text/plain");
  10702. });
  10703. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. listen_thread.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. Client cli("localhost", PORT);
  10711. // Verify that Get(path, params) works without requiring Headers argument
  10712. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10714. EXPECT_EQ(StatusCode::OK_200, res->status);
  10715. EXPECT_EQ("cpp-httplib", res->body);
  10716. }
  10717. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10718. auto host = "httpbingo.org";
  10719. auto path = std::string{"/range/32"};
  10720. #ifdef CPPHTTPLIB_SSL_ENABLED
  10721. SSLClient cli(host);
  10722. #else
  10723. Client cli(host);
  10724. #endif
  10725. cli.set_default_headers({make_range_header({{1, 10}})});
  10726. cli.set_connection_timeout(5);
  10727. {
  10728. auto res = cli.Get(path);
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. EXPECT_EQ("bcdefghijk", res->body);
  10731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10732. }
  10733. {
  10734. auto res = cli.Get(path);
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. EXPECT_EQ("bcdefghijk", res->body);
  10737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10738. }
  10739. }
  10740. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10741. Server svr;
  10742. svr.set_default_headers({{"Hello", "World"}});
  10743. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10744. res.set_content("ok", "text/plain");
  10745. });
  10746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10747. auto se = detail::scope_exit([&] {
  10748. svr.stop();
  10749. listen_thread.join();
  10750. ASSERT_FALSE(svr.is_running());
  10751. });
  10752. svr.wait_until_ready();
  10753. Client cli("localhost", PORT);
  10754. auto res = cli.Get("/");
  10755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10756. EXPECT_EQ(StatusCode::OK_200, res->status);
  10757. EXPECT_EQ("ok", res->body);
  10758. EXPECT_EQ("World", res->get_header_value("Hello"));
  10759. }
  10760. #ifdef CPPHTTPLIB_SSL_ENABLED
  10761. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10763. ASSERT_TRUE(svr.is_valid());
  10764. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10765. std::this_thread::sleep_for(std::chrono::seconds(2));
  10766. res.set_content("a", "text/plain");
  10767. });
  10768. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10769. res.set_content("b", "text/plain");
  10770. });
  10771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10772. auto se = detail::scope_exit([&] {
  10773. svr.stop();
  10774. listen_thread.join();
  10775. ASSERT_FALSE(svr.is_running());
  10776. });
  10777. svr.wait_until_ready();
  10778. SSLClient cli("localhost", PORT);
  10779. cli.enable_server_certificate_verification(false);
  10780. cli.set_keep_alive(true);
  10781. cli.set_read_timeout(std::chrono::seconds(1));
  10782. auto resa = cli.Get("/a");
  10783. ASSERT_TRUE(!resa);
  10784. EXPECT_EQ(Error::Read, resa.error());
  10785. auto resb = cli.Get("/b");
  10786. ASSERT_TRUE(resb);
  10787. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10788. EXPECT_EQ("b", resb->body);
  10789. }
  10790. // Closing an idle keep-alive connection sends close_notify and returns. The
  10791. // server must not wait for the client's close_notify: an idle client never
  10792. // sends one, so the worker would be held until the read timeout expires, and
  10793. // stop() would wait for it.
  10794. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10796. ASSERT_TRUE(svr.is_valid());
  10797. svr.set_keep_alive_timeout(1);
  10798. svr.set_read_timeout(10, 0);
  10799. svr.Get("/", [](const Request &, Response &res) {
  10800. res.set_content("ok", "text/plain");
  10801. });
  10802. auto port = svr.bind_to_any_port(HOST);
  10803. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10804. auto se = detail::scope_exit([&] {
  10805. if (listen_thread.joinable()) {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. }
  10809. });
  10810. svr.wait_until_ready();
  10811. SSLClient cli(HOST, port);
  10812. cli.enable_server_certificate_verification(false);
  10813. cli.set_keep_alive(true);
  10814. auto res = cli.Get("/");
  10815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10816. EXPECT_EQ(StatusCode::OK_200, res->status);
  10817. // Stay idle past the keep-alive timeout so the server closes the connection.
  10818. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10819. auto start = std::chrono::steady_clock::now();
  10820. svr.stop();
  10821. listen_thread.join();
  10822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10823. std::chrono::steady_clock::now() - start)
  10824. .count();
  10825. EXPECT_LT(elapsed, 3000);
  10826. }
  10827. #endif
  10828. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10829. protected:
  10830. ServerTestWithAI_PASSIVE()
  10831. : cli_(HOST, PORT)
  10832. #ifdef CPPHTTPLIB_SSL_ENABLED
  10833. ,
  10834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10835. #endif
  10836. {
  10837. #ifdef CPPHTTPLIB_SSL_ENABLED
  10838. cli_.enable_server_certificate_verification(false);
  10839. #endif
  10840. }
  10841. virtual void SetUp() {
  10842. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10843. res.set_content("Hello World!", "text/plain");
  10844. });
  10845. t_ = thread(
  10846. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10847. svr_.wait_until_ready();
  10848. }
  10849. virtual void TearDown() {
  10850. svr_.stop();
  10851. t_.join();
  10852. }
  10853. #ifdef CPPHTTPLIB_SSL_ENABLED
  10854. SSLClient cli_;
  10855. SSLServer svr_;
  10856. #else
  10857. Client cli_;
  10858. Server svr_;
  10859. #endif
  10860. thread t_;
  10861. };
  10862. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10863. auto res = cli_.Get("/hi");
  10864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10865. EXPECT_EQ(StatusCode::OK_200, res->status);
  10866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10867. EXPECT_EQ("Hello World!", res->body);
  10868. }
  10869. class ServerUpDownTest : public ::testing::Test {
  10870. protected:
  10871. ServerUpDownTest() : cli_(HOST, PORT) {}
  10872. virtual void SetUp() {
  10873. t_ = thread([&]() {
  10874. svr_.bind_to_any_port(HOST);
  10875. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10876. ASSERT_TRUE(svr_.listen_after_bind());
  10877. });
  10878. svr_.wait_until_ready();
  10879. }
  10880. virtual void TearDown() {
  10881. svr_.stop();
  10882. t_.join();
  10883. }
  10884. Client cli_;
  10885. Server svr_;
  10886. thread t_;
  10887. };
  10888. TEST_F(ServerUpDownTest, QuickStartStop) {
  10889. // Should not crash, especially when run with
  10890. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10891. }
  10892. class PayloadMaxLengthTest : public ::testing::Test {
  10893. protected:
  10894. PayloadMaxLengthTest()
  10895. : cli_(HOST, PORT)
  10896. #ifdef CPPHTTPLIB_SSL_ENABLED
  10897. ,
  10898. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10899. #endif
  10900. {
  10901. #ifdef CPPHTTPLIB_SSL_ENABLED
  10902. cli_.enable_server_certificate_verification(false);
  10903. #endif
  10904. }
  10905. virtual void SetUp() {
  10906. svr_.set_payload_max_length(8);
  10907. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10908. res.set_content("test", "text/plain");
  10909. });
  10910. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10911. svr_.wait_until_ready();
  10912. }
  10913. virtual void TearDown() {
  10914. svr_.stop();
  10915. t_.join();
  10916. }
  10917. #ifdef CPPHTTPLIB_SSL_ENABLED
  10918. SSLClient cli_;
  10919. SSLServer svr_;
  10920. #else
  10921. Client cli_;
  10922. Server svr_;
  10923. #endif
  10924. thread t_;
  10925. };
  10926. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10927. auto res = cli_.Post("/test", "123456789", "text/plain");
  10928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10929. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10930. res = cli_.Post("/test", "12345678", "text/plain");
  10931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10932. EXPECT_EQ(StatusCode::OK_200, res->status);
  10933. }
  10934. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10935. // Test chunked encoding with payload exceeding the 8-byte limit
  10936. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10937. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10939. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10940. }
  10941. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10942. // Test chunked encoding with payload within the 8-byte limit
  10943. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10944. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10946. EXPECT_EQ(StatusCode::OK_200, res->status);
  10947. }
  10948. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10949. // Test using send_request to send chunked data exceeding payload limit
  10950. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10951. "Host: " +
  10952. std::string(HOST) + ":" + std::to_string(PORT) +
  10953. "\r\n"
  10954. "Transfer-Encoding: chunked\r\n"
  10955. "Connection: close\r\n"
  10956. "\r\n"
  10957. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10958. "0123456789\r\n"
  10959. "0\r\n" // End chunk
  10960. "\r\n";
  10961. std::string response;
  10962. bool result = send_request(1, chunked_request, &response);
  10963. if (!result) {
  10964. // If send_request fails, it might be because the server closed the
  10965. // connection due to payload limit enforcement, which is acceptable
  10966. SUCCEED()
  10967. << "Server rejected oversized chunked request (connection closed)";
  10968. } else {
  10969. // If we got a response, check if it's an error response or connection was
  10970. // closed early Short response length indicates connection was closed due to
  10971. // payload limit
  10972. if (response.length() <= 10) {
  10973. SUCCEED() << "Server closed connection for oversized chunked request";
  10974. } else {
  10975. // Check for error status codes
  10976. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10977. response.find("Payload Too Large") != std::string::npos ||
  10978. response.find("400") != std::string::npos);
  10979. }
  10980. }
  10981. }
  10982. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10983. // Test request without Content-Length header exceeding payload limit
  10984. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10985. "Host: " +
  10986. std::string(HOST) + ":" +
  10987. std::to_string(PORT) +
  10988. "\r\n"
  10989. "Connection: close\r\n"
  10990. "\r\n";
  10991. // Add payload exceeding the 8-byte limit
  10992. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10993. request_without_content_length += large_payload;
  10994. std::string response;
  10995. bool result = send_request(1, request_without_content_length, &response);
  10996. if (!result) {
  10997. // If send_request fails, server likely closed connection due to payload
  10998. // limit
  10999. SUCCEED() << "Server rejected oversized request without Content-Length "
  11000. "(connection closed)";
  11001. } else {
  11002. // Check if server responded with error or closed connection early
  11003. if (response.length() <= 10) {
  11004. SUCCEED() << "Server closed connection for oversized request without "
  11005. "Content-Length";
  11006. } else {
  11007. // Check for error status codes
  11008. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11009. response.find("Payload Too Large") != std::string::npos ||
  11010. response.find("400") != std::string::npos);
  11011. }
  11012. }
  11013. }
  11014. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11015. // Test request without Content-Length header within payload limit
  11016. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11017. "Host: " +
  11018. std::string(HOST) + ":" +
  11019. std::to_string(PORT) +
  11020. "\r\n"
  11021. "Connection: close\r\n"
  11022. "\r\n";
  11023. // Add payload within the 8-byte limit
  11024. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11025. request_without_content_length += small_payload;
  11026. std::string response;
  11027. bool result = send_request(1, request_without_content_length, &response);
  11028. // For requests without Content-Length, the server may have different behavior
  11029. // The key is that it should not reject due to payload limit for small
  11030. // payloads
  11031. if (result) {
  11032. // Check for any HTTP response (success or error, but not connection closed)
  11033. if (response.length() > 10) {
  11034. SUCCEED()
  11035. << "Server processed request without Content-Length within limit";
  11036. } else {
  11037. // Short response might indicate connection closed, which is acceptable
  11038. SUCCEED() << "Server closed connection for request without "
  11039. "Content-Length (acceptable behavior)";
  11040. }
  11041. } else {
  11042. // Connection failure might be due to protocol requirements
  11043. SUCCEED() << "Connection issue with request without Content-Length "
  11044. "(environment-specific)";
  11045. }
  11046. }
  11047. class LargePayloadMaxLengthTest : public ::testing::Test {
  11048. protected:
  11049. LargePayloadMaxLengthTest()
  11050. : cli_(HOST, PORT)
  11051. #ifdef CPPHTTPLIB_SSL_ENABLED
  11052. ,
  11053. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11054. #endif
  11055. {
  11056. #ifdef CPPHTTPLIB_SSL_ENABLED
  11057. cli_.enable_server_certificate_verification(false);
  11058. #endif
  11059. }
  11060. virtual void SetUp() {
  11061. // Set 10MB payload limit
  11062. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11063. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11064. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11065. res.set_content("Large payload test", "text/plain");
  11066. });
  11067. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11068. svr_.wait_until_ready();
  11069. }
  11070. virtual void TearDown() {
  11071. svr_.stop();
  11072. t_.join();
  11073. }
  11074. #ifdef CPPHTTPLIB_SSL_ENABLED
  11075. SSLClient cli_;
  11076. SSLServer svr_;
  11077. #else
  11078. Client cli_;
  11079. Server svr_;
  11080. #endif
  11081. thread t_;
  11082. };
  11083. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11084. // Test chunked encoding with payload within 10MB limit
  11085. std::string medium_payload(5 * 1024 * 1024,
  11086. 'A'); // 5MB payload, within 10MB limit
  11087. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11089. EXPECT_EQ(StatusCode::OK_200, res->status);
  11090. }
  11091. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11092. // Test chunked encoding with payload exceeding 10MB limit
  11093. std::string large_payload(12 * 1024 * 1024,
  11094. 'B'); // 12MB payload, exceeds 10MB limit
  11095. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11096. // Server may either return 413 or close the connection
  11097. if (res) {
  11098. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11099. } else {
  11100. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11101. }
  11102. }
  11103. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11104. // Test request without Content-Length header within 10MB limit
  11105. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11106. "Host: " +
  11107. std::string(HOST) + ":" +
  11108. std::to_string(PORT) +
  11109. "\r\n"
  11110. "Connection: close\r\n"
  11111. "\r\n";
  11112. // Add 1MB payload (within 10MB limit)
  11113. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11114. request_without_content_length += medium_payload;
  11115. std::string response;
  11116. bool result = send_request(5, request_without_content_length, &response);
  11117. if (result) {
  11118. // Should get a proper HTTP response for payloads within limit
  11119. if (response.length() > 10) {
  11120. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11121. "10MB limit";
  11122. } else {
  11123. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11124. "Content-Length)";
  11125. }
  11126. } else {
  11127. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11128. }
  11129. }
  11130. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11131. // Test request without Content-Length header exceeding 10MB limit
  11132. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11133. "Host: " +
  11134. std::string(HOST) + ":" +
  11135. std::to_string(PORT) +
  11136. "\r\n"
  11137. "Connection: close\r\n"
  11138. "\r\n";
  11139. // Add 12MB payload (exceeds 10MB limit)
  11140. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11141. request_without_content_length += large_payload;
  11142. std::string response;
  11143. bool result = send_request(10, request_without_content_length, &response);
  11144. if (!result) {
  11145. // Server should close connection due to payload limit
  11146. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11147. "(connection closed)";
  11148. } else {
  11149. // Check for error response
  11150. if (response.length() <= 10) {
  11151. SUCCEED()
  11152. << "Server closed connection for 12MB request exceeding 10MB limit";
  11153. } else {
  11154. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11155. response.find("Payload Too Large") != std::string::npos ||
  11156. response.find("400") != std::string::npos);
  11157. }
  11158. }
  11159. }
  11160. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11161. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11162. // path.
  11163. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11164. Server svr;
  11165. const size_t LIMIT = 64 * 1024; // 64KB
  11166. svr.set_payload_max_length(LIMIT);
  11167. size_t total = 0;
  11168. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11169. const ContentReader &content_reader) {
  11170. content_reader([&](const char * /*data*/, size_t len) {
  11171. total += len;
  11172. return true;
  11173. });
  11174. res.status = 200;
  11175. res.set_content("stream_ok", "text/plain");
  11176. });
  11177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11178. auto se = detail::scope_exit([&] {
  11179. svr.stop();
  11180. thread.join();
  11181. ASSERT_FALSE(svr.is_running());
  11182. });
  11183. svr.wait_until_ready();
  11184. // Prepare 256KB raw data and gzip-compress it
  11185. std::string raw(256 * 1024, 'A');
  11186. std::string gz;
  11187. {
  11188. z_stream zs{};
  11189. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11190. Z_DEFAULT_STRATEGY);
  11191. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11192. zs.avail_in = static_cast<uInt>(raw.size());
  11193. char outbuf[4096];
  11194. int ret;
  11195. do {
  11196. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11197. zs.avail_out = sizeof(outbuf);
  11198. ret = deflate(&zs, Z_FINISH);
  11199. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11200. } while (ret != Z_STREAM_END);
  11201. deflateEnd(&zs);
  11202. }
  11203. Client cli(HOST, PORT);
  11204. cli.set_connection_timeout(std::chrono::seconds(5));
  11205. Headers headers = {{"Content-Encoding", "gzip"}};
  11206. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11207. "application/octet-stream");
  11208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11209. // Server must reject oversized decompressed payloads with 413.
  11210. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11211. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11212. EXPECT_LE(total, LIMIT);
  11213. }
  11214. #ifndef CPPHTTPLIB_SSL_ENABLED
  11215. // For a request with neither Content-Length nor Transfer-Encoding, the
  11216. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11217. // compressed wire bytes straight to the ContentReader without ever routing
  11218. // them through the decompressor, so payload_max_length_ only bounded the
  11219. // compressed size on the wire, not the decompressed size.
  11220. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11221. Server svr;
  11222. const size_t LIMIT = 64 * 1024; // 64KB
  11223. svr.set_payload_max_length(LIMIT);
  11224. size_t total = 0;
  11225. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11226. const ContentReader &content_reader) {
  11227. content_reader([&](const char * /*data*/, size_t len) {
  11228. total += len;
  11229. return true;
  11230. });
  11231. res.status = 200;
  11232. res.set_content("stream_ok", "text/plain");
  11233. });
  11234. auto port = svr.bind_to_any_port(HOST);
  11235. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11236. auto se = detail::scope_exit([&] {
  11237. svr.stop();
  11238. thread.join();
  11239. ASSERT_FALSE(svr.is_running());
  11240. });
  11241. svr.wait_until_ready();
  11242. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11243. // StreamingGzipDecompression test above.
  11244. std::string raw(256 * 1024, 'A');
  11245. std::string gz;
  11246. {
  11247. httplib::detail::gzip_compressor compressor;
  11248. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11249. [&](const char *chunk, size_t len) {
  11250. gz.append(chunk, len);
  11251. return true;
  11252. });
  11253. ASSERT_TRUE(result);
  11254. }
  11255. // Send the gzip body over raw TCP with neither Content-Length nor
  11256. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11257. // kicks in.
  11258. std::string req = "POST /stream HTTP/1.1\r\n"
  11259. "Host: " +
  11260. std::string(HOST) + ":" + std::to_string(port) +
  11261. "\r\n"
  11262. "Content-Encoding: gzip\r\n"
  11263. "Connection: close\r\n"
  11264. "\r\n" +
  11265. gz;
  11266. std::string response;
  11267. ASSERT_TRUE(send_request(5, req, &response, port));
  11268. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11269. EXPECT_LE(total, LIMIT);
  11270. }
  11271. #endif
  11272. #endif
  11273. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11274. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11275. // the payload must be passed through untouched instead of being rejected.
  11276. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11277. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11278. Server svr;
  11279. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11280. res.set_content(body, "image/jpeg");
  11281. res.set_header("Content-Encoding", "UTF-8");
  11282. });
  11283. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11284. res.set_content(body, "image/jpeg");
  11285. res.set_header("Content-Encoding", "identity");
  11286. });
  11287. svr.Post("/echo", [](const Request &req, Response &res) {
  11288. res.set_content(req.body, "image/jpeg");
  11289. });
  11290. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11291. auto se = detail::scope_exit([&] {
  11292. svr.stop();
  11293. t.join();
  11294. ASSERT_FALSE(svr.is_running());
  11295. });
  11296. svr.wait_until_ready();
  11297. Client cli(HOST, PORT);
  11298. {
  11299. auto res = cli.Get("/image");
  11300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11301. EXPECT_EQ(StatusCode::OK_200, res->status);
  11302. EXPECT_EQ(body, res->body);
  11303. }
  11304. {
  11305. auto res = cli.Get("/identity");
  11306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11307. EXPECT_EQ(StatusCode::OK_200, res->status);
  11308. EXPECT_EQ(body, res->body);
  11309. }
  11310. {
  11311. // The same applies to a request body reaching the server.
  11312. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11313. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::OK_200, res->status);
  11316. EXPECT_EQ(body, res->body);
  11317. }
  11318. }
  11319. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11320. // gzip-encoded response even when the build has no zlib support.
  11321. static const char GZIPPED_HELLO_WORLD[] = {
  11322. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11323. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11324. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11325. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11326. // A content coding is a whole token, not something the field value merely
  11327. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11328. // as "fibre" look like Brotli, and turned a multi-coding value like
  11329. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11330. // it was never meant to see.
  11331. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11332. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11333. Server svr;
  11334. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11335. res.set_content(body, "image/jpeg");
  11336. res.set_header("Content-Encoding", "fibre");
  11337. });
  11338. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11339. res.set_content(body, "image/jpeg");
  11340. res.set_header("Content-Encoding", "gzip, br");
  11341. });
  11342. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11343. res.set_content(body, "image/jpeg");
  11344. res.set_header("Content-Encoding", "x-zstd-ish");
  11345. });
  11346. auto port = svr.bind_to_any_port(HOST);
  11347. thread t = thread([&]() { svr.listen_after_bind(); });
  11348. auto se = detail::scope_exit([&] {
  11349. svr.stop();
  11350. t.join();
  11351. ASSERT_FALSE(svr.is_running());
  11352. });
  11353. svr.wait_until_ready();
  11354. Client cli(HOST, port);
  11355. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11356. auto res = cli.Get(path);
  11357. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11358. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11359. // Not a coding we recognize, so the payload comes back untouched
  11360. EXPECT_EQ(body, res->body) << path;
  11361. }
  11362. }
  11363. // A content coding cpp-httplib recognizes but was not built with must be
  11364. // reported as such. Handing the still-compressed payload back to the caller
  11365. // would silently corrupt it.
  11366. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11367. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11368. Server svr;
  11369. // "image/jpeg" keeps the server from applying a content coding of its own,
  11370. // so the hand-crafted Content-Encoding below survives.
  11371. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11372. res.set_content(gzipped, "image/jpeg");
  11373. res.set_header("Content-Encoding", "gzip");
  11374. });
  11375. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11376. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11377. res.set_content(gzipped, "image/jpeg");
  11378. res.set_header("Content-Encoding", "GZIP");
  11379. });
  11380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. t.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli(HOST, PORT);
  11388. {
  11389. auto res = cli.Get("/gzipped");
  11390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11392. EXPECT_EQ("Hello World!", res->body);
  11393. #else
  11394. ASSERT_FALSE(res);
  11395. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11396. #endif
  11397. }
  11398. {
  11399. // open_stream() must behave the same way.
  11400. auto handle = cli.open_stream("GET", "/gzipped");
  11401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11402. ASSERT_TRUE(handle.is_valid());
  11403. std::string received;
  11404. char buf[256];
  11405. ssize_t n;
  11406. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11407. received.append(buf, static_cast<size_t>(n));
  11408. }
  11409. EXPECT_EQ("Hello World!", received);
  11410. #else
  11411. EXPECT_FALSE(handle.is_valid());
  11412. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11413. #endif
  11414. }
  11415. {
  11416. // A differently-cased coding must not be mistaken for an unknown one, or
  11417. // the body would be handed back still compressed.
  11418. auto res = cli.Get("/gzipped-uppercase");
  11419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11421. EXPECT_EQ("Hello World!", res->body);
  11422. #else
  11423. ASSERT_FALSE(res);
  11424. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11425. #endif
  11426. }
  11427. }
  11428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11429. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11430. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11431. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11432. // body a second time and appending a second Content-Encoding field line, so
  11433. // clients that decode one coding per listed value handed back raw gzip bytes.
  11434. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11435. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11436. Server svr;
  11437. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11438. // keeps the server from applying a coding of its own.
  11439. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11440. res.set_content(gzipped, "text/plain");
  11441. res.set_header("Content-Encoding", "gzip");
  11442. });
  11443. auto port = svr.bind_to_any_port(HOST);
  11444. thread t = thread([&]() { svr.listen_after_bind(); });
  11445. auto se = detail::scope_exit([&] {
  11446. svr.stop();
  11447. t.join();
  11448. ASSERT_FALSE(svr.is_running());
  11449. });
  11450. svr.wait_until_ready();
  11451. Client cli(HOST, port);
  11452. Headers headers = {{"Accept-Encoding", "gzip"}};
  11453. auto res = cli.Get("/pre-gzipped", headers);
  11454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11455. EXPECT_EQ(StatusCode::OK_200, res->status);
  11456. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11457. EXPECT_EQ("Hello World!", res->body);
  11458. }
  11459. // A chunked provider settles its coding where the headers are written and
  11460. // reuses it at write time. Both ends of that have to hold: a handler's own
  11461. // Content-Encoding suppresses the coding, and a response without one is still
  11462. // compressed as it always was.
  11463. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11464. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11465. const std::string plain = "Hello World! Hello World! Hello World!";
  11466. Server svr;
  11467. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11468. res.set_header("Content-Encoding", "gzip");
  11469. res.set_chunked_content_provider(
  11470. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11471. sink.write(gzipped.data(), gzipped.size());
  11472. sink.done();
  11473. return true;
  11474. });
  11475. });
  11476. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11477. res.set_chunked_content_provider(
  11478. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11479. sink.write(plain.data(), plain.size());
  11480. sink.done();
  11481. return true;
  11482. });
  11483. });
  11484. auto port = svr.bind_to_any_port(HOST);
  11485. thread t = thread([&]() { svr.listen_after_bind(); });
  11486. auto se = detail::scope_exit([&] {
  11487. svr.stop();
  11488. t.join();
  11489. ASSERT_FALSE(svr.is_running());
  11490. });
  11491. svr.wait_until_ready();
  11492. Client cli(HOST, port);
  11493. Headers headers = {{"Accept-Encoding", "gzip"}};
  11494. {
  11495. auto res = cli.Get("/pre-gzipped", headers);
  11496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::OK_200, res->status);
  11498. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11499. EXPECT_EQ("Hello World!", res->body);
  11500. }
  11501. {
  11502. auto res = cli.Get("/negotiated", headers);
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. EXPECT_EQ(StatusCode::OK_200, res->status);
  11505. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11506. EXPECT_EQ(plain, res->body);
  11507. }
  11508. }
  11509. #endif
  11510. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11511. // the same message as the comma-joined one, so both have to be read the same
  11512. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11513. // single gzip coding, and a body the sender says was encoded twice was handed
  11514. // back after one pass, still compressed but presented as decoded.
  11515. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11516. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11517. Server svr;
  11518. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11519. res.set_content(body, "image/jpeg");
  11520. res.headers.emplace("Content-Encoding", "gzip");
  11521. res.headers.emplace("Content-Encoding", "gzip");
  11522. });
  11523. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11524. res.set_content(body, "image/jpeg");
  11525. res.set_header("Content-Encoding", "gzip, gzip");
  11526. });
  11527. auto port = svr.bind_to_any_port(HOST);
  11528. thread t = thread([&]() { svr.listen_after_bind(); });
  11529. auto se = detail::scope_exit([&] {
  11530. svr.stop();
  11531. t.join();
  11532. ASSERT_FALSE(svr.is_running());
  11533. });
  11534. svr.wait_until_ready();
  11535. Client cli(HOST, port);
  11536. // Two codings is not something cpp-httplib decodes, so both representations
  11537. // take the pass-through path rather than one of them being gunzipped once.
  11538. for (const char *path : {"/split", "/joined"}) {
  11539. auto res = cli.Get(path);
  11540. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11541. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11542. EXPECT_EQ(body, res->body) << path;
  11543. }
  11544. }
  11545. // Regression test for DoS vulnerability: a malicious server sending a response
  11546. // without Content-Length header must not cause unbounded memory consumption on
  11547. // the client side. The client should stop reading after a reasonable limit,
  11548. // similar to the server-side set_payload_max_length protection.
  11549. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11550. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11551. #ifndef _WIN32
  11552. signal(SIGPIPE, SIG_IGN);
  11553. #endif
  11554. auto server_thread = std::thread([] {
  11555. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11556. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11557. default_socket_options(srv);
  11558. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11559. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11560. sockaddr_in addr{};
  11561. addr.sin_family = AF_INET;
  11562. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11563. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11564. int opt = 1;
  11565. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11566. #ifdef _WIN32
  11567. reinterpret_cast<const char *>(&opt),
  11568. #else
  11569. &opt,
  11570. #endif
  11571. sizeof(opt));
  11572. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11573. ::listen(srv, 1);
  11574. sockaddr_in cli_addr{};
  11575. socklen_t cli_len = sizeof(cli_addr);
  11576. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11577. if (cli != INVALID_SOCKET) {
  11578. char buf[4096];
  11579. ::recv(cli, buf, sizeof(buf), 0);
  11580. // Malicious response: no Content-Length, no chunked encoding
  11581. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11582. "Connection: close\r\n"
  11583. "\r\n";
  11584. ::send(cli,
  11585. #ifdef _WIN32
  11586. static_cast<const char *>(response_header.c_str()),
  11587. static_cast<int>(response_header.size()),
  11588. #else
  11589. response_header.c_str(), response_header.size(),
  11590. #endif
  11591. 0);
  11592. // Send 10MB of data
  11593. std::string chunk(64 * 1024, 'A');
  11594. size_t total_sent = 0;
  11595. while (total_sent < MALICIOUS_DATA_SIZE) {
  11596. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11597. auto sent = ::send(cli,
  11598. #ifdef _WIN32
  11599. static_cast<const char *>(chunk.c_str()),
  11600. static_cast<int>(to_send),
  11601. #else
  11602. chunk.c_str(), to_send,
  11603. #endif
  11604. 0);
  11605. if (sent <= 0) break;
  11606. total_sent += static_cast<size_t>(sent);
  11607. }
  11608. detail::close_socket(cli);
  11609. }
  11610. detail::close_socket(srv);
  11611. });
  11612. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11613. size_t total_read = 0;
  11614. {
  11615. Client cli("127.0.0.1", PORT + 2);
  11616. cli.set_read_timeout(5, 0);
  11617. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11618. auto stream = cli.open_stream("GET", "/malicious");
  11619. ASSERT_TRUE(stream.is_valid());
  11620. char buffer[64 * 1024];
  11621. ssize_t n;
  11622. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11623. total_read += static_cast<size_t>(n);
  11624. }
  11625. } // StreamHandle and Client destroyed here, closing the socket
  11626. server_thread.join();
  11627. // With set_payload_max_length, the client must stop reading before consuming
  11628. // all 10MB. The read loop should be cut off at or near the configured limit.
  11629. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11630. << "Client read " << total_read << " bytes, exceeding the configured "
  11631. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11632. }
  11633. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11634. // the entire response body without truncation.
  11635. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11636. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11637. #ifndef _WIN32
  11638. signal(SIGPIPE, SIG_IGN);
  11639. #endif
  11640. auto server_thread = std::thread([] {
  11641. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11642. default_socket_options(srv);
  11643. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11644. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11645. sockaddr_in addr{};
  11646. addr.sin_family = AF_INET;
  11647. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11648. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11649. int opt = 1;
  11650. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11651. #ifdef _WIN32
  11652. reinterpret_cast<const char *>(&opt),
  11653. #else
  11654. &opt,
  11655. #endif
  11656. sizeof(opt));
  11657. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11658. ::listen(srv, 1);
  11659. sockaddr_in cli_addr{};
  11660. socklen_t cli_len = sizeof(cli_addr);
  11661. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11662. if (cli != INVALID_SOCKET) {
  11663. char buf[4096];
  11664. ::recv(cli, buf, sizeof(buf), 0);
  11665. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11666. "Connection: close\r\n"
  11667. "\r\n";
  11668. ::send(cli,
  11669. #ifdef _WIN32
  11670. static_cast<const char *>(response_header.c_str()),
  11671. static_cast<int>(response_header.size()),
  11672. #else
  11673. response_header.c_str(), response_header.size(),
  11674. #endif
  11675. 0);
  11676. std::string chunk(64 * 1024, 'A');
  11677. size_t total_sent = 0;
  11678. while (total_sent < DATA_SIZE) {
  11679. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11680. auto sent = ::send(cli,
  11681. #ifdef _WIN32
  11682. static_cast<const char *>(chunk.c_str()),
  11683. static_cast<int>(to_send),
  11684. #else
  11685. chunk.c_str(), to_send,
  11686. #endif
  11687. 0);
  11688. if (sent <= 0) break;
  11689. total_sent += static_cast<size_t>(sent);
  11690. }
  11691. #ifdef _WIN32
  11692. ::shutdown(cli, SD_SEND);
  11693. #else
  11694. ::shutdown(cli, SHUT_WR);
  11695. #endif
  11696. // Drain until the client closes its end, ensuring all data is delivered
  11697. char drain[1024];
  11698. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11699. detail::close_socket(cli);
  11700. }
  11701. detail::close_socket(srv);
  11702. });
  11703. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11704. size_t total_read = 0;
  11705. {
  11706. Client cli("127.0.0.1", PORT + 2);
  11707. cli.set_read_timeout(5, 0);
  11708. cli.set_payload_max_length(0); // 0 means no limit
  11709. auto stream = cli.open_stream("GET", "/data");
  11710. ASSERT_TRUE(stream.is_valid());
  11711. char buffer[64 * 1024];
  11712. ssize_t n;
  11713. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11714. total_read += static_cast<size_t>(n);
  11715. }
  11716. }
  11717. server_thread.join();
  11718. EXPECT_EQ(total_read, DATA_SIZE)
  11719. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11720. << " bytes without truncation, but only read " << total_read << " bytes.";
  11721. }
  11722. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11723. // enormous Content-Length must not cause the client to pre-allocate a huge
  11724. // response body buffer. The reservation is capped at payload_max_length_, and
  11725. // the read itself fails when the body exceeds the limit.
  11726. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11727. #ifndef _WIN32
  11728. signal(SIGPIPE, SIG_IGN);
  11729. #endif
  11730. auto server_thread = std::thread([] {
  11731. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11732. default_socket_options(srv);
  11733. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11734. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11735. sockaddr_in addr{};
  11736. addr.sin_family = AF_INET;
  11737. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11738. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11739. int opt = 1;
  11740. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11741. #ifdef _WIN32
  11742. reinterpret_cast<const char *>(&opt),
  11743. #else
  11744. &opt,
  11745. #endif
  11746. sizeof(opt));
  11747. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11748. ::listen(srv, 1);
  11749. sockaddr_in cli_addr{};
  11750. socklen_t cli_len = sizeof(cli_addr);
  11751. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11752. if (cli != INVALID_SOCKET) {
  11753. char buf[4096];
  11754. ::recv(cli, buf, sizeof(buf), 0);
  11755. // Malicious response: claim a 20GB body but send only a tiny payload.
  11756. std::string response = "HTTP/1.1 200 OK\r\n"
  11757. "Content-Length: 20000000000\r\n"
  11758. "\r\n"
  11759. "abc";
  11760. ::send(cli,
  11761. #ifdef _WIN32
  11762. static_cast<const char *>(response.c_str()),
  11763. static_cast<int>(response.size()),
  11764. #else
  11765. response.c_str(), response.size(),
  11766. #endif
  11767. 0);
  11768. detail::close_socket(cli);
  11769. }
  11770. detail::close_socket(srv);
  11771. });
  11772. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11773. {
  11774. Client cli("127.0.0.1", PORT + 2);
  11775. cli.set_read_timeout(5, 0);
  11776. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11777. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11778. // (server claims more bytes than payload_max_length permits), but it must
  11779. // not exhaust memory before getting there.
  11780. auto res = cli.Get("/malicious");
  11781. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11782. }
  11783. server_thread.join();
  11784. }
  11785. // Verify that content_receiver bypasses the default payload_max_length,
  11786. // allowing streaming downloads larger than 100MB without requiring an explicit
  11787. // set_payload_max_length call.
  11788. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11789. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11790. #ifndef _WIN32
  11791. signal(SIGPIPE, SIG_IGN);
  11792. #endif
  11793. auto server_thread = std::thread([] {
  11794. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11795. default_socket_options(srv);
  11796. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11797. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11798. sockaddr_in addr{};
  11799. addr.sin_family = AF_INET;
  11800. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11801. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11802. int opt = 1;
  11803. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11804. #ifdef _WIN32
  11805. reinterpret_cast<const char *>(&opt),
  11806. #else
  11807. &opt,
  11808. #endif
  11809. sizeof(opt));
  11810. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11811. ::listen(srv, 1);
  11812. sockaddr_in cli_addr{};
  11813. socklen_t cli_len = sizeof(cli_addr);
  11814. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11815. if (cli != INVALID_SOCKET) {
  11816. char buf[4096];
  11817. ::recv(cli, buf, sizeof(buf), 0);
  11818. // Response with Content-Length larger than default 100MB limit
  11819. auto content_length = std::to_string(DATA_SIZE);
  11820. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11821. "Content-Length: " +
  11822. content_length +
  11823. "\r\n"
  11824. "Connection: close\r\n"
  11825. "\r\n";
  11826. ::send(cli,
  11827. #ifdef _WIN32
  11828. static_cast<const char *>(response_header.c_str()),
  11829. static_cast<int>(response_header.size()),
  11830. #else
  11831. response_header.c_str(), response_header.size(),
  11832. #endif
  11833. 0);
  11834. std::string chunk(64 * 1024, 'A');
  11835. size_t total_sent = 0;
  11836. while (total_sent < DATA_SIZE) {
  11837. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11838. auto sent = ::send(cli,
  11839. #ifdef _WIN32
  11840. static_cast<const char *>(chunk.c_str()),
  11841. static_cast<int>(to_send),
  11842. #else
  11843. chunk.c_str(), to_send,
  11844. #endif
  11845. 0);
  11846. if (sent <= 0) break;
  11847. total_sent += static_cast<size_t>(sent);
  11848. }
  11849. detail::close_socket(cli);
  11850. }
  11851. detail::close_socket(srv);
  11852. });
  11853. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11854. size_t total_received = 0;
  11855. {
  11856. Client cli("127.0.0.1", PORT + 2);
  11857. cli.set_read_timeout(10, 0);
  11858. // Do NOT call set_payload_max_length — use the default 100MB limit
  11859. auto res =
  11860. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11861. total_received += data_length;
  11862. return true;
  11863. });
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. }
  11867. server_thread.join();
  11868. EXPECT_EQ(total_received, DATA_SIZE)
  11869. << "With content_receiver, the client should read all " << DATA_SIZE
  11870. << " bytes despite the default 100MB payload_max_length, but only read "
  11871. << total_received << " bytes.";
  11872. }
  11873. // Verify that an explicit set_payload_max_length smaller than the response is
  11874. // enforced even when a content_receiver is used.
  11875. TEST(ClientVulnerabilityTest,
  11876. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11877. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11878. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11879. #ifndef _WIN32
  11880. signal(SIGPIPE, SIG_IGN);
  11881. #endif
  11882. auto server_thread = std::thread([] {
  11883. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11884. default_socket_options(srv);
  11885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11887. sockaddr_in addr{};
  11888. addr.sin_family = AF_INET;
  11889. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11890. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11891. int opt = 1;
  11892. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11893. #ifdef _WIN32
  11894. reinterpret_cast<const char *>(&opt),
  11895. #else
  11896. &opt,
  11897. #endif
  11898. sizeof(opt));
  11899. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11900. ::listen(srv, 1);
  11901. sockaddr_in cli_addr{};
  11902. socklen_t cli_len = sizeof(cli_addr);
  11903. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11904. if (cli != INVALID_SOCKET) {
  11905. char buf[4096];
  11906. ::recv(cli, buf, sizeof(buf), 0);
  11907. auto content_length = std::to_string(DATA_SIZE);
  11908. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11909. "Content-Length: " +
  11910. content_length +
  11911. "\r\n"
  11912. "Connection: close\r\n"
  11913. "\r\n";
  11914. ::send(cli,
  11915. #ifdef _WIN32
  11916. static_cast<const char *>(response_header.c_str()),
  11917. static_cast<int>(response_header.size()),
  11918. #else
  11919. response_header.c_str(), response_header.size(),
  11920. #endif
  11921. 0);
  11922. std::string chunk(64 * 1024, 'A');
  11923. size_t total_sent = 0;
  11924. while (total_sent < DATA_SIZE) {
  11925. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11926. auto sent = ::send(cli,
  11927. #ifdef _WIN32
  11928. static_cast<const char *>(chunk.c_str()),
  11929. static_cast<int>(to_send),
  11930. #else
  11931. chunk.c_str(), to_send,
  11932. #endif
  11933. 0);
  11934. if (sent <= 0) break;
  11935. total_sent += static_cast<size_t>(sent);
  11936. }
  11937. detail::close_socket(cli);
  11938. }
  11939. detail::close_socket(srv);
  11940. });
  11941. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11942. size_t total_received = 0;
  11943. {
  11944. Client cli("127.0.0.1", PORT + 2);
  11945. cli.set_read_timeout(10, 0);
  11946. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11947. auto res =
  11948. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11949. total_received += data_length;
  11950. return true;
  11951. });
  11952. // Should fail because 200MB exceeds the explicit 150MB limit
  11953. EXPECT_FALSE(res);
  11954. }
  11955. server_thread.join();
  11956. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11957. << "Client with content_receiver should respect the explicit "
  11958. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11959. << total_received << " bytes.";
  11960. }
  11961. // Verify that an explicit set_payload_max_length larger than the response
  11962. // allows the content_receiver to read all data successfully.
  11963. TEST(ClientVulnerabilityTest,
  11964. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11965. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11966. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11967. #ifndef _WIN32
  11968. signal(SIGPIPE, SIG_IGN);
  11969. #endif
  11970. auto server_thread = std::thread([] {
  11971. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11972. default_socket_options(srv);
  11973. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11974. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11975. sockaddr_in addr{};
  11976. addr.sin_family = AF_INET;
  11977. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11978. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11979. int opt = 1;
  11980. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11981. #ifdef _WIN32
  11982. reinterpret_cast<const char *>(&opt),
  11983. #else
  11984. &opt,
  11985. #endif
  11986. sizeof(opt));
  11987. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11988. ::listen(srv, 1);
  11989. sockaddr_in cli_addr{};
  11990. socklen_t cli_len = sizeof(cli_addr);
  11991. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11992. if (cli != INVALID_SOCKET) {
  11993. char buf[4096];
  11994. ::recv(cli, buf, sizeof(buf), 0);
  11995. auto content_length = std::to_string(DATA_SIZE);
  11996. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11997. "Content-Length: " +
  11998. content_length +
  11999. "\r\n"
  12000. "Connection: close\r\n"
  12001. "\r\n";
  12002. ::send(cli,
  12003. #ifdef _WIN32
  12004. static_cast<const char *>(response_header.c_str()),
  12005. static_cast<int>(response_header.size()),
  12006. #else
  12007. response_header.c_str(), response_header.size(),
  12008. #endif
  12009. 0);
  12010. std::string chunk(64 * 1024, 'A');
  12011. size_t total_sent = 0;
  12012. while (total_sent < DATA_SIZE) {
  12013. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12014. auto sent = ::send(cli,
  12015. #ifdef _WIN32
  12016. static_cast<const char *>(chunk.c_str()),
  12017. static_cast<int>(to_send),
  12018. #else
  12019. chunk.c_str(), to_send,
  12020. #endif
  12021. 0);
  12022. if (sent <= 0) break;
  12023. total_sent += static_cast<size_t>(sent);
  12024. }
  12025. #ifdef _WIN32
  12026. ::shutdown(cli, SD_SEND);
  12027. #else
  12028. ::shutdown(cli, SHUT_WR);
  12029. #endif
  12030. char drain[1024];
  12031. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12032. detail::close_socket(cli);
  12033. }
  12034. detail::close_socket(srv);
  12035. });
  12036. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12037. size_t total_received = 0;
  12038. {
  12039. Client cli("127.0.0.1", PORT + 2);
  12040. cli.set_read_timeout(10, 0);
  12041. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12042. auto res =
  12043. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12044. total_received += data_length;
  12045. return true;
  12046. });
  12047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12048. EXPECT_EQ(StatusCode::OK_200, res->status);
  12049. }
  12050. server_thread.join();
  12051. EXPECT_EQ(total_received, DATA_SIZE)
  12052. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12053. << " bytes (larger than " << DATA_SIZE
  12054. << " bytes response), content_receiver should read all data, but only "
  12055. "read "
  12056. << total_received << " bytes.";
  12057. }
  12058. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12059. // Regression test for "zip bomb" attack on the client side: a malicious server
  12060. // sends a small gzip-compressed response that decompresses to a huge payload.
  12061. // The client must enforce payload_max_length on the decompressed size.
  12062. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12063. constexpr size_t DECOMPRESSED_SIZE =
  12064. 10 * 1024 * 1024; // 10MB after decompression
  12065. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12066. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12067. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12068. std::string compressed;
  12069. {
  12070. httplib::detail::gzip_compressor compressor;
  12071. bool ok =
  12072. compressor.compress(uncompressed.data(), uncompressed.size(),
  12073. /*last=*/true, [&](const char *buf, size_t len) {
  12074. compressed.append(buf, len);
  12075. return true;
  12076. });
  12077. ASSERT_TRUE(ok);
  12078. }
  12079. // Sanity: compressed data should be much smaller than the decompressed size
  12080. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12081. #ifndef _WIN32
  12082. signal(SIGPIPE, SIG_IGN);
  12083. #endif
  12084. // Set up the listening socket in the main thread so the server is guaranteed
  12085. // to be ready before the client connects (eliminates race condition).
  12086. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12087. default_socket_options(srv);
  12088. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12089. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12090. sockaddr_in addr{};
  12091. addr.sin_family = AF_INET;
  12092. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12093. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12094. int opt = 1;
  12095. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12096. #ifdef _WIN32
  12097. reinterpret_cast<const char *>(&opt),
  12098. #else
  12099. &opt,
  12100. #endif
  12101. sizeof(opt));
  12102. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12103. ASSERT_EQ(0, ::listen(srv, 1));
  12104. auto server_thread = std::thread([&compressed, srv] {
  12105. sockaddr_in cli_addr{};
  12106. socklen_t cli_len = sizeof(cli_addr);
  12107. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12108. if (cli != INVALID_SOCKET) {
  12109. // Read the full HTTP request (until \r\n\r\n)
  12110. char buf[4096];
  12111. size_t total = 0;
  12112. while (total < sizeof(buf)) {
  12113. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12114. if (n <= 0) break;
  12115. total += static_cast<size_t>(n);
  12116. // Check for end of headers
  12117. if (total >= 4) {
  12118. std::string req(buf, total);
  12119. if (req.find("\r\n\r\n") != std::string::npos) break;
  12120. }
  12121. }
  12122. // Malicious response: gzip-compressed body, no Content-Length
  12123. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12124. "Content-Encoding: gzip\r\n"
  12125. "Connection: close\r\n"
  12126. "\r\n";
  12127. ::send(cli,
  12128. #ifdef _WIN32
  12129. static_cast<const char *>(response_header.c_str()),
  12130. static_cast<int>(response_header.size()),
  12131. #else
  12132. response_header.c_str(), response_header.size(),
  12133. #endif
  12134. 0);
  12135. // Send the compressed payload (small on the wire, huge when decompressed)
  12136. size_t total_sent = 0;
  12137. while (total_sent < compressed.size()) {
  12138. auto to_send = std::min(compressed.size() - total_sent,
  12139. static_cast<size_t>(64 * 1024));
  12140. auto sent =
  12141. ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(compressed.c_str() + total_sent),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. compressed.c_str() + total_sent, to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. detail::close_socket(cli);
  12153. }
  12154. });
  12155. auto se = detail::scope_exit([&] {
  12156. detail::close_socket(srv);
  12157. server_thread.join();
  12158. });
  12159. size_t total_decompressed = 0;
  12160. {
  12161. Client cli("127.0.0.1", PORT + 3);
  12162. cli.set_read_timeout(5, 0);
  12163. cli.set_decompress(true);
  12164. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12165. auto stream = cli.open_stream("GET", "/zipbomb");
  12166. ASSERT_TRUE(stream.is_valid());
  12167. char buffer[64 * 1024];
  12168. ssize_t n;
  12169. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12170. total_decompressed += static_cast<size_t>(n);
  12171. }
  12172. }
  12173. // The decompressed size must be capped by payload_max_length. Without
  12174. // protection, the client would decompress the full 10MB from a tiny
  12175. // compressed payload, enabling a zip bomb DoS attack.
  12176. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12177. << "Client decompressed " << total_decompressed
  12178. << " bytes from a gzip response. The decompressed size should be "
  12179. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12180. }
  12181. #endif
  12182. TEST(HostAndPortPropertiesTest, NoSSL) {
  12183. httplib::Client cli("www.google.com", 1234);
  12184. ASSERT_EQ("www.google.com", cli.host());
  12185. ASSERT_EQ(1234, cli.port());
  12186. }
  12187. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12188. httplib::Client cli("www.google.com:1234");
  12189. ASSERT_EQ("www.google.com", cli.host());
  12190. ASSERT_EQ(1234, cli.port());
  12191. }
  12192. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12193. // Port number that overflows int — should not crash, client becomes invalid
  12194. httplib::Client cli("http://www.google.com:99999999999999999999");
  12195. ASSERT_FALSE(cli.is_valid());
  12196. }
  12197. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12198. // Port 99999 exceeds valid range (1-65535) — should not crash
  12199. httplib::Client cli("http://www.google.com:99999");
  12200. ASSERT_FALSE(cli.is_valid());
  12201. }
  12202. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12203. httplib::Client cli("http://www.google.com:80abc");
  12204. ASSERT_FALSE(cli.is_valid());
  12205. }
  12206. #ifdef CPPHTTPLIB_SSL_ENABLED
  12207. TEST(HostAndPortPropertiesTest, SSL) {
  12208. httplib::SSLClient cli("www.google.com");
  12209. ASSERT_EQ("www.google.com", cli.host());
  12210. ASSERT_EQ(443, cli.port());
  12211. }
  12212. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12213. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12214. std::string cert;
  12215. read_file(CA_CERT_FILE, cert);
  12216. httplib::SSLClient httplib_client("www.google.com");
  12217. // Load CA store first time
  12218. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12219. // Load CA store second time (update)
  12220. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12221. // Verify client is still valid and can make connections
  12222. httplib_client.enable_server_certificate_verification(true);
  12223. auto res = httplib_client.Get("/");
  12224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12225. // Google may return 200 or 301 depending on various factors
  12226. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12227. res->status == StatusCode::MovedPermanently_301);
  12228. }
  12229. TEST(SSLClientTest, ServerNameIndication_Online) {
  12230. auto host = "httpbingo.org";
  12231. auto path = std::string{"/get"};
  12232. SSLClient cli(host, 443);
  12233. auto res = cli.Get(path);
  12234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12235. ASSERT_EQ(StatusCode::OK_200, res->status);
  12236. }
  12237. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12238. // Use a site that will cause SSL verification failure due to self-signed cert
  12239. SSLClient cli("self-signed.badssl.com", 443);
  12240. cli.enable_server_certificate_verification(true);
  12241. auto res = cli.Get("/");
  12242. ASSERT_TRUE(!res);
  12243. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12244. // Verify backend error is captured for SSLServerVerification
  12245. // This occurs when certificate verification fails
  12246. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12247. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12248. EXPECT_NE(0UL, res.ssl_backend_error());
  12249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12250. // For OpenSSL, ssl_error is 0 for verification errors
  12251. EXPECT_EQ(0, res.ssl_error());
  12252. #if !defined(_WIN32) || \
  12253. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12254. // On non-Windows or when Windows Schannel is disabled, the error comes
  12255. // from OpenSSL's verification
  12256. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12257. res.ssl_backend_error());
  12258. #endif
  12259. #endif
  12260. }
  12261. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12262. // Use a site where hostname doesn't match the certificate
  12263. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12264. SSLClient cli("wrong.host.badssl.com", 443);
  12265. cli.enable_server_certificate_verification(true);
  12266. cli.enable_server_hostname_verification(true);
  12267. auto res = cli.Get("/");
  12268. ASSERT_TRUE(!res);
  12269. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12270. // Verify backend error is captured for hostname verification failure
  12271. EXPECT_NE(0UL, res.ssl_backend_error());
  12272. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12273. // For OpenSSL, ssl_error is 0 for verification errors
  12274. EXPECT_EQ(0, res.ssl_error());
  12275. #if !defined(_WIN32) || \
  12276. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12277. // On non-Windows or when Windows Schannel is disabled, the error comes
  12278. // from OpenSSL's hostname verification
  12279. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12280. res.ssl_backend_error());
  12281. #endif
  12282. #endif
  12283. }
  12284. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12285. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12286. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12287. SSLClient cli("www.google.com", 443);
  12288. cli.enable_server_certificate_verification(true);
  12289. auto res = cli.Get("/");
  12290. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12291. }
  12292. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12293. SSLClient cli("www.google.com", 443);
  12294. cli.enable_server_certificate_verification(true);
  12295. cli.enable_windows_certificate_verification(false);
  12296. auto res = cli.Get("/");
  12297. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12298. }
  12299. // The server sends an intermediate cross-signed by a root Windows trusts,
  12300. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12301. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12302. SSLClient cli("accounts.spotify.com", 443);
  12303. auto res = cli.Get("/");
  12304. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12305. << " ssl_backend_error=" << res.ssl_backend_error();
  12306. }
  12307. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12308. // policy status, which no backend reports for a self-signed certificate.
  12309. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12310. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12311. ASSERT_TRUE(svr.is_valid());
  12312. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12313. auto se = detail::scope_exit([&] {
  12314. svr.stop();
  12315. t.join();
  12316. ASSERT_FALSE(svr.is_running());
  12317. });
  12318. svr.wait_until_ready();
  12319. SSLClient cli("127.0.0.1", PORT);
  12320. cli.set_connection_timeout(30);
  12321. auto res = cli.Get("/");
  12322. ASSERT_FALSE(res);
  12323. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12324. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12325. }
  12326. #endif
  12327. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12328. Client cli("https://google.com");
  12329. auto res = cli.Get("/");
  12330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12331. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12332. }
  12333. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12334. SSLClient cli("google.com");
  12335. cli.set_ca_cert_path(CA_CERT_FILE);
  12336. auto res = cli.Get("/");
  12337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12338. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12339. }
  12340. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12341. SSLClient cli("google.com");
  12342. cli.enable_server_certificate_verification(true);
  12343. cli.set_ca_cert_path("hello");
  12344. auto res = cli.Get("/");
  12345. ASSERT_TRUE(!res);
  12346. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12347. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12348. // should be set
  12349. EXPECT_EQ(0, res.ssl_error());
  12350. // Verify backend error is captured for SSLLoadingCerts
  12351. // This error occurs when loading CA certificates fails
  12352. EXPECT_NE(0UL, res.ssl_backend_error());
  12353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12354. // OpenSSL specific error codes:
  12355. // > openssl errstr 0x80000002
  12356. // error:80000002:system library::No such file or directory
  12357. // > openssl errstr 0xA000126
  12358. // error:0A000126:SSL routines::unexpected eof while reading
  12359. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12360. res.ssl_backend_error() == 0xA000126);
  12361. #endif
  12362. }
  12363. TEST(SSLClientTest, ServerCertificateVerification4) {
  12364. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12365. ASSERT_TRUE(svr.is_valid());
  12366. svr.Get("/test", [&](const Request &, Response &res) {
  12367. res.set_content("test", "text/plain");
  12368. svr.stop();
  12369. ASSERT_TRUE(true);
  12370. });
  12371. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12372. auto se = detail::scope_exit([&] {
  12373. t.join();
  12374. ASSERT_FALSE(svr.is_running());
  12375. });
  12376. svr.wait_until_ready();
  12377. SSLClient cli("127.0.0.1", PORT);
  12378. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12379. cli.enable_server_certificate_verification(true);
  12380. cli.set_connection_timeout(30);
  12381. auto res = cli.Get("/test");
  12382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12383. ASSERT_EQ(StatusCode::OK_200, res->status);
  12384. }
  12385. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12386. std::string cert;
  12387. read_file(CA_CERT_FILE, cert);
  12388. SSLClient cli("google.com");
  12389. cli.load_ca_cert_store(cert.data(), cert.size());
  12390. const auto res = cli.Get("/");
  12391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12392. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12393. }
  12394. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12395. // clang-format off
  12396. static constexpr char cert[] =
  12397. "GlobalSign Root CA\n"
  12398. "==================\n"
  12399. "-----BEGIN CERTIFICATE-----\n"
  12400. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12401. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12402. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12403. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12404. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12405. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12406. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12407. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12408. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12409. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12410. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12411. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12412. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12413. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12414. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12415. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12416. "-----END CERTIFICATE-----\n";
  12417. // clang-format on
  12418. SSLClient cli("google.com");
  12419. cli.load_ca_cert_store(cert, sizeof(cert));
  12420. const auto res = cli.Get("/");
  12421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12422. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12423. }
  12424. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12425. SSLClient cli("www.youtube.com");
  12426. cli.set_ca_cert_path(CA_CERT_FILE);
  12427. cli.enable_server_certificate_verification(true);
  12428. cli.set_follow_location(true);
  12429. auto res = cli.Get("/");
  12430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12431. ASSERT_EQ(StatusCode::OK_200, res->status);
  12432. }
  12433. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12434. SSLClient cli("wWw.YouTube.Com");
  12435. cli.set_ca_cert_path(CA_CERT_FILE);
  12436. cli.enable_server_certificate_verification(true);
  12437. cli.enable_server_hostname_verification(true);
  12438. cli.set_follow_location(true);
  12439. auto res = cli.Get("/");
  12440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12441. ASSERT_EQ(StatusCode::OK_200, res->status);
  12442. }
  12443. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12444. SSLClient cli("gOoGlE.COm");
  12445. cli.enable_server_certificate_verification(true);
  12446. cli.enable_server_hostname_verification(true);
  12447. cli.set_follow_location(true);
  12448. auto res = cli.Get("/");
  12449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12450. ASSERT_EQ(StatusCode::OK_200, res->status);
  12451. }
  12452. TEST(SSLClientTest, Issue2004_Online) {
  12453. Client client("https://google.com");
  12454. client.set_follow_location(true);
  12455. auto res = client.Get("/");
  12456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12457. ASSERT_EQ(StatusCode::OK_200, res->status);
  12458. auto body = res->body;
  12459. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12460. }
  12461. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12462. // Create SSLClient with invalid cert/key to make is_valid() return false
  12463. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12464. "nonexistent_key.pem");
  12465. // is_valid() should be false due to cert loading failure
  12466. ASSERT_FALSE(cli.is_valid());
  12467. auto res = cli.Get("/");
  12468. ASSERT_FALSE(res);
  12469. EXPECT_EQ(Error::SSLConnection, res.error());
  12470. }
  12471. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12472. // Test for Issue #2251: SSL error not properly reported when client cert
  12473. // and key paths are swapped or mismatched
  12474. // This simulates the scenario where user accidentally swaps the cert and key
  12475. // files
  12476. // Using client cert file as private key and vice versa (completely wrong)
  12477. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12478. // Should fail validation due to cert/key mismatch
  12479. ASSERT_FALSE(cli.is_valid());
  12480. // Attempt to make a request should fail with proper error
  12481. auto res = cli.Get("/");
  12482. ASSERT_FALSE(res);
  12483. EXPECT_EQ(Error::SSLConnection, res.error());
  12484. // SSL error should be recorded in the Result object (this is the key fix for
  12485. // Issue #2251)
  12486. auto backend_error = res.ssl_backend_error();
  12487. EXPECT_NE(0u, backend_error);
  12488. }
  12489. // Tests cert/key mismatch detection at the TLS context level
  12490. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12491. // Test that using mismatched cert/key causes connection failure.
  12492. // We verify this at the SSLClient level rather than through internal
  12493. // TLS API functions.
  12494. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12495. cli.enable_server_certificate_verification(false);
  12496. cli.set_connection_timeout(2);
  12497. // The mismatch should cause a connection or handshake error
  12498. auto res = cli.Get("/test");
  12499. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12500. // Either way, the request should fail
  12501. EXPECT_FALSE(res);
  12502. }
  12503. #endif
  12504. #if 0
  12505. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12506. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12507. ASSERT_TRUE(cli != nullptr);
  12508. cli->set_address_family(AF_INET6);
  12509. cli->set_interface("en0");
  12510. auto res = cli->Get("/get");
  12511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12512. ASSERT_EQ(StatusCode::OK_200, res->status);
  12513. }
  12514. #endif
  12515. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12516. #ifdef CPPHTTPLIB_SSL_ENABLED
  12517. void ClientCertPresent(
  12518. const std::string &client_cert_file,
  12519. const std::string &client_private_key_file,
  12520. const std::string &client_encrypted_private_key_pass = std::string()) {
  12521. using namespace httplib::tls;
  12522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12523. CLIENT_CA_CERT_DIR);
  12524. ASSERT_TRUE(svr.is_valid());
  12525. svr.Get("/test", [&](const Request &req, Response &res) {
  12526. res.set_content("test", "text/plain");
  12527. auto cert = req.peer_cert();
  12528. ASSERT_TRUE(static_cast<bool>(cert));
  12529. std::string common_name = cert.subject_cn();
  12530. EXPECT_EQ("Common Name", common_name);
  12531. });
  12532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12533. auto se = detail::scope_exit([&] {
  12534. svr.stop();
  12535. t.join();
  12536. ASSERT_FALSE(svr.is_running());
  12537. });
  12538. svr.wait_until_ready();
  12539. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12540. client_encrypted_private_key_pass);
  12541. cli.enable_server_certificate_verification(false);
  12542. cli.set_connection_timeout(30);
  12543. auto res = cli.Get("/test");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. ASSERT_EQ(StatusCode::OK_200, res->status);
  12546. }
  12547. TEST(SSLClientServerTest, ClientCertPresent) {
  12548. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12549. }
  12550. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12551. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12552. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12553. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12554. }
  12555. // PEM memory-based constructor tests (works with all TLS backends)
  12556. void PemMemoryClientCertPresent(
  12557. const std::string &client_cert_file,
  12558. const std::string &client_private_key_file,
  12559. const std::string &client_encrypted_private_key_pass = std::string()) {
  12560. // Read PEM files into memory
  12561. std::string server_cert_pem, server_key_pem;
  12562. std::string client_ca_pem;
  12563. std::string client_cert_pem, client_key_pem;
  12564. read_file(SERVER_CERT_FILE, server_cert_pem);
  12565. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12566. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12567. read_file(client_cert_file, client_cert_pem);
  12568. read_file(client_private_key_file, client_key_pem);
  12569. // Create server with PEM memory
  12570. SSLServer::PemMemory server_pem = {
  12571. server_cert_pem.c_str(),
  12572. server_cert_pem.size(),
  12573. server_key_pem.c_str(),
  12574. server_key_pem.size(),
  12575. client_ca_pem.c_str(),
  12576. client_ca_pem.size(),
  12577. nullptr // no password for server key
  12578. };
  12579. SSLServer svr(server_pem);
  12580. ASSERT_TRUE(svr.is_valid());
  12581. svr.Get("/test", [&](const Request &, Response &res) {
  12582. res.set_content("test", "text/plain");
  12583. });
  12584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12585. auto se = detail::scope_exit([&] {
  12586. svr.stop();
  12587. t.join();
  12588. ASSERT_FALSE(svr.is_running());
  12589. });
  12590. svr.wait_until_ready();
  12591. // Create client with PEM memory
  12592. const char *password = client_encrypted_private_key_pass.empty()
  12593. ? nullptr
  12594. : client_encrypted_private_key_pass.c_str();
  12595. SSLClient::PemMemory client_pem = {
  12596. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12597. client_key_pem.size(), password};
  12598. SSLClient cli(HOST, PORT, client_pem);
  12599. cli.enable_server_certificate_verification(false);
  12600. cli.set_connection_timeout(30);
  12601. auto res = cli.Get("/test");
  12602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12603. ASSERT_EQ(StatusCode::OK_200, res->status);
  12604. }
  12605. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12606. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12607. }
  12608. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12609. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12610. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12611. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12612. }
  12613. TEST(SSLClientServerTest, ClientCertMissing) {
  12614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12615. CLIENT_CA_CERT_DIR);
  12616. ASSERT_TRUE(svr.is_valid());
  12617. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12618. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12619. auto se = detail::scope_exit([&] {
  12620. svr.stop();
  12621. t.join();
  12622. ASSERT_FALSE(svr.is_running());
  12623. });
  12624. svr.wait_until_ready();
  12625. SSLClient cli(HOST, PORT);
  12626. cli.set_connection_timeout(30);
  12627. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12628. // the chain check on Windows, so the result does not depend on the order.
  12629. cli.enable_server_hostname_verification(false);
  12630. auto res = cli.Get("/test");
  12631. ASSERT_TRUE(!res);
  12632. // When client cert is missing and server requires it, connection fails
  12633. // Error type depends on backend implementation
  12634. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12635. res.error() == Error::SSLConnection);
  12636. // Verify backend error is captured
  12637. // Note: This test may have different error codes depending on the exact
  12638. // verification failure
  12639. EXPECT_NE(0UL, res.ssl_backend_error());
  12640. }
  12641. TEST(SSLClientServerTest, TrustDirOptional) {
  12642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12643. ASSERT_TRUE(svr.is_valid());
  12644. svr.Get("/test", [&](const Request &, Response &res) {
  12645. res.set_content("test", "text/plain");
  12646. });
  12647. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12648. auto se = detail::scope_exit([&] {
  12649. svr.stop();
  12650. t.join();
  12651. ASSERT_FALSE(svr.is_running());
  12652. });
  12653. svr.wait_until_ready();
  12654. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12655. cli.enable_server_certificate_verification(false);
  12656. cli.set_connection_timeout(30);
  12657. auto res = cli.Get("/test");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. ASSERT_EQ(StatusCode::OK_200, res->status);
  12660. }
  12661. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12662. class NoListenSSLServer : public SSLServer {
  12663. public:
  12664. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12665. const char *client_ca_cert_file_path,
  12666. const char *client_ca_cert_dir_path = nullptr)
  12667. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12668. client_ca_cert_dir_path),
  12669. stop_(false) {}
  12670. std::atomic_bool stop_;
  12671. private:
  12672. bool process_and_close_socket(socket_t /*sock*/) override {
  12673. // Don't create SSL context
  12674. while (!stop_.load()) {
  12675. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12676. }
  12677. return true;
  12678. }
  12679. };
  12680. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12681. CLIENT_CA_CERT_FILE);
  12682. ASSERT_TRUE(svr.is_valid());
  12683. svr.Get("/test", [&](const Request &, Response &res) {
  12684. res.set_content("test", "text/plain");
  12685. });
  12686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop_ = true;
  12689. svr.stop();
  12690. t.join();
  12691. ASSERT_FALSE(svr.is_running());
  12692. });
  12693. svr.wait_until_ready();
  12694. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12695. cli.enable_server_certificate_verification(false);
  12696. cli.set_connection_timeout(1);
  12697. auto res = cli.Get("/test");
  12698. ASSERT_TRUE(!res);
  12699. EXPECT_EQ(Error::SSLConnection, res.error());
  12700. // Timeout results in WantRead error code (maps to backend-specific value)
  12701. EXPECT_NE(0, res.ssl_error());
  12702. }
  12703. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12704. // Test SSLServer with client certificate verification using the standard
  12705. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12707. CLIENT_CA_CERT_DIR);
  12708. ASSERT_TRUE(svr.is_valid());
  12709. svr.Get("/test", [&](const Request &req, Response &res) {
  12710. res.set_content("test", "text/plain");
  12711. auto cert = req.peer_cert();
  12712. ASSERT_TRUE(static_cast<bool>(cert));
  12713. auto common_name = cert.subject_cn();
  12714. EXPECT_EQ("Common Name", common_name);
  12715. });
  12716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12717. auto se = detail::scope_exit([&] {
  12718. svr.stop();
  12719. t.join();
  12720. ASSERT_FALSE(svr.is_running());
  12721. });
  12722. svr.wait_until_ready();
  12723. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12724. cli.enable_server_certificate_verification(false);
  12725. cli.set_connection_timeout(30);
  12726. auto res = cli.Get("/test");
  12727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12728. ASSERT_EQ(StatusCode::OK_200, res->status);
  12729. }
  12730. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12731. // Verifies that wildcard matching and exact matching work consistently
  12732. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12733. using namespace httplib::tls;
  12734. // We need a running server to test against
  12735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12736. ASSERT_TRUE(svr.is_valid());
  12737. svr.Get("/test", [](const Request &, Response &res) {
  12738. res.set_content("ok", "text/plain");
  12739. });
  12740. thread t([&]() { svr.listen(HOST, PORT); });
  12741. auto se = detail::scope_exit([&] {
  12742. svr.stop();
  12743. t.join();
  12744. });
  12745. svr.wait_until_ready();
  12746. bool verify_callback_called = false;
  12747. bool verify_result_wrong = false;
  12748. SSLClient cli(HOST, PORT);
  12749. cli.enable_server_certificate_verification(true);
  12750. cli.set_ca_cert_path(CA_CERT_FILE);
  12751. cli.set_connection_timeout(5);
  12752. // Note: Test certificate has CN="Common Name", not "localhost"
  12753. bool verify_result_cn = false;
  12754. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12755. verify_callback_called = true;
  12756. if (!ctx.cert) return false;
  12757. // Test 1: "Common Name" should match (our test server cert CN)
  12758. verify_result_cn = ctx.check_hostname("Common Name");
  12759. // Test 2: wrong hostname should not match
  12760. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12761. return true; // Accept for the purpose of this test
  12762. });
  12763. auto res = cli.Get("/test");
  12764. // The request may succeed or fail depending on cert configuration
  12765. // but the callback should have been called
  12766. ASSERT_TRUE(verify_callback_called)
  12767. << "Verify callback should have been called";
  12768. // CN="Common Name" should match our test certificate
  12769. //
  12770. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12771. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12772. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12773. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12774. // <openssl/base.h>, which is included transitively when
  12775. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12776. #if defined(OPENSSL_IS_BORINGSSL)
  12777. EXPECT_FALSE(verify_result_cn)
  12778. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12779. #else
  12780. EXPECT_TRUE(verify_result_cn)
  12781. << "verify_hostname should match 'Common Name' (certificate CN)";
  12782. #endif
  12783. // Wrong hostname should not match
  12784. EXPECT_FALSE(verify_result_wrong)
  12785. << "verify_hostname should not match 'wronghost.example.com'";
  12786. }
  12787. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12788. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12789. // X509_check_ip behavior and must hold for every backend.
  12790. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12791. using namespace httplib::tls;
  12792. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12793. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12794. ASSERT_TRUE(svr.is_valid());
  12795. svr.Get("/test", [](const Request &, Response &res) {
  12796. res.set_content("ok", "text/plain");
  12797. });
  12798. thread t([&]() { svr.listen(HOST, PORT); });
  12799. auto se = detail::scope_exit([&] {
  12800. svr.stop();
  12801. t.join();
  12802. });
  12803. svr.wait_until_ready();
  12804. bool verify_callback_called = false;
  12805. bool ip_matched_via_cn = true;
  12806. SSLClient cli(HOST, PORT);
  12807. cli.enable_server_certificate_verification(true);
  12808. cli.set_ca_cert_path(CA_CERT_FILE);
  12809. cli.set_connection_timeout(5);
  12810. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12811. verify_callback_called = true;
  12812. if (!ctx.cert) return false;
  12813. // The IP appears only in the CN, so it must NOT be accepted.
  12814. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12815. return true; // Accept for the purpose of this test
  12816. });
  12817. cli.Get("/test");
  12818. ASSERT_TRUE(verify_callback_called)
  12819. << "Verify callback should have been called";
  12820. EXPECT_FALSE(ip_matched_via_cn)
  12821. << "An IP host must not be authenticated via the certificate CN";
  12822. }
  12823. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12824. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12825. using namespace httplib::tls;
  12826. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12827. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12828. ASSERT_TRUE(svr.is_valid());
  12829. svr.Get("/test", [](const Request &, Response &res) {
  12830. res.set_content("ok", "text/plain");
  12831. });
  12832. thread t([&]() { svr.listen(HOST, PORT); });
  12833. auto se = detail::scope_exit([&] {
  12834. svr.stop();
  12835. t.join();
  12836. });
  12837. svr.wait_until_ready();
  12838. bool verify_callback_called = false;
  12839. bool san_matched = false;
  12840. bool wrong_ipv6_matched = true;
  12841. bool cn_ipv6_matched = true;
  12842. SSLClient cli(HOST, PORT);
  12843. cli.enable_server_certificate_verification(true);
  12844. cli.set_ca_cert_path(CA_CERT_FILE);
  12845. cli.set_connection_timeout(5);
  12846. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12847. verify_callback_called = true;
  12848. if (!ctx.cert) return false;
  12849. // Matches the IPv6 iPAddress SAN.
  12850. san_matched = ctx.check_hostname("2001:db8::1");
  12851. // A different IPv6 address must not match.
  12852. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12853. // "::1" lives only in the CN, so it must not be accepted.
  12854. cn_ipv6_matched = ctx.check_hostname("::1");
  12855. return true; // Accept for the purpose of this test
  12856. });
  12857. cli.Get("/test");
  12858. ASSERT_TRUE(verify_callback_called)
  12859. << "Verify callback should have been called";
  12860. EXPECT_TRUE(san_matched)
  12861. << "verify_hostname should match an IPv6 iPAddress SAN";
  12862. EXPECT_FALSE(wrong_ipv6_matched)
  12863. << "verify_hostname should not match a non-matching IPv6 address";
  12864. EXPECT_FALSE(cn_ipv6_matched)
  12865. << "An IPv6 host must not be authenticated via the certificate CN";
  12866. }
  12867. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12868. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12869. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12870. using namespace httplib::tls;
  12871. // SANs: DNS:a.zz, IP:42.46.122.122
  12872. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12873. ASSERT_TRUE(svr.is_valid());
  12874. svr.Get("/test", [](const Request &, Response &res) {
  12875. res.set_content("ok", "text/plain");
  12876. });
  12877. auto port = svr.bind_to_any_port(HOST);
  12878. thread t([&]() { svr.listen_after_bind(); });
  12879. auto se = detail::scope_exit([&] {
  12880. svr.stop();
  12881. t.join();
  12882. });
  12883. svr.wait_until_ready();
  12884. bool verify_callback_called = false;
  12885. bool dns_san_matched = false;
  12886. bool ip_san_matched = false;
  12887. bool ip_matched_via_dns_san = true;
  12888. bool dns_matched_via_ip_san = true;
  12889. SSLClient cli(HOST, port);
  12890. cli.enable_server_certificate_verification(true);
  12891. cli.set_ca_cert_path(CA_CERT_FILE);
  12892. cli.set_connection_timeout(5);
  12893. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12894. verify_callback_called = true;
  12895. if (!ctx.cert) return false;
  12896. dns_san_matched = ctx.check_hostname("a.zz");
  12897. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12898. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12899. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12900. return true; // Accept for the purpose of this test
  12901. });
  12902. cli.Get("/test");
  12903. ASSERT_TRUE(verify_callback_called)
  12904. << "Verify callback should have been called";
  12905. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12906. EXPECT_TRUE(ip_san_matched)
  12907. << "verify_hostname should match an iPAddress SAN";
  12908. EXPECT_FALSE(ip_matched_via_dns_san)
  12909. << "An IP host must not be authenticated via a dNSName SAN";
  12910. EXPECT_FALSE(dns_matched_via_ip_san)
  12911. << "A DNS host must not be authenticated via an iPAddress SAN";
  12912. }
  12913. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12914. // "www.*.example.test" names one host and not every host under example.test.
  12915. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12916. using namespace httplib::tls;
  12917. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12918. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12919. ASSERT_TRUE(svr.is_valid());
  12920. svr.Get("/test", [](const Request &, Response &res) {
  12921. res.set_content("ok", "text/plain");
  12922. });
  12923. auto port = svr.bind_to_any_port(HOST);
  12924. thread t([&]() { svr.listen_after_bind(); });
  12925. auto se = detail::scope_exit([&] {
  12926. svr.stop();
  12927. t.join();
  12928. });
  12929. svr.wait_until_ready();
  12930. bool verify_callback_called = false;
  12931. bool leftmost_wildcard_matched = false;
  12932. bool wildcard_spanned_labels = true;
  12933. bool inner_wildcard_matched = true;
  12934. SSLClient cli(HOST, port);
  12935. cli.enable_server_certificate_verification(true);
  12936. cli.set_ca_cert_path(CA_CERT_FILE);
  12937. cli.set_connection_timeout(5);
  12938. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12939. verify_callback_called = true;
  12940. if (!ctx.cert) return false;
  12941. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12942. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12943. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12944. return true; // Accept for the purpose of this test
  12945. });
  12946. cli.Get("/test");
  12947. ASSERT_TRUE(verify_callback_called)
  12948. << "Verify callback should have been called";
  12949. EXPECT_TRUE(leftmost_wildcard_matched)
  12950. << "A leftmost wildcard should match a single label";
  12951. EXPECT_FALSE(wildcard_spanned_labels)
  12952. << "A wildcard label must not match more than one label";
  12953. EXPECT_FALSE(inner_wildcard_matched)
  12954. << "A wildcard outside the leftmost label must not be honoured";
  12955. }
  12956. // sans() must report each SAN entry under its own type.
  12957. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12958. using namespace httplib::tls;
  12959. // SANs: DNS:a.zz, IP:42.46.122.122
  12960. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12961. ASSERT_TRUE(svr.is_valid());
  12962. svr.Get("/test", [](const Request &, Response &res) {
  12963. res.set_content("ok", "text/plain");
  12964. });
  12965. auto port = svr.bind_to_any_port(HOST);
  12966. thread t([&]() { svr.listen_after_bind(); });
  12967. auto se = detail::scope_exit([&] {
  12968. svr.stop();
  12969. t.join();
  12970. });
  12971. svr.wait_until_ready();
  12972. bool verify_callback_called = false;
  12973. std::vector<SanEntry> sans;
  12974. SSLClient cli(HOST, port);
  12975. cli.enable_server_certificate_verification(true);
  12976. cli.set_ca_cert_path(CA_CERT_FILE);
  12977. cli.set_connection_timeout(5);
  12978. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12979. verify_callback_called = true;
  12980. if (!ctx.cert) return false;
  12981. sans = ctx.sans();
  12982. return true; // Accept for the purpose of this test
  12983. });
  12984. cli.Get("/test");
  12985. ASSERT_TRUE(verify_callback_called)
  12986. << "Verify callback should have been called";
  12987. auto has_san = [&](SanType type, const std::string &value) {
  12988. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12989. return san.type == type && san.value == value;
  12990. });
  12991. };
  12992. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12993. << "sans() should report the dNSName SAN";
  12994. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12995. << "sans() should report the iPAddress SAN";
  12996. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12997. << "sans() must not report the dNSName SAN as an address";
  12998. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12999. << "sans() must not report the iPAddress SAN as a DNS name";
  13000. }
  13001. #endif
  13002. // mbedTLS-specific callback constructor test
  13003. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13004. #ifdef CPPHTTPLIB_SSL_ENABLED
  13005. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13007. ASSERT_TRUE(svr.is_valid());
  13008. // Set up a handler to verify client certificate is present
  13009. bool client_cert_verified = false;
  13010. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13011. // Verify that client certificate was provided
  13012. client_cert_verified = true;
  13013. res.set_content("success", "text/plain");
  13014. });
  13015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13016. auto se = detail::scope_exit([&] {
  13017. svr.stop();
  13018. t.join();
  13019. ASSERT_FALSE(svr.is_running());
  13020. });
  13021. svr.wait_until_ready();
  13022. // Client with certificate
  13023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13024. cli.enable_server_certificate_verification(false);
  13025. cli.set_connection_timeout(30);
  13026. auto res = cli.Get("/test");
  13027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13028. ASSERT_EQ(StatusCode::OK_200, res->status);
  13029. ASSERT_TRUE(client_cert_verified);
  13030. EXPECT_EQ("success", res->body);
  13031. }
  13032. #endif
  13033. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13034. // backends
  13035. #ifdef CPPHTTPLIB_SSL_ENABLED
  13036. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13037. using namespace httplib::tls;
  13038. // Test that when client CA cert file is provided,
  13039. // the server properly requests and validates client certificates
  13040. // Create a server with client authentication
  13041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13042. ASSERT_TRUE(svr.is_valid());
  13043. bool handler_called = false;
  13044. svr.Get("/test", [&](const Request &req, Response &res) {
  13045. handler_called = true;
  13046. // Verify that a client certificate was provided
  13047. auto cert = req.peer_cert();
  13048. ASSERT_TRUE(static_cast<bool>(cert));
  13049. // Get the issuer name
  13050. std::string issuer_str = cert.issuer_name();
  13051. ASSERT_FALSE(issuer_str.empty());
  13052. // The client certificate should be issued by our test CA
  13053. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13054. res.set_content("authenticated", "text/plain");
  13055. });
  13056. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13057. auto se = detail::scope_exit([&] {
  13058. svr.stop();
  13059. t.join();
  13060. ASSERT_FALSE(svr.is_running());
  13061. });
  13062. svr.wait_until_ready();
  13063. // Connect with a client certificate issued by the CA
  13064. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13065. cli.enable_server_certificate_verification(false);
  13066. cli.set_connection_timeout(30);
  13067. auto res = cli.Get("/test");
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. ASSERT_EQ(StatusCode::OK_200, res->status);
  13070. ASSERT_TRUE(handler_called);
  13071. EXPECT_EQ("authenticated", res->body);
  13072. }
  13073. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13074. using namespace httplib::tls;
  13075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13076. ASSERT_TRUE(svr.is_valid());
  13077. svr.Get("/test", [](const Request &, Response &res) {
  13078. res.set_content("ok", "text/plain");
  13079. });
  13080. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13081. auto se = detail::scope_exit([&] {
  13082. svr.stop();
  13083. t.join();
  13084. });
  13085. svr.wait_until_ready();
  13086. SSLClient cli(HOST, PORT);
  13087. cli.enable_server_certificate_verification(false);
  13088. cli.set_connection_timeout(30);
  13089. bool cert_checked = false;
  13090. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13091. if (ctx.cert) {
  13092. auto sans = ctx.sans();
  13093. // Test certificate may or may not have SANs - just verify the API
  13094. // works If SANs exist, verify the types are valid
  13095. for (const auto &san : sans) {
  13096. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13097. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13098. san.type == SanType::OTHER);
  13099. EXPECT_FALSE(san.value.empty());
  13100. }
  13101. cert_checked = true;
  13102. }
  13103. return true;
  13104. });
  13105. auto res = cli.Get("/test");
  13106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13107. EXPECT_TRUE(cert_checked);
  13108. }
  13109. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13110. using namespace httplib::tls;
  13111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13112. ASSERT_TRUE(svr.is_valid());
  13113. svr.Get("/test", [](const Request &, Response &res) {
  13114. res.set_content("ok", "text/plain");
  13115. });
  13116. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13117. auto se = detail::scope_exit([&] {
  13118. svr.stop();
  13119. t.join();
  13120. });
  13121. svr.wait_until_ready();
  13122. SSLClient cli(HOST, PORT);
  13123. cli.enable_server_certificate_verification(false);
  13124. cli.set_connection_timeout(30);
  13125. bool validity_checked = false;
  13126. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13127. if (ctx.cert) {
  13128. time_t not_before = 0, not_after = 0;
  13129. bool result = ctx.validity(not_before, not_after);
  13130. EXPECT_TRUE(result);
  13131. // Verify that not_before < now < not_after for a valid cert
  13132. time_t now = time(nullptr);
  13133. EXPECT_LT(not_before, now);
  13134. EXPECT_GT(not_after, now);
  13135. validity_checked = true;
  13136. }
  13137. return true;
  13138. });
  13139. auto res = cli.Get("/test");
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. EXPECT_TRUE(validity_checked);
  13142. }
  13143. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13144. using namespace httplib::tls;
  13145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13146. ASSERT_TRUE(svr.is_valid());
  13147. svr.Get("/test", [](const Request &, Response &res) {
  13148. res.set_content("ok", "text/plain");
  13149. });
  13150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13151. auto se = detail::scope_exit([&] {
  13152. svr.stop();
  13153. t.join();
  13154. });
  13155. svr.wait_until_ready();
  13156. SSLClient cli(HOST, PORT);
  13157. cli.enable_server_certificate_verification(false);
  13158. cli.set_connection_timeout(30);
  13159. bool serial_checked = false;
  13160. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13161. if (ctx.cert) {
  13162. std::string serial = ctx.serial();
  13163. EXPECT_FALSE(serial.empty());
  13164. // Serial should be a hex string
  13165. for (char c : serial) {
  13166. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13167. (c >= 'a' && c <= 'f'));
  13168. }
  13169. serial_checked = true;
  13170. }
  13171. return true;
  13172. });
  13173. auto res = cli.Get("/test");
  13174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13175. EXPECT_TRUE(serial_checked);
  13176. }
  13177. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13178. // Test 1: Valid CA file - no error should be recorded
  13179. {
  13180. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13181. CLIENT_CA_CERT_FILE);
  13182. ASSERT_TRUE(svr.is_valid());
  13183. // With valid setup, last_ssl_error should be 0
  13184. EXPECT_EQ(0, svr.ssl_last_error());
  13185. }
  13186. // Test 2: Invalid CA file content
  13187. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13188. {
  13189. // Create a temporary file with completely invalid content
  13190. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13191. {
  13192. std::ofstream ofs(temp_invalid_ca);
  13193. ofs << "This is not a certificate file at all\n";
  13194. ofs << "Just plain text content\n";
  13195. }
  13196. // Create server with invalid CA file
  13197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13198. // Clean up temporary file
  13199. std::remove(temp_invalid_ca);
  13200. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13201. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13202. // Note: SSL_CTX_load_verify_locations typically fails first,
  13203. // but our error handling code path is still exercised
  13204. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13205. }
  13206. }
  13207. TEST(VerifyCallbackTest, VerifyContextFields) {
  13208. using namespace httplib::tls;
  13209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13210. ASSERT_TRUE(svr.is_valid());
  13211. svr.Get("/test", [](const Request &, Response &res) {
  13212. res.set_content("ok", "text/plain");
  13213. });
  13214. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13215. auto se = detail::scope_exit([&] {
  13216. svr.stop();
  13217. t.join();
  13218. });
  13219. svr.wait_until_ready();
  13220. SSLClient cli(HOST, PORT);
  13221. cli.enable_server_certificate_verification(false);
  13222. cli.set_connection_timeout(30);
  13223. int callback_count = 0;
  13224. bool saw_leaf_cert = false;
  13225. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13226. if (ctx.cert) {
  13227. callback_count++;
  13228. // We should see at least one certificate (the leaf)
  13229. std::string cn = ctx.subject_cn();
  13230. if (!cn.empty()) { saw_leaf_cert = true; }
  13231. // Verify context fields are populated
  13232. EXPECT_NE(ctx.session, nullptr);
  13233. EXPECT_GE(ctx.depth, 0);
  13234. }
  13235. return true;
  13236. });
  13237. auto res = cli.Get("/test");
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. EXPECT_GT(callback_count, 0);
  13240. EXPECT_TRUE(saw_leaf_cert);
  13241. }
  13242. // A verifier belongs to the client that set it, not to the thread that set it.
  13243. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13244. using namespace httplib::tls;
  13245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13246. ASSERT_TRUE(svr.is_valid());
  13247. svr.Get("/test", [](const Request &, Response &res) {
  13248. res.set_content("ok", "text/plain");
  13249. });
  13250. auto port = svr.bind_to_any_port(HOST);
  13251. thread t([&]() { svr.listen_after_bind(); });
  13252. auto se = detail::scope_exit([&] {
  13253. svr.stop();
  13254. t.join();
  13255. });
  13256. svr.wait_until_ready();
  13257. auto rejecting_calls = 0;
  13258. SSLClient rejecting(HOST, port);
  13259. rejecting.enable_server_certificate_verification(false);
  13260. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13261. rejecting_calls++;
  13262. return false;
  13263. });
  13264. auto accepting_calls = 0;
  13265. SSLClient accepting(HOST, port);
  13266. accepting.enable_server_certificate_verification(false);
  13267. // Set on another thread than the requests below.
  13268. thread([&]() {
  13269. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13270. accepting_calls++;
  13271. return true;
  13272. });
  13273. }).join();
  13274. // Requested on another thread than the verifier was set on.
  13275. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13276. EXPECT_GT(rejecting_calls, 0);
  13277. auto res = accepting.Get("/test");
  13278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13279. EXPECT_GT(accepting_calls, 0);
  13280. }
  13281. // VerifyContext::session is the same handle the other tls:: functions take.
  13282. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13283. using namespace httplib::tls;
  13284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13285. ASSERT_TRUE(svr.is_valid());
  13286. svr.Get("/test", [](const Request &, Response &res) {
  13287. res.set_content("ok", "text/plain");
  13288. });
  13289. auto port = svr.bind_to_any_port(HOST);
  13290. thread t([&]() { svr.listen_after_bind(); });
  13291. auto se = detail::scope_exit([&] {
  13292. svr.stop();
  13293. t.join();
  13294. });
  13295. svr.wait_until_ready();
  13296. SSLClient cli(HOST, port);
  13297. cli.enable_server_certificate_verification(false);
  13298. session_t verifier_session = nullptr;
  13299. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13300. verifier_session = ctx.session;
  13301. return true;
  13302. });
  13303. session_t session_verifier_session = nullptr;
  13304. cli.set_session_verifier([&](session_t session) {
  13305. session_verifier_session = session;
  13306. return SSLVerifierResponse::NoDecisionMade;
  13307. });
  13308. auto res = cli.Get("/test");
  13309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13310. EXPECT_NE(nullptr, verifier_session);
  13311. EXPECT_EQ(session_verifier_session, verifier_session);
  13312. }
  13313. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13314. using httplib::tls::TlsError;
  13315. // Test that verify_error_to_string returns empty for success
  13316. std::string success_str = TlsError::verify_error_to_string(0);
  13317. EXPECT_TRUE(success_str.empty());
  13318. // Test that verify_error_to_string returns non-empty for error codes
  13319. // Using a common error code (certificate expired)
  13320. std::string error_str =
  13321. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13322. EXPECT_FALSE(error_str.empty());
  13323. }
  13324. TEST(SessionVerifierTest, CertificateAccepted) {
  13325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13326. ASSERT_TRUE(svr.is_valid());
  13327. svr.Get("/test", [](const Request &, Response &res) {
  13328. res.set_content("ok", "text/plain");
  13329. });
  13330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13331. auto se = detail::scope_exit([&] {
  13332. svr.stop();
  13333. t.join();
  13334. });
  13335. svr.wait_until_ready();
  13336. SSLClient cli(HOST, PORT);
  13337. cli.enable_server_certificate_verification(false);
  13338. cli.set_connection_timeout(30);
  13339. bool callback_called = false;
  13340. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13341. EXPECT_NE(session, nullptr);
  13342. callback_called = true;
  13343. return SSLVerifierResponse::CertificateAccepted;
  13344. });
  13345. auto res = cli.Get("/test");
  13346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13347. EXPECT_EQ(200, res->status);
  13348. EXPECT_TRUE(callback_called);
  13349. }
  13350. TEST(SessionVerifierTest, CertificateRejected) {
  13351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13352. ASSERT_TRUE(svr.is_valid());
  13353. svr.Get("/test", [](const Request &, Response &res) {
  13354. res.set_content("ok", "text/plain");
  13355. });
  13356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. t.join();
  13360. });
  13361. svr.wait_until_ready();
  13362. SSLClient cli(HOST, PORT);
  13363. cli.enable_server_certificate_verification(false);
  13364. cli.set_connection_timeout(30);
  13365. bool callback_called = false;
  13366. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13367. EXPECT_NE(session, nullptr);
  13368. callback_called = true;
  13369. return SSLVerifierResponse::CertificateRejected;
  13370. });
  13371. auto res = cli.Get("/test");
  13372. EXPECT_FALSE(res);
  13373. EXPECT_TRUE(callback_called);
  13374. }
  13375. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  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. // NoDecisionMade with verification disabled should succeed (no default check)
  13388. SSLClient cli(HOST, PORT);
  13389. cli.enable_server_certificate_verification(false);
  13390. cli.set_connection_timeout(30);
  13391. bool callback_called = false;
  13392. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13393. EXPECT_NE(session, nullptr);
  13394. callback_called = true;
  13395. return SSLVerifierResponse::NoDecisionMade;
  13396. });
  13397. auto res = cli.Get("/test");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. EXPECT_EQ(200, res->status);
  13400. EXPECT_TRUE(callback_called);
  13401. }
  13402. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13403. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13404. ASSERT_TRUE(svr.is_valid());
  13405. svr.Get("/test", [](const Request &, Response &res) {
  13406. res.set_content("ok", "text/plain");
  13407. });
  13408. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13409. auto se = detail::scope_exit([&] {
  13410. svr.stop();
  13411. t.join();
  13412. });
  13413. svr.wait_until_ready();
  13414. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13415. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13416. // so we only check that the request fails, not whether the callback was
  13417. // called.
  13418. SSLClient cli(HOST, PORT);
  13419. cli.enable_server_certificate_verification(true);
  13420. cli.set_connection_timeout(30);
  13421. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13422. EXPECT_NE(session, nullptr);
  13423. return SSLVerifierResponse::NoDecisionMade;
  13424. });
  13425. auto res = cli.Get("/test");
  13426. EXPECT_FALSE(res);
  13427. }
  13428. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13429. // Test SSL server using PemMemory constructor with client CA certificates
  13430. // Read PEM files
  13431. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13432. read_file(SERVER_CERT_FILE, server_cert_pem);
  13433. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13434. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13435. // Create SSLServer with PemMemory constructor including client CA
  13436. SSLServer::PemMemory server_pem = {
  13437. server_cert_pem.c_str(),
  13438. server_cert_pem.size(),
  13439. server_key_pem.c_str(),
  13440. server_key_pem.size(),
  13441. client_ca_pem.c_str(),
  13442. client_ca_pem.size(),
  13443. nullptr // no password for server key
  13444. };
  13445. SSLServer svr(server_pem);
  13446. ASSERT_TRUE(svr.is_valid());
  13447. // No SSL error should be recorded for valid setup
  13448. EXPECT_EQ(0, svr.ssl_last_error());
  13449. // Set up server endpoints
  13450. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13451. res.set_content("ok", "text/plain");
  13452. });
  13453. // Start server in a thread
  13454. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13455. svr.wait_until_ready();
  13456. // Connect with client certificate (using constructor with paths)
  13457. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13458. cli.enable_server_certificate_verification(false);
  13459. auto res = cli.Get("/test-pem-ca");
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. EXPECT_EQ(200, res->status);
  13462. EXPECT_EQ("ok", res->body);
  13463. svr.stop();
  13464. server_thread.join();
  13465. }
  13466. #endif
  13467. #ifdef _WIN32
  13468. TEST(CleanupTest, WSACleanup) {
  13469. int ret = WSACleanup();
  13470. ASSERT_EQ(0, ret);
  13471. }
  13472. #endif
  13473. #ifndef CPPHTTPLIB_SSL_ENABLED
  13474. TEST(NoSSLSupport, SimpleInterface) {
  13475. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13476. }
  13477. #endif
  13478. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13479. TEST(InvalidScheme, SimpleInterface) {
  13480. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13481. }
  13482. #endif
  13483. TEST(NoScheme, SimpleInterface) {
  13484. Client cli("yahoo.com:80");
  13485. ASSERT_TRUE(cli.is_valid());
  13486. }
  13487. TEST(SendAPI, SimpleInterface_Online) {
  13488. Client cli("http://yahoo.com");
  13489. Request req;
  13490. req.method = "GET";
  13491. req.path = "/";
  13492. auto res = cli.send(req);
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13495. }
  13496. TEST(SendAPI, WithParamsInRequest) {
  13497. Server svr;
  13498. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13499. EXPECT_TRUE(req.has_param("test"));
  13500. EXPECT_EQ("test_value", req.get_param_value("test"));
  13501. });
  13502. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13503. auto se = detail::scope_exit([&] {
  13504. svr.stop();
  13505. t.join();
  13506. ASSERT_FALSE(svr.is_running());
  13507. });
  13508. svr.wait_until_ready();
  13509. Client cli(HOST, PORT);
  13510. {
  13511. Request req;
  13512. req.method = "GET";
  13513. req.path = "/";
  13514. req.params.emplace("test", "test_value");
  13515. auto res = cli.send(req);
  13516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13517. }
  13518. {
  13519. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13521. }
  13522. }
  13523. TEST(ClientImplMethods, GetSocketTest) {
  13524. httplib::Server svr;
  13525. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13526. res.status = StatusCode::OK_200;
  13527. });
  13528. auto port = svr.bind_to_any_port("127.0.0.1");
  13529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13530. auto se = detail::scope_exit([&] {
  13531. svr.stop();
  13532. thread.join();
  13533. ASSERT_FALSE(svr.is_running());
  13534. });
  13535. svr.wait_until_ready();
  13536. {
  13537. httplib::Client cli("127.0.0.1", port);
  13538. cli.set_keep_alive(true);
  13539. // Use the behavior of cpp-httplib of opening the connection
  13540. // only when the first request happens. If that changes,
  13541. // this test would be obsolete.
  13542. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13543. // This also implicitly tests the server. But other tests would fail much
  13544. // earlier than this one to be considered.
  13545. auto res = cli.Get("/");
  13546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13547. EXPECT_EQ(StatusCode::OK_200, res->status);
  13548. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13549. }
  13550. }
  13551. #ifdef CPPHTTPLIB_SSL_ENABLED
  13552. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13553. Client cli("http://yahoo.com");
  13554. auto res = cli.Get("/");
  13555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13556. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13557. cli.set_follow_location(true);
  13558. res = cli.Get("/");
  13559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13560. EXPECT_EQ(StatusCode::OK_200, res->status);
  13561. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13562. }
  13563. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13564. Client cli("https://yahoo.com");
  13565. auto res = cli.Get("/");
  13566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13567. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13568. cli.set_follow_location(true);
  13569. res = cli.Get("/");
  13570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13571. EXPECT_EQ(StatusCode::OK_200, res->status);
  13572. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13573. }
  13574. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13575. Client cli("https://yahoo.com");
  13576. auto res = cli.Get("/");
  13577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13578. ASSERT_FALSE(!res);
  13579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13580. ASSERT_FALSE(res == nullptr);
  13581. ASSERT_TRUE(res != nullptr);
  13582. EXPECT_EQ(Error::Success, res.error());
  13583. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13584. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13585. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13586. cli.set_follow_location(true);
  13587. res = cli.Get("/");
  13588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13589. EXPECT_EQ(Error::Success, res.error());
  13590. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13591. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13592. EXPECT_EQ(StatusCode::OK_200, res->status);
  13593. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13594. }
  13595. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13596. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13597. Client cli("https://cdnjs.cloudflare.com");
  13598. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13599. Headers{{"Accept-Encoding", "br"}});
  13600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13601. EXPECT_EQ(StatusCode::OK_200, res->status);
  13602. EXPECT_EQ(287630U, res->body.size());
  13603. EXPECT_EQ("application/javascript; charset=utf-8",
  13604. res->get_header_value("Content-Type"));
  13605. }
  13606. #endif
  13607. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13608. #undef REDIR_HOST // Silence compiler warning
  13609. #define REDIR_HOST "https://httpbingo.org"
  13610. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13611. Client cli(REDIR_HOST);
  13612. cli.set_follow_location(true);
  13613. auto res =
  13614. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13616. EXPECT_EQ(StatusCode::OK_200, res->status);
  13617. }
  13618. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13619. Client cli(REDIR_HOST);
  13620. cli.set_follow_location(true);
  13621. Params params;
  13622. params.emplace("url", "http://example.com");
  13623. params.emplace("status_code", "302");
  13624. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13626. EXPECT_EQ(StatusCode::OK_200, res->status);
  13627. }
  13628. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13629. Client cli(REDIR_HOST);
  13630. cli.set_follow_location(true);
  13631. Params params;
  13632. params.emplace("url", "http://example.com");
  13633. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13635. EXPECT_EQ(StatusCode::OK_200, res->status);
  13636. }
  13637. TEST(HttpToHttpsRedirectTest, CertFile) {
  13638. auto ssl_port = PORT + 1;
  13639. Server svr;
  13640. ASSERT_TRUE(svr.is_valid());
  13641. svr.Get("/index", [&](const Request &, Response &res) {
  13642. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13643. "/index");
  13644. svr.stop();
  13645. });
  13646. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13647. ASSERT_TRUE(ssl_svr.is_valid());
  13648. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13649. res.set_content("test", "text/plain");
  13650. ssl_svr.stop();
  13651. });
  13652. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13653. thread t2 =
  13654. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13655. auto se = detail::scope_exit([&] {
  13656. t2.join();
  13657. t.join();
  13658. ASSERT_FALSE(svr.is_running());
  13659. });
  13660. svr.wait_until_ready();
  13661. ssl_svr.wait_until_ready();
  13662. Client cli("127.0.0.1", PORT);
  13663. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13664. cli.enable_server_certificate_verification(true);
  13665. cli.set_follow_location(true);
  13666. cli.set_connection_timeout(30);
  13667. auto res = cli.Get("/index");
  13668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13669. ASSERT_EQ(StatusCode::OK_200, res->status);
  13670. }
  13671. TEST(SSLClientRedirectTest, CertFile) {
  13672. auto ssl_port = PORT + 1;
  13673. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13674. ASSERT_TRUE(ssl_svr1.is_valid());
  13675. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13676. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13677. "/index");
  13678. ssl_svr1.stop();
  13679. });
  13680. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13681. ASSERT_TRUE(ssl_svr2.is_valid());
  13682. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13683. res.set_content("test", "text/plain");
  13684. ssl_svr2.stop();
  13685. });
  13686. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13687. thread t2 =
  13688. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13689. auto se = detail::scope_exit([&] {
  13690. t2.join();
  13691. t.join();
  13692. ASSERT_FALSE(ssl_svr1.is_running());
  13693. });
  13694. ssl_svr1.wait_until_ready();
  13695. ssl_svr2.wait_until_ready();
  13696. SSLClient cli("127.0.0.1", PORT);
  13697. std::string cert;
  13698. read_file(SERVER_CERT2_FILE, cert);
  13699. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13700. cli.enable_server_certificate_verification(true);
  13701. cli.set_follow_location(true);
  13702. cli.set_connection_timeout(30);
  13703. auto res = cli.Get("/index");
  13704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13705. ASSERT_EQ(StatusCode::OK_200, res->status);
  13706. }
  13707. #endif
  13708. #ifdef CPPHTTPLIB_SSL_ENABLED
  13709. // Test that set_ca_cert_store() skips system certs (consistent with
  13710. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13711. // should be trusted - system certs should NOT be loaded.
  13712. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13713. // Load a specific cert that is NOT a system CA cert
  13714. std::string cert;
  13715. read_file(SERVER_CERT2_FILE, cert);
  13716. SSLClient cli("google.com");
  13717. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13718. cli.enable_server_certificate_verification(true);
  13719. // This should FAIL because:
  13720. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13721. // 2. System certs should NOT be loaded when custom store is set
  13722. // If system certs WERE loaded, this would succeed
  13723. auto res = cli.Get("/");
  13724. ASSERT_FALSE(res);
  13725. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13726. }
  13727. // Same as above, but through the native store handle path. Regression test:
  13728. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13729. // merged system certs into the user-provided store.
  13730. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13731. std::string cert;
  13732. read_file(SERVER_CERT2_FILE, cert);
  13733. SSLClient cli("google.com");
  13734. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13735. cli.enable_server_certificate_verification(true);
  13736. auto res = cli.Get("/");
  13737. ASSERT_FALSE(res);
  13738. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13739. }
  13740. // A custom store set via the native handle must still verify a server whose
  13741. // cert it does contain.
  13742. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13743. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13744. ASSERT_TRUE(svr.is_valid());
  13745. svr.Get("/test", [&](const Request &, Response &res) {
  13746. res.set_content("test", "text/plain");
  13747. });
  13748. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13749. auto se = detail::scope_exit([&] {
  13750. svr.stop();
  13751. t.join();
  13752. ASSERT_FALSE(svr.is_running());
  13753. });
  13754. svr.wait_until_ready();
  13755. SSLClient cli("127.0.0.1", PORT);
  13756. std::string cert;
  13757. read_file(SERVER_CERT2_FILE, cert);
  13758. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13759. cli.enable_server_certificate_verification(true);
  13760. cli.set_connection_timeout(30);
  13761. auto res = cli.Get("/test");
  13762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13763. ASSERT_EQ(StatusCode::OK_200, res->status);
  13764. }
  13765. // CA certs loaded through the universal Client must be transferred to the
  13766. // client created internally for following an HTTPS redirect. Regression test:
  13767. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13768. // the CA data for redirect transfer.
  13769. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13770. auto ssl_port = PORT + 1;
  13771. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13772. ASSERT_TRUE(ssl_svr1.is_valid());
  13773. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13774. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13775. "/index");
  13776. });
  13777. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13778. ASSERT_TRUE(ssl_svr2.is_valid());
  13779. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13780. res.set_content("test", "text/plain");
  13781. });
  13782. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13783. thread t2 =
  13784. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13785. auto se = detail::scope_exit([&] {
  13786. ssl_svr2.stop();
  13787. ssl_svr1.stop();
  13788. t2.join();
  13789. t.join();
  13790. ASSERT_FALSE(ssl_svr1.is_running());
  13791. });
  13792. ssl_svr1.wait_until_ready();
  13793. ssl_svr2.wait_until_ready();
  13794. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13795. std::string cert;
  13796. read_file(SERVER_CERT2_FILE, cert);
  13797. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13798. cli.enable_server_certificate_verification(true);
  13799. cli.set_follow_location(true);
  13800. cli.set_connection_timeout(30);
  13801. auto res = cli.Get("/index");
  13802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13803. ASSERT_EQ(StatusCode::OK_200, res->status);
  13804. }
  13805. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13806. // so a host signed by a system CA verifies even though a custom CA is set
  13807. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13808. std::string cert;
  13809. read_file(SERVER_CERT2_FILE, cert);
  13810. SSLClient cli("google.com");
  13811. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13812. cli.enable_system_ca(true);
  13813. cli.enable_server_certificate_verification(true);
  13814. auto res = cli.Get("/");
  13815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13816. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13817. }
  13818. // The custom CA remains effective when combined with the system CA
  13819. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13820. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13821. ASSERT_TRUE(svr.is_valid());
  13822. svr.Get("/test", [&](const Request &, Response &res) {
  13823. res.set_content("test", "text/plain");
  13824. });
  13825. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13826. auto se = detail::scope_exit([&] {
  13827. svr.stop();
  13828. t.join();
  13829. ASSERT_FALSE(svr.is_running());
  13830. });
  13831. svr.wait_until_ready();
  13832. SSLClient cli("127.0.0.1", PORT);
  13833. std::string cert;
  13834. read_file(SERVER_CERT2_FILE, cert);
  13835. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13836. cli.enable_system_ca(true);
  13837. cli.enable_server_certificate_verification(true);
  13838. cli.set_connection_timeout(30);
  13839. auto res = cli.Get("/test");
  13840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13841. ASSERT_EQ(StatusCode::OK_200, res->status);
  13842. }
  13843. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13844. // skip chain verification entirely (only the certificate identity was
  13845. // checked), so a server presenting an untrusted certificate with a matching
  13846. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13847. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13848. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13849. ASSERT_TRUE(svr.is_valid());
  13850. svr.Get("/test", [&](const Request &, Response &res) {
  13851. res.set_content("test", "text/plain");
  13852. });
  13853. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13854. auto se = detail::scope_exit([&] {
  13855. svr.stop();
  13856. t.join();
  13857. ASSERT_FALSE(svr.is_running());
  13858. });
  13859. svr.wait_until_ready();
  13860. SSLClient cli("127.0.0.1", PORT);
  13861. std::string cert;
  13862. // A trusted CA that did not sign the server certificate. The server cert
  13863. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13864. // this connection.
  13865. read_file(CLIENT_CA_CERT_FILE, cert);
  13866. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13867. cli.enable_server_certificate_verification(true);
  13868. cli.set_connection_timeout(30);
  13869. auto res = cli.Get("/test");
  13870. ASSERT_FALSE(res);
  13871. }
  13872. // enable_system_ca(false) prevents system CA loading entirely
  13873. TEST(SSLClientTest, DisableSystemCa_Online) {
  13874. SSLClient cli("google.com");
  13875. cli.enable_system_ca(false);
  13876. cli.enable_server_certificate_verification(true);
  13877. auto res = cli.Get("/");
  13878. ASSERT_FALSE(res);
  13879. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13880. // itself when the CA chain is empty
  13881. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13882. res.error() == Error::SSLConnection);
  13883. }
  13884. // The universal Client forwards enable_system_ca()
  13885. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13886. std::string cert;
  13887. read_file(SERVER_CERT2_FILE, cert);
  13888. Client cli("https://google.com");
  13889. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13890. cli.enable_system_ca(true);
  13891. cli.enable_server_certificate_verification(true);
  13892. auto res = cli.Get("/");
  13893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13894. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13895. }
  13896. // The system CA policy must carry over to the client created internally for
  13897. // following a cross-host HTTPS redirect
  13898. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13899. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13900. ASSERT_TRUE(svr.is_valid());
  13901. svr.Get("/index", [&](const Request &, Response &res) {
  13902. res.set_redirect("https://www.google.com/");
  13903. });
  13904. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13905. auto se = detail::scope_exit([&] {
  13906. svr.stop();
  13907. t.join();
  13908. ASSERT_FALSE(svr.is_running());
  13909. });
  13910. svr.wait_until_ready();
  13911. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13912. std::string cert;
  13913. read_file(SERVER_CERT2_FILE, cert);
  13914. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13915. cli.enable_system_ca(true);
  13916. cli.enable_server_certificate_verification(true);
  13917. cli.set_follow_location(true);
  13918. cli.set_connection_timeout(30);
  13919. // Receiving any response proves the redirect client completed the TLS
  13920. // handshake with a system-CA-signed host
  13921. auto res = cli.Get("/index");
  13922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13923. }
  13924. TEST(MultipartFormDataTest, LargeData) {
  13925. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13926. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13927. const ContentReader &content_reader) {
  13928. if (req.is_multipart_form_data()) {
  13929. std::vector<FormData> items;
  13930. content_reader(
  13931. [&](const FormData &file) {
  13932. items.push_back(file);
  13933. return true;
  13934. },
  13935. [&](const char *data, size_t data_length) {
  13936. items.back().content.append(data, data_length);
  13937. return true;
  13938. });
  13939. EXPECT_TRUE(std::string(items[0].name) == "document");
  13940. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13941. EXPECT_TRUE(items[0].filename == "2MB_data");
  13942. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13943. EXPECT_TRUE(items[1].name == "hello");
  13944. EXPECT_TRUE(items[1].content == "world");
  13945. EXPECT_TRUE(items[1].filename == "");
  13946. EXPECT_TRUE(items[1].content_type == "");
  13947. } else {
  13948. std::string body;
  13949. content_reader([&](const char *data, size_t data_length) {
  13950. body.append(data, data_length);
  13951. return true;
  13952. });
  13953. }
  13954. });
  13955. auto port = svr.bind_to_any_port(HOST);
  13956. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13957. auto se = detail::scope_exit([&] {
  13958. svr.stop();
  13959. t.join();
  13960. ASSERT_FALSE(svr.is_running());
  13961. });
  13962. svr.wait_until_ready();
  13963. {
  13964. std::string data(1024 * 1024 * 2, '.');
  13965. std::stringstream buffer;
  13966. buffer << data;
  13967. SSLClient cli(HOST, port);
  13968. cli.enable_server_certificate_verification(false);
  13969. UploadFormDataItems items{
  13970. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13971. {"hello", "world", "", ""},
  13972. };
  13973. auto res = cli.Post("/post", items);
  13974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13975. ASSERT_EQ(StatusCode::OK_200, res->status);
  13976. }
  13977. }
  13978. TEST(MultipartFormDataTest, DataProviderItems) {
  13979. std::random_device seed_gen;
  13980. std::mt19937 random(seed_gen());
  13981. std::string rand1;
  13982. rand1.resize(1000);
  13983. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13984. std::string rand2;
  13985. rand2.resize(3000);
  13986. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13987. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13988. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13989. const ContentReader &content_reader) {
  13990. ASSERT_FALSE(req.is_multipart_form_data());
  13991. std::string body;
  13992. content_reader([&](const char *data, size_t data_length) {
  13993. body.append(data, data_length);
  13994. return true;
  13995. });
  13996. EXPECT_EQ(body, "");
  13997. });
  13998. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13999. const ContentReader &content_reader) {
  14000. ASSERT_TRUE(req.is_multipart_form_data());
  14001. std::vector<FormData> items;
  14002. content_reader(
  14003. [&](const FormData &file) {
  14004. items.push_back(file);
  14005. return true;
  14006. },
  14007. [&](const char *data, size_t data_length) {
  14008. items.back().content.append(data, data_length);
  14009. return true;
  14010. });
  14011. ASSERT_TRUE(items.size() == 2);
  14012. EXPECT_EQ(std::string(items[0].name), "name1");
  14013. EXPECT_EQ(items[0].content, "Testing123");
  14014. EXPECT_EQ(items[0].filename, "filename1");
  14015. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14016. EXPECT_EQ(items[1].name, "name2");
  14017. EXPECT_EQ(items[1].content, "Testing456");
  14018. EXPECT_EQ(items[1].filename, "");
  14019. EXPECT_EQ(items[1].content_type, "");
  14020. });
  14021. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14022. const ContentReader &content_reader) {
  14023. ASSERT_TRUE(req.is_multipart_form_data());
  14024. std::vector<FormData> items;
  14025. content_reader(
  14026. [&](const FormData &file) {
  14027. items.push_back(file);
  14028. return true;
  14029. },
  14030. [&](const char *data, size_t data_length) {
  14031. items.back().content.append(data, data_length);
  14032. return true;
  14033. });
  14034. ASSERT_TRUE(items.size() == 2);
  14035. EXPECT_EQ(items[0].name, "name3");
  14036. EXPECT_EQ(items[0].content, rand1);
  14037. EXPECT_EQ(items[0].filename, "filename3");
  14038. EXPECT_EQ(items[0].content_type, "");
  14039. EXPECT_EQ(items[1].name, "name4");
  14040. EXPECT_EQ(items[1].content, rand2);
  14041. EXPECT_EQ(items[1].filename, "filename4");
  14042. EXPECT_EQ(items[1].content_type, "");
  14043. });
  14044. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14045. const ContentReader &content_reader) {
  14046. ASSERT_TRUE(req.is_multipart_form_data());
  14047. std::vector<FormData> items;
  14048. content_reader(
  14049. [&](const FormData &file) {
  14050. items.push_back(file);
  14051. return true;
  14052. },
  14053. [&](const char *data, size_t data_length) {
  14054. items.back().content.append(data, data_length);
  14055. return true;
  14056. });
  14057. ASSERT_TRUE(items.size() == 4);
  14058. EXPECT_EQ(std::string(items[0].name), "name1");
  14059. EXPECT_EQ(items[0].content, "Testing123");
  14060. EXPECT_EQ(items[0].filename, "filename1");
  14061. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14062. EXPECT_EQ(items[1].name, "name2");
  14063. EXPECT_EQ(items[1].content, "Testing456");
  14064. EXPECT_EQ(items[1].filename, "");
  14065. EXPECT_EQ(items[1].content_type, "");
  14066. EXPECT_EQ(items[2].name, "name3");
  14067. EXPECT_EQ(items[2].content, rand1);
  14068. EXPECT_EQ(items[2].filename, "filename3");
  14069. EXPECT_EQ(items[2].content_type, "");
  14070. EXPECT_EQ(items[3].name, "name4");
  14071. EXPECT_EQ(items[3].content, rand2);
  14072. EXPECT_EQ(items[3].filename, "filename4");
  14073. EXPECT_EQ(items[3].content_type, "");
  14074. });
  14075. auto port = svr.bind_to_any_port("localhost");
  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. SSLClient cli("localhost", port);
  14085. cli.enable_server_certificate_verification(false);
  14086. UploadFormDataItems items{
  14087. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14088. {"name2", "Testing456", "", ""}, // not a file
  14089. };
  14090. {
  14091. auto res = cli.Post("/post-none", {}, {}, {});
  14092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14093. ASSERT_EQ(StatusCode::OK_200, res->status);
  14094. }
  14095. FormDataProviderItems providers;
  14096. {
  14097. auto res =
  14098. cli.Post("/post-items", {}, items, providers); // empty providers
  14099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14100. ASSERT_EQ(StatusCode::OK_200, res->status);
  14101. }
  14102. providers.push_back({"name3",
  14103. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14104. // test the offset is given correctly at each step
  14105. if (!offset)
  14106. sink.os.write(rand1.data(), 30);
  14107. else if (offset == 30)
  14108. sink.os.write(rand1.data() + 30, 300);
  14109. else if (offset == 330)
  14110. sink.os.write(rand1.data() + 330, 670);
  14111. else if (offset == rand1.size())
  14112. sink.done();
  14113. return true;
  14114. },
  14115. "filename3",
  14116. {}});
  14117. providers.push_back({"name4",
  14118. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14119. // test the offset is given correctly at each step
  14120. if (!offset)
  14121. sink.os.write(rand2.data(), 2000);
  14122. else if (offset == 2000)
  14123. sink.os.write(rand2.data() + 2000, 1);
  14124. else if (offset == 2001)
  14125. sink.os.write(rand2.data() + 2001, 999);
  14126. else if (offset == rand2.size())
  14127. sink.done();
  14128. return true;
  14129. },
  14130. "filename4",
  14131. {}});
  14132. {
  14133. auto res = cli.Post("/post-providers", {}, {}, providers);
  14134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14135. ASSERT_EQ(StatusCode::OK_200, res->status);
  14136. }
  14137. {
  14138. auto res = cli.Post("/post-both", {}, items, providers);
  14139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14140. ASSERT_EQ(StatusCode::OK_200, res->status);
  14141. }
  14142. }
  14143. }
  14144. TEST(MultipartFormDataTest, BadHeader) {
  14145. Server svr;
  14146. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14147. res.set_content("ok", "text/plain");
  14148. });
  14149. thread t = thread([&] { svr.listen(HOST, PORT); });
  14150. auto se = detail::scope_exit([&] {
  14151. svr.stop();
  14152. t.join();
  14153. ASSERT_FALSE(svr.is_running());
  14154. });
  14155. svr.wait_until_ready();
  14156. const std::string body =
  14157. "This is the preamble. It is to be ignored, though it\r\n"
  14158. "is a handy place for composition agents to include an\r\n"
  14159. "explanatory note to non-MIME conformant readers.\r\n"
  14160. "\r\n"
  14161. "\r\n"
  14162. "--simple boundary\r\n"
  14163. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14164. ": BAD...\r\n"
  14165. "\r\n"
  14166. "value1\r\n"
  14167. "--simple boundary\r\n"
  14168. "Content-Disposition: form-data; name=\"field2\"; "
  14169. "filename=\"example.txt\"\r\n"
  14170. "\r\n"
  14171. "value2\r\n"
  14172. "--simple boundary--\r\n"
  14173. "This is the epilogue. It is also to be ignored.\r\n";
  14174. std::string content_type =
  14175. R"(multipart/form-data; boundary="simple boundary")";
  14176. Client cli(HOST, PORT);
  14177. auto res = cli.Post("/post", body, content_type.c_str());
  14178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14179. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14180. }
  14181. TEST(MultipartFormDataTest, WithPreamble) {
  14182. Server svr;
  14183. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14184. res.set_content("ok", "text/plain");
  14185. });
  14186. thread t = thread([&] { svr.listen(HOST, PORT); });
  14187. auto se = detail::scope_exit([&] {
  14188. svr.stop();
  14189. t.join();
  14190. ASSERT_FALSE(svr.is_running());
  14191. });
  14192. svr.wait_until_ready();
  14193. const std::string body =
  14194. "This is the preamble. It is to be ignored, though it\r\n"
  14195. "is a handy place for composition agents to include an\r\n"
  14196. "explanatory note to non-MIME conformant readers.\r\n"
  14197. "\r\n"
  14198. "\r\n"
  14199. "--simple boundary\r\n"
  14200. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14201. "\r\n"
  14202. "value1\r\n"
  14203. "--simple boundary\r\n"
  14204. "Content-Disposition: form-data; name=\"field2\"; "
  14205. "filename=\"example.txt\"\r\n"
  14206. "\r\n"
  14207. "value2\r\n"
  14208. "--simple boundary--\r\n"
  14209. "This is the epilogue. It is also to be ignored.\r\n";
  14210. std::string content_type =
  14211. R"(multipart/form-data; boundary="simple boundary")";
  14212. Client cli(HOST, PORT);
  14213. auto res = cli.Post("/post", body, content_type.c_str());
  14214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14215. EXPECT_EQ(StatusCode::OK_200, res->status);
  14216. }
  14217. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14218. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14219. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14220. const ContentReader &content_reader) {
  14221. if (req.is_multipart_form_data()) {
  14222. std::vector<FormData> items;
  14223. content_reader(
  14224. [&](const FormData &file) {
  14225. items.push_back(file);
  14226. return true;
  14227. },
  14228. [&](const char *data, size_t data_length) {
  14229. items.back().content.append(data, data_length);
  14230. return true;
  14231. });
  14232. EXPECT_TRUE(std::string(items[0].name) == "document");
  14233. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14234. EXPECT_TRUE(items[0].filename == "2MB_data");
  14235. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14236. EXPECT_TRUE(items[1].name == "hello");
  14237. EXPECT_TRUE(items[1].content == "world");
  14238. EXPECT_TRUE(items[1].filename == "");
  14239. EXPECT_TRUE(items[1].content_type == "");
  14240. } else {
  14241. std::string body;
  14242. content_reader([&](const char *data, size_t data_length) {
  14243. body.append(data, data_length);
  14244. return true;
  14245. });
  14246. }
  14247. });
  14248. auto port = svr.bind_to_any_port("localhost");
  14249. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. t.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. });
  14255. svr.wait_until_ready();
  14256. {
  14257. std::string data(1024 * 1024 * 2, '.');
  14258. std::stringstream buffer;
  14259. buffer << data;
  14260. SSLClient cli("localhost", port);
  14261. cli.enable_server_certificate_verification(false);
  14262. UploadFormDataItems items{
  14263. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14264. {"hello", "world", "", ""},
  14265. };
  14266. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14268. ASSERT_EQ(StatusCode::OK_200, res->status);
  14269. }
  14270. }
  14271. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14272. std::string data(1024 * 1024 * 2, '&');
  14273. std::stringstream buffer;
  14274. buffer << data;
  14275. Client cli("https://localhost:8080");
  14276. UploadFormDataItems items{
  14277. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14278. {"hello", "world", "", ""},
  14279. };
  14280. for (const char &c : " \t\r\n") {
  14281. auto res =
  14282. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14283. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14284. ASSERT_FALSE(res);
  14285. }
  14286. }
  14287. TEST(MultipartFormDataTest, PutFormData) {
  14288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14289. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14290. const ContentReader &content_reader) {
  14291. if (req.is_multipart_form_data()) {
  14292. std::vector<FormData> items;
  14293. content_reader(
  14294. [&](const FormData &file) {
  14295. items.push_back(file);
  14296. return true;
  14297. },
  14298. [&](const char *data, size_t data_length) {
  14299. items.back().content.append(data, data_length);
  14300. return true;
  14301. });
  14302. EXPECT_TRUE(std::string(items[0].name) == "document");
  14303. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14304. EXPECT_TRUE(items[0].filename == "2MB_data");
  14305. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14306. EXPECT_TRUE(items[1].name == "hello");
  14307. EXPECT_TRUE(items[1].content == "world");
  14308. EXPECT_TRUE(items[1].filename == "");
  14309. EXPECT_TRUE(items[1].content_type == "");
  14310. } else {
  14311. std::string body;
  14312. content_reader([&](const char *data, size_t data_length) {
  14313. body.append(data, data_length);
  14314. return true;
  14315. });
  14316. }
  14317. });
  14318. auto port = svr.bind_to_any_port("localhost");
  14319. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14320. auto se = detail::scope_exit([&] {
  14321. svr.stop();
  14322. t.join();
  14323. ASSERT_FALSE(svr.is_running());
  14324. });
  14325. svr.wait_until_ready();
  14326. {
  14327. std::string data(1024 * 1024 * 2, '&');
  14328. std::stringstream buffer;
  14329. buffer << data;
  14330. SSLClient cli("localhost", port);
  14331. cli.enable_server_certificate_verification(false);
  14332. UploadFormDataItems items{
  14333. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14334. {"hello", "world", "", ""},
  14335. };
  14336. auto res = cli.Put("/put", items);
  14337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14338. ASSERT_EQ(StatusCode::OK_200, res->status);
  14339. }
  14340. }
  14341. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14343. svr.Put("/put_customboundary",
  14344. [&](const Request &req, const Response & /*res*/,
  14345. const ContentReader &content_reader) {
  14346. if (req.is_multipart_form_data()) {
  14347. std::vector<FormData> items;
  14348. content_reader(
  14349. [&](const FormData &file) {
  14350. items.push_back(file);
  14351. return true;
  14352. },
  14353. [&](const char *data, size_t data_length) {
  14354. items.back().content.append(data, data_length);
  14355. return true;
  14356. });
  14357. EXPECT_TRUE(std::string(items[0].name) == "document");
  14358. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14359. EXPECT_TRUE(items[0].filename == "2MB_data");
  14360. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14361. EXPECT_TRUE(items[1].name == "hello");
  14362. EXPECT_TRUE(items[1].content == "world");
  14363. EXPECT_TRUE(items[1].filename == "");
  14364. EXPECT_TRUE(items[1].content_type == "");
  14365. } else {
  14366. std::string body;
  14367. content_reader([&](const char *data, size_t data_length) {
  14368. body.append(data, data_length);
  14369. return true;
  14370. });
  14371. }
  14372. });
  14373. auto port = svr.bind_to_any_port("localhost");
  14374. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14375. auto se = detail::scope_exit([&] {
  14376. svr.stop();
  14377. t.join();
  14378. ASSERT_FALSE(svr.is_running());
  14379. });
  14380. svr.wait_until_ready();
  14381. {
  14382. std::string data(1024 * 1024 * 2, '&');
  14383. std::stringstream buffer;
  14384. buffer << data;
  14385. SSLClient cli("localhost", port);
  14386. cli.enable_server_certificate_verification(false);
  14387. UploadFormDataItems items{
  14388. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14389. {"hello", "world", "", ""},
  14390. };
  14391. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14393. ASSERT_EQ(StatusCode::OK_200, res->status);
  14394. }
  14395. }
  14396. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14397. std::string data(1024 * 1024 * 2, '&');
  14398. std::stringstream buffer;
  14399. buffer << data;
  14400. Client cli("https://localhost:8080");
  14401. cli.enable_server_certificate_verification(false);
  14402. UploadFormDataItems items{
  14403. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14404. {"hello", "world", "", ""},
  14405. };
  14406. for (const char &c : " \t\r\n") {
  14407. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14408. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14409. ASSERT_FALSE(res);
  14410. }
  14411. }
  14412. TEST(MultipartFormDataTest, AlternateFilename) {
  14413. auto handled = false;
  14414. Server svr;
  14415. svr.Post("/test", [&](const Request &req, Response &res) {
  14416. ASSERT_EQ(2u, req.form.files.size());
  14417. ASSERT_EQ(1u, req.form.fields.size());
  14418. // Test files
  14419. const auto &file1 = req.form.get_file("file1");
  14420. ASSERT_EQ("file1", file1.name);
  14421. ASSERT_EQ("A.txt", file1.filename);
  14422. ASSERT_EQ("text/plain", file1.content_type);
  14423. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14424. const auto &file2 = req.form.get_file("file2");
  14425. ASSERT_EQ("file2", file2.name);
  14426. ASSERT_EQ("a.html", file2.filename);
  14427. ASSERT_EQ("text/html", file2.content_type);
  14428. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14429. file2.content);
  14430. // Test text field
  14431. const auto &text = req.form.get_field("text");
  14432. ASSERT_EQ("text default", text);
  14433. res.set_content("ok", "text/plain");
  14434. handled = true;
  14435. });
  14436. thread t = thread([&] { svr.listen(HOST, PORT); });
  14437. auto se = detail::scope_exit([&] {
  14438. svr.stop();
  14439. t.join();
  14440. ASSERT_FALSE(svr.is_running());
  14441. ASSERT_TRUE(handled);
  14442. });
  14443. svr.wait_until_ready();
  14444. auto req = "POST /test HTTP/1.1\r\n"
  14445. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14446. "Content-Length: 399\r\n"
  14447. "\r\n"
  14448. "----------\r\n"
  14449. "Content-Disposition: form-data; name=\"text\"\r\n"
  14450. "\r\n"
  14451. "text default\r\n"
  14452. "----------\r\n"
  14453. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14454. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14455. "Content-Type: text/plain\r\n"
  14456. "\r\n"
  14457. "Content of a.txt.\r\n"
  14458. "\r\n"
  14459. "----------\r\n"
  14460. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14461. "\"a.html\"\r\n"
  14462. "Content-Type: text/html\r\n"
  14463. "\r\n"
  14464. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14465. "\r\n"
  14466. "------------\r\n";
  14467. ASSERT_TRUE(send_request(1, req));
  14468. }
  14469. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14470. auto handled = false;
  14471. Server svr;
  14472. svr.Post("/test", [&](const Request &req, Response &res) {
  14473. // Case-insensitive "utf-8''" prefix with a long value
  14474. const auto &file = req.form.get_file("file1");
  14475. ASSERT_EQ("file1", file.name);
  14476. // 8000 chars exercises both the Content-Disposition parser and the
  14477. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14478. // Prior to the fix, std::regex_match on this header would cause O(N)
  14479. // stack recursion in libstdc++, leading to SIGSEGV.
  14480. std::string expected_filename(8000, 'A');
  14481. ASSERT_EQ(expected_filename, file.filename);
  14482. res.set_content("ok", "text/plain");
  14483. handled = true;
  14484. });
  14485. thread t = thread([&] { svr.listen(HOST, PORT); });
  14486. auto se = detail::scope_exit([&] {
  14487. svr.stop();
  14488. t.join();
  14489. ASSERT_FALSE(svr.is_running());
  14490. ASSERT_TRUE(handled);
  14491. });
  14492. svr.wait_until_ready();
  14493. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14494. // Regression test for GHSA-qq6v-r583-3h69
  14495. std::string long_filename(8000, 'A');
  14496. std::string body = "----------\r\n"
  14497. "Content-Disposition: form-data; name=\"file1\"; "
  14498. "filename*=\"Utf-8''" +
  14499. long_filename +
  14500. "\"\r\n"
  14501. "\r\n"
  14502. "hello\r\n"
  14503. "------------\r\n";
  14504. auto req = "POST /test HTTP/1.1\r\n"
  14505. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14506. "Content-Length: " +
  14507. std::to_string(body.size()) + "\r\n\r\n" + body;
  14508. ASSERT_TRUE(send_request(1, req));
  14509. }
  14510. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14511. auto handled = false;
  14512. Server svr;
  14513. svr.Post("/test", [&](const Request &req, Response &) {
  14514. ASSERT_EQ(2u, req.form.fields.size());
  14515. const auto &text1 = req.form.get_field("text1");
  14516. ASSERT_EQ("text1", text1);
  14517. const auto &text2 = req.form.get_field("text2");
  14518. ASSERT_EQ("text2", text2);
  14519. handled = true;
  14520. });
  14521. thread t = thread([&] { svr.listen(HOST, PORT); });
  14522. auto se = detail::scope_exit([&] {
  14523. svr.stop();
  14524. t.join();
  14525. ASSERT_FALSE(svr.is_running());
  14526. ASSERT_TRUE(handled);
  14527. });
  14528. svr.wait_until_ready();
  14529. auto req = "POST /test HTTP/1.1\r\n"
  14530. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14531. "Content-Length: 146\r\n"
  14532. "\r\n----------\r\n"
  14533. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14534. "\r\n"
  14535. "text1"
  14536. "\r\n----------\r\n"
  14537. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14538. "\r\n"
  14539. "text2"
  14540. "\r\n------------";
  14541. std::string response;
  14542. ASSERT_TRUE(send_request(1, req, &response));
  14543. ASSERT_EQ("200", response.substr(9, 3));
  14544. }
  14545. TEST(MultipartFormDataTest, ContentLength) {
  14546. auto handled = false;
  14547. Server svr;
  14548. svr.Post("/test", [&](const Request &req, Response &) {
  14549. ASSERT_EQ(2u, req.form.fields.size());
  14550. const auto &text1 = req.form.get_field("text1");
  14551. ASSERT_EQ("text1", text1);
  14552. const auto &text2 = req.form.get_field("text2");
  14553. ASSERT_EQ("text2", text2);
  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: 167\r\n"
  14567. "\r\n----------\r\n"
  14568. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14569. "Content-Length: 5\r\n"
  14570. "\r\n"
  14571. "text1"
  14572. "\r\n----------\r\n"
  14573. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14574. "\r\n"
  14575. "text2"
  14576. "\r\n------------\r\n";
  14577. std::string response;
  14578. ASSERT_TRUE(send_request(1, req, &response));
  14579. ASSERT_EQ("200", response.substr(9, 3));
  14580. }
  14581. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14582. auto handled = false;
  14583. Server svr;
  14584. svr.Post("/test", [&](const Request &req, Response &) {
  14585. ASSERT_EQ(2u, req.form.fields.size());
  14586. const auto &text1 = req.form.get_field("text1");
  14587. ASSERT_EQ("text1", text1);
  14588. // TODO: Add header access for text fields if needed
  14589. const auto &text2 = req.form.get_field("text2");
  14590. ASSERT_EQ("text2", text2);
  14591. // TODO: Header access for text fields needs to be implemented
  14592. // auto &headers = it->second.headers;
  14593. // ASSERT_EQ(3U, headers.size());
  14594. // auto custom_header = headers.find("x-whatever");
  14595. // ASSERT_TRUE(custom_header != headers.end());
  14596. // ASSERT_NE("customvalue", custom_header->second);
  14597. // ASSERT_EQ("CustomValue", custom_header->second);
  14598. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14599. handled = true;
  14600. });
  14601. thread t = thread([&] { svr.listen(HOST, PORT); });
  14602. auto se = detail::scope_exit([&] {
  14603. svr.stop();
  14604. t.join();
  14605. ASSERT_FALSE(svr.is_running());
  14606. ASSERT_TRUE(handled);
  14607. });
  14608. svr.wait_until_ready();
  14609. auto req = "POST /test HTTP/1.1\r\n"
  14610. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14611. "Content-Length: 232\r\n"
  14612. "\r\n----------\r\n"
  14613. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14614. "Content-Length: 5\r\n"
  14615. "X-Test: 1\r\n"
  14616. "\r\n"
  14617. "text1"
  14618. "\r\n----------\r\n"
  14619. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14620. "Content-Type: text/plain\r\n"
  14621. "X-Whatever: CustomValue\r\n"
  14622. "\r\n"
  14623. "text2"
  14624. "\r\n------------\r\n"
  14625. "That should be disregarded. Not even read";
  14626. std::string response;
  14627. ASSERT_TRUE(send_request(1, req, &response));
  14628. ASSERT_EQ("200", response.substr(9, 3));
  14629. }
  14630. TEST(MultipartFormDataTest, LargeHeader) {
  14631. auto handled = false;
  14632. Server svr;
  14633. svr.Post("/test", [&](const Request &req, Response &) {
  14634. ASSERT_EQ(1u, req.form.fields.size());
  14635. const auto &text = req.form.get_field("name1");
  14636. ASSERT_EQ("text1", text);
  14637. handled = true;
  14638. });
  14639. thread t = thread([&] { svr.listen(HOST, PORT); });
  14640. auto se = detail::scope_exit([&] {
  14641. svr.stop();
  14642. t.join();
  14643. ASSERT_FALSE(svr.is_running());
  14644. ASSERT_TRUE(handled);
  14645. });
  14646. svr.wait_until_ready();
  14647. auto boundary = std::string("cpp-httplib-multipart-data");
  14648. std::string content = "--" + boundary +
  14649. "\r\n"
  14650. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14651. "\r\n"
  14652. "text1\r\n"
  14653. "--" +
  14654. boundary + "--\r\n";
  14655. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14656. "Content-Type: multipart/form-data;boundary=" +
  14657. boundary +
  14658. "\r\n"
  14659. "Content-Length: " +
  14660. std::to_string(content.size()) +
  14661. "\r\n"
  14662. "Dummy-Header: ";
  14663. std::string header_suffix = "\r\n"
  14664. "\r\n";
  14665. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14666. size_t header_dummy_size =
  14667. read_buff_size -
  14668. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14669. auto header_dummy = std::string(header_dummy_size, '@');
  14670. auto req = header_prefix + header_dummy + header_suffix + content;
  14671. std::string response;
  14672. ASSERT_TRUE(send_request(1, req, &response));
  14673. ASSERT_EQ("200", response.substr(9, 3));
  14674. }
  14675. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14676. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14677. // (not chunked Transfer-Encoding) after the streaming refactor.
  14678. auto handled = false;
  14679. Server svr;
  14680. svr.Post("/upload", [&](const Request &req, Response &res) {
  14681. auto cl_it = req.headers.find("Content-Length");
  14682. EXPECT_TRUE(cl_it != req.headers.end());
  14683. auto te_it = req.headers.find("Transfer-Encoding");
  14684. EXPECT_TRUE(te_it == req.headers.end());
  14685. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14686. res.set_content("ok", "text/plain");
  14687. handled = true;
  14688. });
  14689. auto port = svr.bind_to_any_port(HOST);
  14690. auto t = thread([&] { svr.listen_after_bind(); });
  14691. auto se = detail::scope_exit([&] {
  14692. svr.stop();
  14693. t.join();
  14694. ASSERT_FALSE(svr.is_running());
  14695. ASSERT_TRUE(handled);
  14696. });
  14697. svr.wait_until_ready();
  14698. UploadFormDataItems items = {
  14699. {"field1", "hello", "", "text/plain"},
  14700. {"file1", "world", "test.txt", "application/octet-stream"},
  14701. };
  14702. Client cli(HOST, port);
  14703. auto res = cli.Post("/upload", {}, items);
  14704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14705. EXPECT_EQ(StatusCode::OK_200, res->status);
  14706. }
  14707. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14708. // Verify that make_multipart_content_provider coalesces many small segments
  14709. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14710. constexpr size_t kItemCount = 1000;
  14711. UploadFormDataItems items;
  14712. items.reserve(kItemCount);
  14713. for (size_t i = 0; i < kItemCount; i++) {
  14714. items.push_back(
  14715. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14716. }
  14717. const std::string boundary = "----test-boundary";
  14718. auto content_length = detail::get_multipart_content_length(items, boundary);
  14719. auto provider = detail::make_multipart_content_provider(items, boundary);
  14720. // Drive the provider the same way write_content_with_progress does
  14721. size_t write_count = 0;
  14722. size_t total_bytes = 0;
  14723. DataSink sink;
  14724. size_t offset = 0;
  14725. sink.write = [&](const char *d, size_t l) -> bool {
  14726. (void)d;
  14727. write_count++;
  14728. total_bytes += l;
  14729. offset += l;
  14730. return true;
  14731. };
  14732. sink.is_writable = []() -> bool { return true; };
  14733. while (offset < content_length) {
  14734. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14735. }
  14736. EXPECT_EQ(content_length, total_bytes);
  14737. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14738. // With buffering into 64KB blocks, write_count should be much smaller.
  14739. auto segment_count = 3 * kItemCount + 1;
  14740. EXPECT_LT(write_count, segment_count / 10);
  14741. }
  14742. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14743. // Integration test: send many UploadFormDataItems and verify the server
  14744. // receives all of them correctly (#2410).
  14745. constexpr size_t kItemCount = 500;
  14746. auto handled = false;
  14747. Server svr;
  14748. svr.Post("/upload", [&](const Request &req, Response &res) {
  14749. EXPECT_EQ(kItemCount, req.form.fields.size());
  14750. for (size_t i = 0; i < kItemCount; i++) {
  14751. auto key = "field" + std::to_string(i);
  14752. auto val = "value" + std::to_string(i);
  14753. auto it = req.form.fields.find(key);
  14754. if (it != req.form.fields.end()) {
  14755. EXPECT_EQ(val, it->second.content);
  14756. } else {
  14757. ADD_FAILURE() << "Missing field: " << key;
  14758. }
  14759. }
  14760. res.set_content("ok", "text/plain");
  14761. handled = true;
  14762. });
  14763. auto port = svr.bind_to_any_port(HOST);
  14764. auto t = thread([&] { svr.listen_after_bind(); });
  14765. auto se = detail::scope_exit([&] {
  14766. svr.stop();
  14767. t.join();
  14768. ASSERT_FALSE(svr.is_running());
  14769. ASSERT_TRUE(handled);
  14770. });
  14771. svr.wait_until_ready();
  14772. UploadFormDataItems items;
  14773. items.reserve(kItemCount);
  14774. for (size_t i = 0; i < kItemCount; i++) {
  14775. items.push_back(
  14776. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14777. }
  14778. Client cli(HOST, port);
  14779. auto res = cli.Post("/upload", items);
  14780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14781. EXPECT_EQ(StatusCode::OK_200, res->status);
  14782. }
  14783. TEST(MultipartFormDataTest, MakeFileProvider) {
  14784. // Verify make_file_provider sends a file's contents correctly.
  14785. const std::string file_content(4096, 'Z');
  14786. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14787. {
  14788. std::ofstream ofs(tmp_path, std::ios::binary);
  14789. ofs.write(file_content.data(),
  14790. static_cast<std::streamsize>(file_content.size()));
  14791. }
  14792. auto handled = false;
  14793. Server svr;
  14794. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14795. const ContentReader &content_reader) {
  14796. ASSERT_TRUE(req.is_multipart_form_data());
  14797. std::vector<FormData> items;
  14798. content_reader(
  14799. [&](const FormData &file) {
  14800. items.push_back(file);
  14801. return true;
  14802. },
  14803. [&](const char *data, size_t data_length) {
  14804. items.back().content.append(data, data_length);
  14805. return true;
  14806. });
  14807. ASSERT_EQ(1u, items.size());
  14808. EXPECT_EQ("myfile", items[0].name);
  14809. EXPECT_EQ("data.bin", items[0].filename);
  14810. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14811. EXPECT_EQ(file_content, items[0].content);
  14812. handled = true;
  14813. });
  14814. auto port = svr.bind_to_any_port(HOST);
  14815. auto t = thread([&] { svr.listen_after_bind(); });
  14816. auto se = detail::scope_exit([&] {
  14817. svr.stop();
  14818. t.join();
  14819. ASSERT_FALSE(svr.is_running());
  14820. ASSERT_TRUE(handled);
  14821. std::remove(tmp_path.c_str());
  14822. });
  14823. svr.wait_until_ready();
  14824. FormDataProviderItems providers;
  14825. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14826. "application/octet-stream"));
  14827. Client cli(HOST, port);
  14828. auto res = cli.Post("/upload", {}, {}, providers);
  14829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14830. EXPECT_EQ(StatusCode::OK_200, res->status);
  14831. }
  14832. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14833. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14834. // (100) headers is rejected with a 400 Bad Request response.
  14835. Server svr;
  14836. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14837. res.set_content("ok", "text/plain");
  14838. });
  14839. thread t = thread([&] { svr.listen(HOST, PORT); });
  14840. auto se = detail::scope_exit([&] {
  14841. svr.stop();
  14842. t.join();
  14843. ASSERT_FALSE(svr.is_running());
  14844. });
  14845. svr.wait_until_ready();
  14846. // Build a multipart part with 101 custom headers (exceeding
  14847. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14848. std::stringstream body;
  14849. body << "--simpleboundary\r\n"
  14850. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14851. for (int i = 0; i < 101; i++) {
  14852. body << "X-Custom-Header-" << i << ": value\r\n";
  14853. }
  14854. body << "\r\n"
  14855. << "value1\r\n"
  14856. << "--simpleboundary--\r\n";
  14857. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14858. Client cli(HOST, PORT);
  14859. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14862. }
  14863. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14864. // A body that never contains the declared boundary must not be accumulated
  14865. // while the parser waits for it. Buffering it would also make every read
  14866. // rescan everything seen so far, which is quadratic in the body size.
  14867. Server svr;
  14868. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14869. res.set_content("ok", "text/plain");
  14870. });
  14871. auto port = svr.bind_to_any_port(HOST);
  14872. thread t = thread([&] { svr.listen_after_bind(); });
  14873. auto se = detail::scope_exit([&] {
  14874. svr.stop();
  14875. t.join();
  14876. ASSERT_FALSE(svr.is_running());
  14877. });
  14878. svr.wait_until_ready();
  14879. Client cli(HOST, port);
  14880. cli.set_read_timeout(60, 0);
  14881. cli.set_write_timeout(60, 0);
  14882. // '-' is the worst case: it matches the first character of the boundary, so
  14883. // every position has to be checked against it.
  14884. auto post_dashes = [&](size_t size) {
  14885. const std::string body(size, '-');
  14886. auto start = std::chrono::steady_clock::now();
  14887. auto res =
  14888. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14889. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14890. std::chrono::steady_clock::now() - start)
  14891. .count();
  14892. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14893. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14894. return ms;
  14895. };
  14896. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14897. // Windows.
  14898. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14899. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14900. // Comparing the two sizes rather than checking an absolute duration keeps
  14901. // this meaningful across build types and CI load, both of which move the
  14902. // absolute numbers by more than an order of magnitude. Four times the bytes
  14903. // costs about four times the time when parsing is linear, and about sixteen
  14904. // times when the body is buffered and rescanned.
  14905. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14906. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14907. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14908. << "ms, which suggests the body is being buffered and rescanned";
  14909. }
  14910. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14911. // A boundary can only be followed by CRLF or by "--", so anything else is
  14912. // malformed no matter what comes next. The parser must say so right away
  14913. // instead of buffering the rest of the declared body.
  14914. Server svr;
  14915. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14916. res.set_content("ok", "text/plain");
  14917. });
  14918. auto port = svr.bind_to_any_port(HOST);
  14919. thread t = thread([&] { svr.listen_after_bind(); });
  14920. auto se = detail::scope_exit([&] {
  14921. svr.stop();
  14922. t.join();
  14923. ASSERT_FALSE(svr.is_running());
  14924. });
  14925. svr.wait_until_ready();
  14926. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14927. // buffers instead of failing would still be waiting for the remaining bytes.
  14928. const std::string body = "--zzzz\r\n"
  14929. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14930. "\r\n"
  14931. "text1"
  14932. "\r\n--zzzzXX";
  14933. const std::string req = "POST /post HTTP/1.1\r\n"
  14934. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14935. "Content-Length: 1048576\r\n"
  14936. "\r\n" +
  14937. body;
  14938. std::string response;
  14939. ASSERT_TRUE(send_request(3, req, &response, port));
  14940. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14941. EXPECT_EQ("400", response.substr(9, 3));
  14942. }
  14943. // Posts a multipart body split into two writes, so that the server sees the
  14944. // split at whatever offset the caller chose, and expects the single "text1"
  14945. // field to come through.
  14946. static void expect_split_multipart_ok(const std::string &body1,
  14947. const std::string &body2) {
  14948. auto handled = false;
  14949. Server svr;
  14950. svr.Post("/post", [&](const Request &req, Response &) {
  14951. EXPECT_EQ(1u, req.form.fields.size());
  14952. EXPECT_EQ("text1", req.form.get_field("text1"));
  14953. handled = true;
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. thread t = thread([&] { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. ASSERT_FALSE(svr.is_running());
  14961. ASSERT_TRUE(handled);
  14962. });
  14963. svr.wait_until_ready();
  14964. // "Connection: close" makes the server close once it has answered, so the
  14965. // response drain ends immediately instead of idling until the read timeout.
  14966. const std::string head =
  14967. "POST /post HTTP/1.1\r\n"
  14968. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14969. "Connection: close\r\n"
  14970. "Content-Length: " +
  14971. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14972. std::string response;
  14973. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14974. ASSERT_GE(response.size(), 12u) << "no response";
  14975. EXPECT_EQ("200", response.substr(9, 3));
  14976. }
  14977. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14978. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14979. // ignored, including when it does not arrive in the same read as the
  14980. // close-delimiter itself.
  14981. expect_split_multipart_ok("--zzzz\r\n"
  14982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14983. "\r\n"
  14984. "text1"
  14985. "\r\n--zzzz--",
  14986. "\r\nthis epilogue must be ignored\r\n");
  14987. }
  14988. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14989. // The initial boundary may be preceded by a preamble of any length and may
  14990. // straddle a read boundary. Discarding data while waiting for it must not
  14991. // throw away a partial boundary sitting at the end of the buffer.
  14992. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14993. "zz\r\n"
  14994. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14995. "\r\n"
  14996. "text1"
  14997. "\r\n--zzzz--\r\n");
  14998. }
  14999. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15000. // The received boundary was only checked for being non-empty, so it could be
  15001. // as long as a header is allowed to be. The parser scans the body for
  15002. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15003. // costs a nearly full comparison at nearly every position, making the
  15004. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15005. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15006. Server svr;
  15007. svr.Post("/post", [](const Request &req, Response &res) {
  15008. EXPECT_EQ(1u, req.form.fields.size());
  15009. EXPECT_EQ("text1", req.form.get_field("text1"));
  15010. res.set_content("ok", "text/plain");
  15011. });
  15012. auto port = svr.bind_to_any_port(HOST);
  15013. thread t = thread([&] { svr.listen_after_bind(); });
  15014. auto se = detail::scope_exit([&] {
  15015. svr.stop();
  15016. t.join();
  15017. ASSERT_FALSE(svr.is_running());
  15018. });
  15019. svr.wait_until_ready();
  15020. Client cli(HOST, port);
  15021. auto post_with_boundary_of_length = [&](size_t len) {
  15022. const std::string boundary(len, 'a');
  15023. const std::string body =
  15024. "--" + boundary +
  15025. "\r\n"
  15026. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15027. "\r\n"
  15028. "text1"
  15029. "\r\n--" +
  15030. boundary + "--\r\n";
  15031. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15032. };
  15033. auto res = post_with_boundary_of_length(70);
  15034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15035. EXPECT_EQ(StatusCode::OK_200, res->status);
  15036. res = post_with_boundary_of_length(71);
  15037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15038. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15039. }
  15040. TEST(MakeFileBodyTest, Basic) {
  15041. const std::string file_content(4096, 'Z');
  15042. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15043. {
  15044. std::ofstream ofs(tmp_path, std::ios::binary);
  15045. ofs.write(file_content.data(),
  15046. static_cast<std::streamsize>(file_content.size()));
  15047. }
  15048. auto handled = false;
  15049. Server svr;
  15050. svr.Post("/upload", [&](const Request &req, Response &res) {
  15051. EXPECT_EQ(file_content, req.body);
  15052. handled = true;
  15053. res.status = StatusCode::OK_200;
  15054. });
  15055. auto port = svr.bind_to_any_port(HOST);
  15056. auto t = thread([&] { svr.listen_after_bind(); });
  15057. auto se = detail::scope_exit([&] {
  15058. svr.stop();
  15059. t.join();
  15060. ASSERT_FALSE(svr.is_running());
  15061. ASSERT_TRUE(handled);
  15062. std::remove(tmp_path.c_str());
  15063. });
  15064. svr.wait_until_ready();
  15065. auto fb = make_file_body(tmp_path);
  15066. ASSERT_GT(fb.first, 0u);
  15067. Client cli(HOST, port);
  15068. auto res =
  15069. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15071. EXPECT_EQ(StatusCode::OK_200, res->status);
  15072. }
  15073. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15074. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15075. {
  15076. std::ofstream ofs(path, std::ios::binary);
  15077. const std::string content(100, 'A');
  15078. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15079. }
  15080. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15081. auto body = make_file_body(path);
  15082. ASSERT_EQ(100u, body.first);
  15083. ASSERT_TRUE(static_cast<bool>(body.second));
  15084. // Rewritten shorter after its length was measured - and, on a server, after
  15085. // that length has already gone out as Content-Length.
  15086. {
  15087. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15088. const std::string content(10, 'A');
  15089. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15090. }
  15091. std::string written;
  15092. DataSink sink;
  15093. sink.write = [&](const char *d, size_t l) {
  15094. written.append(d, l);
  15095. return true;
  15096. };
  15097. // The provider has to report failure. write_content_with_progress() advances
  15098. // its offset only by what was written, so a provider that returns true
  15099. // without completing the length it promised is called again straight away,
  15100. // and again.
  15101. EXPECT_FALSE(body.second(0, body.first, sink));
  15102. EXPECT_EQ(std::string(10, 'A'), written);
  15103. }
  15104. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15105. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15106. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15107. {
  15108. std::ofstream ofs(path, std::ios::binary);
  15109. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15110. }
  15111. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15112. auto body = make_file_body(path);
  15113. ASSERT_EQ(content.size(), body.first);
  15114. ASSERT_TRUE(static_cast<bool>(body.second));
  15115. std::string written;
  15116. DataSink sink;
  15117. sink.write = [&](const char *d, size_t l) {
  15118. written.append(d, l);
  15119. return true;
  15120. };
  15121. EXPECT_TRUE(body.second(0, body.first, sink));
  15122. EXPECT_EQ(content, written);
  15123. }
  15124. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15125. static constexpr unsigned int number_of_tasks{1000000};
  15126. std::atomic_uint count{0};
  15127. std::unique_ptr<TaskQueue> task_queue{
  15128. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15129. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15130. auto queued = task_queue->enqueue(
  15131. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15132. EXPECT_TRUE(queued);
  15133. }
  15134. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15135. task_queue->shutdown();
  15136. #else
  15137. EXPECT_NO_THROW(task_queue->shutdown());
  15138. #endif
  15139. EXPECT_EQ(number_of_tasks, count.load());
  15140. }
  15141. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15142. static constexpr unsigned int number_of_tasks{1000000};
  15143. static constexpr unsigned int qlimit{2};
  15144. unsigned int queued_count{0};
  15145. std::atomic_uint count{0};
  15146. std::unique_ptr<TaskQueue> task_queue{
  15147. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15148. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15149. if (task_queue->enqueue(
  15150. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15151. queued_count++;
  15152. }
  15153. }
  15154. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15155. task_queue->shutdown();
  15156. #else
  15157. EXPECT_NO_THROW(task_queue->shutdown());
  15158. #endif
  15159. EXPECT_EQ(queued_count, count.load());
  15160. EXPECT_TRUE(queued_count <= number_of_tasks);
  15161. EXPECT_TRUE(queued_count >= qlimit);
  15162. }
  15163. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15164. // Use a short idle timeout so a dynamic thread spawns, times out and
  15165. // exits during the test, and the pool keeps working afterwards.
  15166. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15167. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15168. /*idle_timeout_sec=*/1}};
  15169. std::atomic_uint count{0};
  15170. std::condition_variable cv;
  15171. std::mutex mtx;
  15172. bool release = false;
  15173. // Block the base thread so the second task spawns a dynamic thread.
  15174. EXPECT_TRUE(task_queue->enqueue([&] {
  15175. std::unique_lock<std::mutex> lock(mtx);
  15176. while (!release) {
  15177. cv.wait(lock);
  15178. }
  15179. count++;
  15180. }));
  15181. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15182. // Let the dynamic thread finish its task and exceed the idle timeout.
  15183. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15184. {
  15185. std::unique_lock<std::mutex> lock(mtx);
  15186. release = true;
  15187. }
  15188. cv.notify_all();
  15189. // The pool must still accept and run tasks after the dynamic thread exited.
  15190. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15191. task_queue->shutdown();
  15192. EXPECT_EQ(3u, count.load());
  15193. }
  15194. TEST(TaskQueueTest, MaxQueuedRequests) {
  15195. static constexpr unsigned int qlimit{3};
  15196. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15197. std::condition_variable sem_cv;
  15198. std::mutex sem_mtx;
  15199. int credits = 0;
  15200. bool queued;
  15201. /* Fill up the queue with tasks that will block until we give them credits to
  15202. * complete. */
  15203. for (unsigned int n = 0; n <= qlimit;) {
  15204. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15205. std::unique_lock<std::mutex> lock(sem_mtx);
  15206. while (credits <= 0) {
  15207. sem_cv.wait(lock);
  15208. }
  15209. /* Consume the credit and signal the test code if they are all gone. */
  15210. if (--credits == 0) { sem_cv.notify_one(); }
  15211. });
  15212. if (n < qlimit) {
  15213. /* The first qlimit enqueues must succeed. */
  15214. EXPECT_TRUE(queued);
  15215. } else {
  15216. /* The last one will succeed only when the worker thread
  15217. * starts and dequeues the first blocking task. Although
  15218. * not necessary for the correctness of this test, we sleep for
  15219. * a short while to avoid busy waiting. */
  15220. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15221. }
  15222. if (queued) { n++; }
  15223. }
  15224. /* Further enqueues must fail since the queue is full. */
  15225. for (auto i = 0; i < 4; i++) {
  15226. queued = task_queue->enqueue([] {});
  15227. EXPECT_FALSE(queued);
  15228. }
  15229. /* Give the credits to allow the previous tasks to complete. */
  15230. {
  15231. std::unique_lock<std::mutex> lock(sem_mtx);
  15232. credits += qlimit + 1;
  15233. }
  15234. sem_cv.notify_all();
  15235. /* Wait for all the credits to be consumed. */
  15236. {
  15237. std::unique_lock<std::mutex> lock(sem_mtx);
  15238. while (credits > 0) {
  15239. sem_cv.wait(lock);
  15240. }
  15241. }
  15242. /* Check that we are able again to enqueue at least qlimit tasks. */
  15243. for (unsigned int i = 0; i < qlimit; i++) {
  15244. queued = task_queue->enqueue([] {});
  15245. EXPECT_TRUE(queued);
  15246. }
  15247. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15248. task_queue->shutdown();
  15249. #else
  15250. EXPECT_NO_THROW(task_queue->shutdown());
  15251. #endif
  15252. }
  15253. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15254. Server svr;
  15255. std::string method;
  15256. std::string body;
  15257. auto has_content_length = false;
  15258. auto has_transfer_encoding = false;
  15259. std::atomic<int> bad_requests{0};
  15260. // Leftover body bytes get parsed as a malformed request and answered with
  15261. // 400
  15262. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15263. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15264. });
  15265. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15266. res.set_redirect("/down", StatusCode::SeeOther_303);
  15267. });
  15268. svr.Get("/down", [&](const Request &req, Response &res) {
  15269. method = req.method;
  15270. body = req.body;
  15271. has_content_length = req.has_header("Content-Length");
  15272. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15273. res.set_content("ok", "text/plain");
  15274. });
  15275. auto port = svr.bind_to_any_port(HOST);
  15276. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15277. auto se = detail::scope_exit([&] {
  15278. svr.stop();
  15279. thread.join();
  15280. ASSERT_FALSE(svr.is_running());
  15281. });
  15282. svr.wait_until_ready();
  15283. const std::string payload = "SECRET-BODY";
  15284. auto check = [&](Client &cli, const Result &res) {
  15285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15286. EXPECT_EQ(StatusCode::OK_200, res->status);
  15287. EXPECT_EQ("ok", res->body);
  15288. EXPECT_EQ("GET", method);
  15289. EXPECT_TRUE(body.empty());
  15290. EXPECT_FALSE(has_content_length);
  15291. EXPECT_FALSE(has_transfer_encoding);
  15292. // Nothing of the original body may be left on the connection
  15293. auto res2 = cli.Get("/down");
  15294. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15295. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15296. EXPECT_EQ("ok", res2->body);
  15297. EXPECT_EQ(0, bad_requests);
  15298. };
  15299. // With content length
  15300. {
  15301. Client cli(HOST, port);
  15302. cli.set_keep_alive(true);
  15303. cli.set_follow_location(true);
  15304. auto res = cli.Post(
  15305. "/up", payload.size(),
  15306. [&](size_t offset, size_t length, DataSink &sink) {
  15307. return sink.write(payload.data() + offset, length);
  15308. },
  15309. "text/plain");
  15310. check(cli, res);
  15311. }
  15312. // Without content length (chunked)
  15313. {
  15314. Client cli(HOST, port);
  15315. cli.set_keep_alive(true);
  15316. cli.set_follow_location(true);
  15317. auto res = cli.Post(
  15318. "/up",
  15319. [&](size_t /*offset*/, DataSink &sink) {
  15320. sink.write(payload.data(), payload.size());
  15321. sink.done();
  15322. return true;
  15323. },
  15324. "text/plain");
  15325. check(cli, res);
  15326. }
  15327. }
  15328. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15329. Server svr;
  15330. std::string target;
  15331. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15332. // Echo the still-encoded name back in the Location
  15333. const std::string prefix = "/start/";
  15334. res.status = StatusCode::Found_302;
  15335. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15336. });
  15337. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15338. target = req.target;
  15339. res.set_content("ok", "text/plain");
  15340. });
  15341. auto port = svr.bind_to_any_port(HOST);
  15342. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15343. auto se = detail::scope_exit([&] {
  15344. svr.stop();
  15345. thread.join();
  15346. ASSERT_FALSE(svr.is_running());
  15347. });
  15348. svr.wait_until_ready();
  15349. // Decoding the Location path would turn the first four into a path
  15350. // separator, a query delimiter, a fragment delimiter and a different
  15351. // percent-encoded octet. The rest must keep reaching the server as they are.
  15352. const std::vector<std::string> names = {
  15353. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15354. };
  15355. for (auto path_encode : {true, false}) {
  15356. Client cli(HOST, port);
  15357. cli.set_follow_location(true);
  15358. cli.set_path_encode(path_encode);
  15359. for (const auto &name : names) {
  15360. target.clear();
  15361. auto res = cli.Get("/start/" + name);
  15362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15363. EXPECT_EQ(StatusCode::OK_200, res->status);
  15364. EXPECT_EQ("/dest/" + name, target);
  15365. }
  15366. }
  15367. }
  15368. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15369. Server svr;
  15370. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15371. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15372. });
  15373. svr.Get("/hello", [](const Request &req, Response &res) {
  15374. res.set_content(req.get_param_value("key"), "text/plain");
  15375. });
  15376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15377. auto se = detail::scope_exit([&] {
  15378. svr.stop();
  15379. thread.join();
  15380. ASSERT_FALSE(svr.is_running());
  15381. });
  15382. svr.wait_until_ready();
  15383. {
  15384. Client cli(HOST, PORT);
  15385. cli.set_follow_location(true);
  15386. auto res = cli.Get("/");
  15387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15388. EXPECT_EQ(StatusCode::OK_200, res->status);
  15389. EXPECT_EQ("val&key2=val2", res->body);
  15390. }
  15391. }
  15392. #endif
  15393. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15394. Server svr;
  15395. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15396. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15397. });
  15398. svr.Get("/hello", [](const Request &req, Response &res) {
  15399. res.set_content(req.get_param_value("key"), "text/plain");
  15400. });
  15401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15402. auto se = detail::scope_exit([&] {
  15403. svr.stop();
  15404. thread.join();
  15405. ASSERT_FALSE(svr.is_running());
  15406. });
  15407. svr.wait_until_ready();
  15408. {
  15409. Client cli(HOST, PORT);
  15410. cli.set_follow_location(true);
  15411. auto res = cli.Get("/");
  15412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15413. EXPECT_EQ(StatusCode::OK_200, res->status);
  15414. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15415. }
  15416. }
  15417. TEST(RedirectTest, RedirectWithPlusInPath) {
  15418. Server svr;
  15419. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15420. res.set_redirect("/a+b");
  15421. });
  15422. // Route pattern uses regex; escape + as \\+
  15423. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15424. res.set_content(req.path, "text/plain");
  15425. });
  15426. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15427. auto se = detail::scope_exit([&] {
  15428. svr.stop();
  15429. thread.join();
  15430. ASSERT_FALSE(svr.is_running());
  15431. });
  15432. svr.wait_until_ready();
  15433. {
  15434. Client cli(HOST, PORT);
  15435. cli.set_follow_location(true);
  15436. auto res = cli.Get("/");
  15437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15438. EXPECT_EQ(StatusCode::OK_200, res->status);
  15439. EXPECT_EQ("/a+b", res->body);
  15440. }
  15441. }
  15442. TEST(RedirectTest, ResolveRelativeLocation) {
  15443. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15444. const std::vector<std::pair<std::string, std::string>> cases = {
  15445. {"g", "/b/c/g"},
  15446. {"./g", "/b/c/g"},
  15447. {"g/", "/b/c/g/"},
  15448. {"?y", "/b/c/d;p?y"},
  15449. {"g?y", "/b/c/g?y"},
  15450. {"#s", "/b/c/d;p?q#s"},
  15451. {"g#s", "/b/c/g#s"},
  15452. {"g?y#s", "/b/c/g?y#s"},
  15453. {";x", "/b/c/;x"},
  15454. {"g;x", "/b/c/g;x"},
  15455. {".", "/b/c/"},
  15456. {"./", "/b/c/"},
  15457. {"..", "/b/"},
  15458. {"../", "/b/"},
  15459. {"../g", "/b/g"},
  15460. {"../..", "/"},
  15461. {"../../", "/"},
  15462. {"../../g", "/g"},
  15463. {"../../../g", "/g"},
  15464. {"g.", "/b/c/g."},
  15465. {".g", "/b/c/.g"},
  15466. {"g..", "/b/c/g.."},
  15467. {"..g", "/b/c/..g"},
  15468. {"./../g", "/b/g"},
  15469. {"./g/.", "/b/c/g/"},
  15470. {"g/./h", "/b/c/g/h"},
  15471. {"g/../h", "/b/c/h"},
  15472. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15473. {"g;x=1/../y", "/b/c/y"},
  15474. {"g?y/./x", "/b/c/g?y/./x"},
  15475. {"g#s/../x", "/b/c/g#s/../x"},
  15476. // Not relative-path references, so left for parse_url.
  15477. {"/g", "/g"},
  15478. {"//g", "//g"},
  15479. {"http://g/x", "http://g/x"},
  15480. {"g:h", "g:h"},
  15481. };
  15482. for (const auto &c : cases) {
  15483. EXPECT_EQ(c.second,
  15484. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15485. << c.first;
  15486. }
  15487. }
  15488. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15489. Server svr;
  15490. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15491. res.set_redirect(req.get_param_value("to"));
  15492. });
  15493. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15494. res.set_content(req.target, "text/plain");
  15495. });
  15496. svr.Get("/other", [](const Request &req, Response &res) {
  15497. res.set_content(req.target, "text/plain");
  15498. });
  15499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15500. auto se = detail::scope_exit([&] {
  15501. svr.stop();
  15502. thread.join();
  15503. ASSERT_FALSE(svr.is_running());
  15504. });
  15505. svr.wait_until_ready();
  15506. const std::vector<std::pair<std::string, std::string>> cases = {
  15507. {"next", "/dir/next"},
  15508. {"./next?x=1", "/dir/next?x=1"},
  15509. {"../other", "/other"},
  15510. };
  15511. for (const auto &c : cases) {
  15512. Client cli(HOST, PORT);
  15513. cli.set_follow_location(true);
  15514. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15515. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15516. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15517. EXPECT_EQ(c.second, res->body) << c.first;
  15518. }
  15519. }
  15520. #ifdef CPPHTTPLIB_SSL_ENABLED
  15521. TEST(RedirectTest, Issue2185_Online) {
  15522. SSLClient client("github.com");
  15523. client.set_follow_location(true);
  15524. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15525. "Coollab-Windows.zip");
  15526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15527. EXPECT_EQ(StatusCode::OK_200, res->status);
  15528. EXPECT_EQ(9920427U, res->body.size());
  15529. }
  15530. #endif
  15531. TEST(VulnerabilityTest, CRLFInjection) {
  15532. Server svr;
  15533. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15534. res.set_content("Hello 1", "text/plain");
  15535. });
  15536. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15537. res.set_content("Hello 2", "text/plain");
  15538. });
  15539. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15540. res.set_content("Hello 3", "text/plain");
  15541. });
  15542. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15543. res.set_content("Hello 4", "text/plain");
  15544. });
  15545. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15546. for (const auto &x : req.headers) {
  15547. auto key = x.first;
  15548. EXPECT_STRNE("evil", key.c_str());
  15549. }
  15550. });
  15551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15552. auto se = detail::scope_exit([&] {
  15553. svr.stop();
  15554. thread.join();
  15555. ASSERT_FALSE(svr.is_running());
  15556. });
  15557. svr.wait_until_ready();
  15558. {
  15559. Client cli(HOST, PORT);
  15560. cli.Post("/test1", "A=B",
  15561. "application/x-www-form-urlencoded\r\nevil: hello1");
  15562. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15563. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15564. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15565. }
  15566. }
  15567. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15568. auto server_thread = std::thread([] {
  15569. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15570. default_socket_options(srv);
  15571. sockaddr_in addr{};
  15572. addr.sin_family = AF_INET;
  15573. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15574. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15575. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15576. ::listen(srv, 1);
  15577. sockaddr_in cli_addr{};
  15578. socklen_t cli_len = sizeof(cli_addr);
  15579. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15580. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15581. std::string buf_all;
  15582. char buf[2048];
  15583. ssize_t n;
  15584. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15585. buf_all.append(buf, static_cast<size_t>(n));
  15586. size_t pos;
  15587. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15588. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15589. auto e = request_block.find("\r\n");
  15590. if (e != std::string::npos) {
  15591. auto request_line = request_block.substr(0, e);
  15592. std::string msg =
  15593. "CRLF injection detected in request line: '" + request_line + "'";
  15594. EXPECT_FALSE(true) << msg;
  15595. }
  15596. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15597. ::send(cli,
  15598. #ifdef _WIN32
  15599. static_cast<const char *>(resp.c_str()),
  15600. static_cast<int>(resp.size()),
  15601. #else
  15602. resp.c_str(), resp.size(),
  15603. #endif
  15604. 0);
  15605. buf_all.erase(0, pos + 4);
  15606. }
  15607. }
  15608. detail::close_socket(cli);
  15609. detail::close_socket(srv);
  15610. });
  15611. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15612. auto cli = Client("127.0.0.1", PORT + 1);
  15613. auto headers = Headers{
  15614. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15615. {"Connection", "keep-alive"}};
  15616. auto res = cli.Get("/hi", headers);
  15617. EXPECT_FALSE(res);
  15618. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15619. server_thread.join();
  15620. }
  15621. // A request rejected before any byte reaches the socket must fail right away
  15622. // instead of waiting for a response the server will never send.
  15623. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15624. // The kernel completes the TCP handshake from the listen backlog, so the
  15625. // client connects, but nothing ever reads, responds or closes.
  15626. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15627. default_socket_options(srv);
  15628. sockaddr_in addr{};
  15629. addr.sin_family = AF_INET;
  15630. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15631. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15632. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15633. ASSERT_EQ(0, ::listen(srv, 8));
  15634. auto cli = Client("127.0.0.1", PORT + 1);
  15635. cli.set_read_timeout(10, 0);
  15636. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15637. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15638. std::chrono::steady_clock::now() - start)
  15639. .count();
  15640. };
  15641. {
  15642. Request req;
  15643. req.method = "GE T";
  15644. req.path = "/";
  15645. auto start = std::chrono::steady_clock::now();
  15646. auto res = cli.send(req);
  15647. EXPECT_FALSE(res);
  15648. EXPECT_EQ(Error::Write, res.error());
  15649. EXPECT_LT(elapsed_ms(start), 1000);
  15650. }
  15651. {
  15652. auto start = std::chrono::steady_clock::now();
  15653. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15654. EXPECT_FALSE(res);
  15655. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15656. EXPECT_LT(elapsed_ms(start), 1000);
  15657. }
  15658. EXPECT_FALSE(cli.is_socket_open());
  15659. detail::close_socket(srv);
  15660. }
  15661. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15662. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15663. default_socket_options(srv);
  15664. sockaddr_in addr{};
  15665. addr.sin_family = AF_INET;
  15666. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15667. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15668. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15669. ASSERT_EQ(0, ::listen(srv, 1));
  15670. std::string received;
  15671. auto server_thread = std::thread([&] {
  15672. auto sock = ::accept(srv, nullptr, nullptr);
  15673. if (sock == INVALID_SOCKET) { return; }
  15674. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15675. char buf[2048];
  15676. ssize_t n;
  15677. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15678. received.append(buf, static_cast<size_t>(n));
  15679. }
  15680. detail::close_socket(sock);
  15681. });
  15682. {
  15683. auto cli = Client("127.0.0.1", PORT + 1);
  15684. // "Z" sorts after the default headers, so writing straight to the socket
  15685. // would have sent the request line and those headers before the rejection.
  15686. auto handle =
  15687. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15688. EXPECT_FALSE(handle.is_valid());
  15689. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15690. }
  15691. server_thread.join();
  15692. detail::close_socket(srv);
  15693. EXPECT_TRUE(received.empty()) << received;
  15694. }
  15695. TEST(PathParamsTest, StaticMatch) {
  15696. const auto pattern = "/users/all";
  15697. detail::PathParamsMatcher matcher(pattern);
  15698. Request request;
  15699. request.path = "/users/all";
  15700. ASSERT_TRUE(matcher.match(request));
  15701. std::unordered_map<std::string, std::string> expected_params = {};
  15702. EXPECT_EQ(request.path_params, expected_params);
  15703. }
  15704. TEST(PathParamsTest, StaticMismatch) {
  15705. const auto pattern = "/users/all";
  15706. detail::PathParamsMatcher matcher(pattern);
  15707. Request request;
  15708. request.path = "/users/1";
  15709. ASSERT_FALSE(matcher.match(request));
  15710. }
  15711. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15712. const auto pattern = "/users/:id/subscriptions";
  15713. detail::PathParamsMatcher matcher(pattern);
  15714. Request request;
  15715. request.path = "/users/42/subscriptions";
  15716. ASSERT_TRUE(matcher.match(request));
  15717. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15718. EXPECT_EQ(request.path_params, expected_params);
  15719. }
  15720. TEST(PathParamsTest, SingleParamInTheEnd) {
  15721. const auto pattern = "/users/:id";
  15722. detail::PathParamsMatcher matcher(pattern);
  15723. Request request;
  15724. request.path = "/users/24";
  15725. ASSERT_TRUE(matcher.match(request));
  15726. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15727. EXPECT_EQ(request.path_params, expected_params);
  15728. }
  15729. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15730. const auto pattern = "/users/:id/";
  15731. detail::PathParamsMatcher matcher(pattern);
  15732. Request request;
  15733. request.path = "/users/42/";
  15734. ASSERT_TRUE(matcher.match(request));
  15735. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15736. EXPECT_EQ(request.path_params, expected_params);
  15737. }
  15738. TEST(PathParamsTest, EmptyParam) {
  15739. const auto pattern = "/users/:id/";
  15740. detail::PathParamsMatcher matcher(pattern);
  15741. Request request;
  15742. request.path = "/users//";
  15743. ASSERT_TRUE(matcher.match(request));
  15744. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15745. EXPECT_EQ(request.path_params, expected_params);
  15746. }
  15747. TEST(PathParamsTest, FragmentMismatch) {
  15748. const auto pattern = "/users/:id/";
  15749. detail::PathParamsMatcher matcher(pattern);
  15750. Request request;
  15751. request.path = "/admins/24/";
  15752. ASSERT_FALSE(matcher.match(request));
  15753. }
  15754. TEST(PathParamsTest, ExtraFragments) {
  15755. const auto pattern = "/users/:id";
  15756. detail::PathParamsMatcher matcher(pattern);
  15757. Request request;
  15758. request.path = "/users/42/subscriptions";
  15759. ASSERT_FALSE(matcher.match(request));
  15760. }
  15761. TEST(PathParamsTest, MissingTrailingParam) {
  15762. const auto pattern = "/users/:id";
  15763. detail::PathParamsMatcher matcher(pattern);
  15764. Request request;
  15765. request.path = "/users";
  15766. ASSERT_FALSE(matcher.match(request));
  15767. }
  15768. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15769. const auto pattern = "/users/:id/subscriptions";
  15770. detail::PathParamsMatcher matcher(pattern);
  15771. Request request;
  15772. request.path = "/users/subscriptions";
  15773. ASSERT_FALSE(matcher.match(request));
  15774. }
  15775. TEST(PathParamsTest, MultipleParams) {
  15776. const auto pattern = "/users/:userid/subscriptions/:subid";
  15777. detail::PathParamsMatcher matcher(pattern);
  15778. Request request;
  15779. request.path = "/users/42/subscriptions/2";
  15780. ASSERT_TRUE(matcher.match(request));
  15781. std::unordered_map<std::string, std::string> expected_params = {
  15782. {"userid", "42"}, {"subid", "2"}};
  15783. EXPECT_EQ(request.path_params, expected_params);
  15784. }
  15785. TEST(PathParamsTest, SequenceOfParams) {
  15786. const auto pattern = "/values/:x/:y/:z";
  15787. detail::PathParamsMatcher matcher(pattern);
  15788. Request request;
  15789. request.path = "/values/1/2/3";
  15790. ASSERT_TRUE(matcher.match(request));
  15791. std::unordered_map<std::string, std::string> expected_params = {
  15792. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15793. EXPECT_EQ(request.path_params, expected_params);
  15794. }
  15795. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15796. const auto pattern = "/prefix:suffix";
  15797. detail::PathParamsMatcher matcher(pattern);
  15798. Request request;
  15799. request.path = "/prefix:suffix";
  15800. ASSERT_TRUE(matcher.match(request));
  15801. const std::unordered_map<std::string, std::string> expected_params = {};
  15802. EXPECT_EQ(request.path_params, expected_params);
  15803. }
  15804. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15805. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15806. // calling thread's stack on a long enough path for a quantified pattern;
  15807. // RegexMatcher must refuse to run regex matching on paths beyond
  15808. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15809. detail::RegexMatcher matcher("/files/(.*)");
  15810. Request within_limit;
  15811. within_limit.path = "/files/" + std::string(10, 'A');
  15812. EXPECT_TRUE(matcher.match(within_limit));
  15813. Request over_limit;
  15814. over_limit.path =
  15815. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15816. EXPECT_FALSE(matcher.match(over_limit));
  15817. }
  15818. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15819. Server svr;
  15820. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15821. res.set_content("ok", "text/plain");
  15822. });
  15823. auto port = svr.bind_to_any_port(HOST);
  15824. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15825. auto se = detail::scope_exit([&] {
  15826. svr.stop();
  15827. thread.join();
  15828. ASSERT_FALSE(svr.is_running());
  15829. });
  15830. svr.wait_until_ready();
  15831. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15832. // request URI limit; this used to be able to crash the process.
  15833. std::string path =
  15834. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15835. std::string req = "GET " + path +
  15836. " HTTP/1.1\r\n"
  15837. "Host: " +
  15838. std::string(HOST) + ":" + std::to_string(port) +
  15839. "\r\n"
  15840. "Connection: close\r\n"
  15841. "\r\n";
  15842. std::string response;
  15843. ASSERT_TRUE(send_request(5, req, &response, port));
  15844. EXPECT_NE(std::string::npos, response.find("404"));
  15845. }
  15846. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15847. Server svr;
  15848. auto handler = [](const Request & /*req*/, Response &res) {
  15849. res.set_content("hit", "text/plain");
  15850. };
  15851. // No regex metacharacter, so this one is compared literally
  15852. svr.Get("/literal/route", handler);
  15853. // '.' is a regex metacharacter, so this one must keep regex semantics
  15854. svr.Get("/a.c", handler);
  15855. auto port = svr.bind_to_any_port(HOST);
  15856. std::thread t([&]() { svr.listen_after_bind(); });
  15857. auto se = detail::scope_exit([&] {
  15858. svr.stop();
  15859. t.join();
  15860. ASSERT_FALSE(svr.is_running());
  15861. });
  15862. svr.wait_until_ready();
  15863. Client cli(HOST, port);
  15864. struct {
  15865. const char *path;
  15866. int status;
  15867. } cases[] = {
  15868. {"/literal/route", StatusCode::OK_200},
  15869. {"/literal/routes", StatusCode::NotFound_404},
  15870. {"/literal/rout", StatusCode::NotFound_404},
  15871. {"/abc", StatusCode::OK_200},
  15872. {"/a.c", StatusCode::OK_200},
  15873. };
  15874. for (const auto &x : cases) {
  15875. auto res = cli.Get(x.path);
  15876. ASSERT_TRUE(res) << x.path;
  15877. EXPECT_EQ(x.status, res->status) << x.path;
  15878. }
  15879. }
  15880. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15881. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15882. // from exhausting the stack, so it must only constrain routes that actually
  15883. // run a regular expression. A literal route is matched by comparison and
  15884. // stays usable at any length.
  15885. Server svr;
  15886. const std::string pattern =
  15887. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15888. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15889. res.set_content("hit", "text/plain");
  15890. });
  15891. auto port = svr.bind_to_any_port(HOST);
  15892. std::thread t([&]() { svr.listen_after_bind(); });
  15893. auto se = detail::scope_exit([&] {
  15894. svr.stop();
  15895. t.join();
  15896. ASSERT_FALSE(svr.is_running());
  15897. });
  15898. svr.wait_until_ready();
  15899. Client cli(HOST, port);
  15900. auto res = cli.Get(pattern);
  15901. ASSERT_TRUE(res);
  15902. EXPECT_EQ(StatusCode::OK_200, res->status);
  15903. }
  15904. TEST(ParseUrlTest, VariousPatterns) {
  15905. {
  15906. detail::UrlComponents uc;
  15907. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15908. EXPECT_EQ("http", uc.scheme);
  15909. EXPECT_EQ("example.com", uc.host);
  15910. EXPECT_EQ("8080", uc.port);
  15911. EXPECT_EQ("/path", uc.path);
  15912. EXPECT_EQ("?q=1", uc.query);
  15913. }
  15914. {
  15915. detail::UrlComponents uc;
  15916. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15917. EXPECT_EQ("https", uc.scheme);
  15918. EXPECT_EQ("example.com", uc.host);
  15919. EXPECT_TRUE(uc.port.empty());
  15920. EXPECT_EQ("/path", uc.path);
  15921. }
  15922. {
  15923. detail::UrlComponents uc;
  15924. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15925. EXPECT_EQ("::1", uc.host);
  15926. EXPECT_EQ("8080", uc.port);
  15927. EXPECT_EQ("/path", uc.path);
  15928. }
  15929. {
  15930. detail::UrlComponents uc;
  15931. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15932. }
  15933. {
  15934. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15935. // the path while the connection still targets the bracketed host.
  15936. detail::UrlComponents uc;
  15937. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15938. }
  15939. {
  15940. detail::UrlComponents uc;
  15941. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15942. }
  15943. {
  15944. detail::UrlComponents uc;
  15945. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15946. EXPECT_EQ("::1", uc.host);
  15947. EXPECT_TRUE(uc.port.empty());
  15948. EXPECT_EQ("/path", uc.path);
  15949. }
  15950. {
  15951. detail::UrlComponents uc;
  15952. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15953. EXPECT_TRUE(uc.scheme.empty());
  15954. EXPECT_EQ("example.com", uc.host);
  15955. EXPECT_EQ("/path", uc.path);
  15956. EXPECT_EQ("?q=1", uc.query);
  15957. }
  15958. {
  15959. detail::UrlComponents uc;
  15960. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15961. EXPECT_TRUE(uc.host.empty());
  15962. EXPECT_EQ("/path", uc.path);
  15963. EXPECT_EQ("?q=1", uc.query);
  15964. }
  15965. {
  15966. detail::UrlComponents uc;
  15967. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15968. EXPECT_EQ("example.com", uc.host);
  15969. EXPECT_EQ("8080", uc.port);
  15970. }
  15971. {
  15972. // Unix socket path — must not be parsed as host
  15973. detail::UrlComponents uc;
  15974. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15975. EXPECT_TRUE(uc.host.empty());
  15976. }
  15977. {
  15978. detail::UrlComponents uc;
  15979. ASSERT_TRUE(detail::parse_url("", uc));
  15980. EXPECT_TRUE(uc.host.empty());
  15981. EXPECT_TRUE(uc.path.empty());
  15982. }
  15983. {
  15984. detail::UrlComponents uc;
  15985. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15986. }
  15987. {
  15988. detail::UrlComponents uc;
  15989. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15990. }
  15991. {
  15992. // Accepted by parse_url; callers restrict to http/https
  15993. detail::UrlComponents uc;
  15994. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15995. EXPECT_EQ("ftp", uc.scheme);
  15996. }
  15997. {
  15998. detail::UrlComponents uc;
  15999. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16000. }
  16001. {
  16002. detail::UrlComponents uc;
  16003. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16004. }
  16005. }
  16006. TEST(ParseUrlTest, FragmentHandling) {
  16007. {
  16008. detail::UrlComponents uc;
  16009. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16010. EXPECT_EQ("/path", uc.path);
  16011. EXPECT_TRUE(uc.query.empty());
  16012. }
  16013. {
  16014. detail::UrlComponents uc;
  16015. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16016. EXPECT_TRUE(uc.path.empty());
  16017. EXPECT_TRUE(uc.query.empty());
  16018. }
  16019. }
  16020. TEST(ParseUrlTest, UserinfoHandling) {
  16021. // Userinfo with @ but no colon — host includes @
  16022. detail::UrlComponents uc;
  16023. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16024. EXPECT_EQ("user@host.com", uc.host);
  16025. EXPECT_EQ("/path", uc.path);
  16026. }
  16027. TEST(ParseUrlTest, IPv6EdgeCases) {
  16028. {
  16029. detail::UrlComponents uc;
  16030. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16031. EXPECT_TRUE(uc.scheme.empty());
  16032. EXPECT_EQ("::1", uc.host);
  16033. EXPECT_EQ("8080", uc.port);
  16034. }
  16035. {
  16036. // Zone ID '%25' is not in [a-fA-F0-9:]
  16037. detail::UrlComponents uc;
  16038. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16039. }
  16040. }
  16041. TEST(ParseUrlTest, SchemeEdgeCases) {
  16042. {
  16043. detail::UrlComponents uc;
  16044. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16045. }
  16046. {
  16047. detail::UrlComponents uc;
  16048. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16049. }
  16050. {
  16051. detail::UrlComponents uc;
  16052. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16053. }
  16054. }
  16055. TEST(ParseUrlTest, PortEdgeCases) {
  16056. {
  16057. detail::UrlComponents uc;
  16058. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16059. EXPECT_TRUE(uc.port.empty());
  16060. EXPECT_EQ("/path", uc.path);
  16061. }
  16062. {
  16063. // parse_url accepts any port string; validation is done by parse_port
  16064. detail::UrlComponents uc;
  16065. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16066. EXPECT_EQ("abc", uc.port);
  16067. }
  16068. }
  16069. TEST(ParseUrlTest, WebSocketPatterns) {
  16070. {
  16071. detail::UrlComponents uc;
  16072. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16073. EXPECT_EQ("ws", uc.scheme);
  16074. EXPECT_EQ("echo.example.com", uc.host);
  16075. EXPECT_EQ("8080", uc.port);
  16076. EXPECT_EQ("/ws", uc.path);
  16077. }
  16078. {
  16079. detail::UrlComponents uc;
  16080. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16081. EXPECT_EQ("wss", uc.scheme);
  16082. EXPECT_EQ("echo.example.com", uc.host);
  16083. EXPECT_TRUE(uc.port.empty());
  16084. EXPECT_EQ("/ws", uc.path);
  16085. }
  16086. }
  16087. TEST(ParseUrlTest, QueryOnly) {
  16088. detail::UrlComponents uc;
  16089. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16090. EXPECT_TRUE(uc.host.empty());
  16091. EXPECT_TRUE(uc.path.empty());
  16092. EXPECT_EQ("?q=1&r=2", uc.query);
  16093. }
  16094. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16095. detail::UrlComponents uc;
  16096. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16097. EXPECT_TRUE(uc.scheme.empty());
  16098. EXPECT_EQ("example.com", uc.host);
  16099. EXPECT_EQ("443", uc.port);
  16100. EXPECT_EQ("/path", uc.path);
  16101. }
  16102. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16103. // If ipv6 regex working, regex match codepath is taken.
  16104. // else port will default to 80 in Client impl
  16105. int clientImplMagicPort = 80;
  16106. int port = 4321;
  16107. // above ports must be different to avoid false negative
  16108. EXPECT_NE(clientImplMagicPort, port);
  16109. std::string ipV6TestURL = "http://[ff06::c3]";
  16110. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16111. CLIENT_PRIVATE_KEY_FILE);
  16112. EXPECT_EQ(cli.port(), port);
  16113. }
  16114. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16115. auto file_path = "./www/dir/index.html";
  16116. auto dir_path = "./www/dir";
  16117. detail::FileStat stat_file(file_path);
  16118. EXPECT_TRUE(stat_file.is_file());
  16119. EXPECT_FALSE(stat_file.is_dir());
  16120. detail::FileStat stat_dir(dir_path);
  16121. EXPECT_FALSE(stat_dir.is_file());
  16122. EXPECT_TRUE(stat_dir.is_dir());
  16123. }
  16124. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16125. // IPv4 with default HTTP port (80)
  16126. EXPECT_EQ("example.com",
  16127. detail::make_host_and_port_string("example.com", 80, false));
  16128. // IPv4 with default HTTPS port (443)
  16129. EXPECT_EQ("example.com",
  16130. detail::make_host_and_port_string("example.com", 443, true));
  16131. // IPv4 with non-default HTTP port
  16132. EXPECT_EQ("example.com:8080",
  16133. detail::make_host_and_port_string("example.com", 8080, false));
  16134. // IPv4 with non-default HTTPS port
  16135. EXPECT_EQ("example.com:8443",
  16136. detail::make_host_and_port_string("example.com", 8443, true));
  16137. // IPv6 with default HTTP port (80)
  16138. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16139. // IPv6 with default HTTPS port (443)
  16140. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16141. // IPv6 with non-default HTTP port
  16142. EXPECT_EQ("[::1]:8080",
  16143. detail::make_host_and_port_string("::1", 8080, false));
  16144. // IPv6 with non-default HTTPS port
  16145. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16146. // IPv6 full address with default port
  16147. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16148. detail::make_host_and_port_string(
  16149. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16150. // IPv6 full address with non-default port
  16151. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16152. detail::make_host_and_port_string(
  16153. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16154. // IPv6 localhost with non-default port
  16155. EXPECT_EQ("[::1]:3000",
  16156. detail::make_host_and_port_string("::1", 3000, false));
  16157. // IPv6 with zone ID (link-local address) with default port
  16158. EXPECT_EQ("[fe80::1%eth0]",
  16159. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16160. // IPv6 with zone ID (link-local address) with non-default port
  16161. EXPECT_EQ("[fe80::1%eth0]:8080",
  16162. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16163. // Edge case: Port 443 with is_ssl=false (should add port)
  16164. EXPECT_EQ("example.com:443",
  16165. detail::make_host_and_port_string("example.com", 443, false));
  16166. // Edge case: Port 80 with is_ssl=true (should add port)
  16167. EXPECT_EQ("example.com:80",
  16168. detail::make_host_and_port_string("example.com", 80, true));
  16169. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16170. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16171. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16172. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16173. // Security fix: Already bracketed IPv6 should not get double brackets
  16174. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16175. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16176. EXPECT_EQ("[::1]:8080",
  16177. detail::make_host_and_port_string("[::1]", 8080, false));
  16178. EXPECT_EQ("[2001:db8::1]:8080",
  16179. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16180. EXPECT_EQ("[fe80::1%eth0]",
  16181. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16182. EXPECT_EQ("[fe80::1%eth0]:8080",
  16183. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16184. // Edge case: Empty host (should return as-is)
  16185. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16186. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16187. // This is a known limitation but shouldn't crash
  16188. EXPECT_EQ("[host:name]",
  16189. detail::make_host_and_port_string("host:name", 80, false));
  16190. // Port number edge cases (no validation, but should not crash)
  16191. EXPECT_EQ("example.com:0",
  16192. detail::make_host_and_port_string("example.com", 0, false));
  16193. EXPECT_EQ("example.com:-1",
  16194. detail::make_host_and_port_string("example.com", -1, false));
  16195. EXPECT_EQ("example.com:65535",
  16196. detail::make_host_and_port_string("example.com", 65535, false));
  16197. EXPECT_EQ("example.com:65536",
  16198. detail::make_host_and_port_string("example.com", 65536, false));
  16199. }
  16200. #ifdef CPPHTTPLIB_SSL_ENABLED
  16201. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16202. httplib::SSLClient cli("roblox.com", 443);
  16203. cli.set_follow_location(true);
  16204. auto res = cli.Get("/");
  16205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16206. EXPECT_EQ(StatusCode::OK_200, res->status);
  16207. }
  16208. #endif
  16209. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16210. Server svr;
  16211. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16212. EXPECT_EQ(res.status, 400);
  16213. });
  16214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16215. auto se = detail::scope_exit([&] {
  16216. svr.stop();
  16217. thread.join();
  16218. ASSERT_FALSE(svr.is_running());
  16219. });
  16220. svr.wait_until_ready();
  16221. Client cli(HOST, PORT);
  16222. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16223. }
  16224. TEST(InvalidHeaderCharsTest, is_field_name) {
  16225. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16226. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16227. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16228. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16229. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16230. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16231. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16232. EXPECT_FALSE(detail::fields::is_field_name(""));
  16233. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16234. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16235. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16236. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16237. }
  16238. TEST(InvalidHeaderCharsTest, is_field_value) {
  16239. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16240. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16241. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16242. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16243. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16244. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16245. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16246. EXPECT_TRUE(detail::fields::is_field_value(""));
  16247. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16248. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16249. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16250. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16251. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16252. }
  16253. TEST(InvalidHeaderCharsTest, OnServer) {
  16254. Server svr;
  16255. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16256. std::string header = "Not Set";
  16257. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16258. res.set_header(header, "value");
  16259. res.set_content("Page Content Page Content", "text/plain");
  16260. });
  16261. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16262. std::string header = "Not Set";
  16263. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16264. res.set_header("X-Test", header);
  16265. res.set_content("Page Content Page Content", "text/plain");
  16266. });
  16267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16268. auto se = detail::scope_exit([&] {
  16269. svr.stop();
  16270. thread.join();
  16271. ASSERT_FALSE(svr.is_running());
  16272. });
  16273. svr.wait_until_ready();
  16274. Client cli(HOST, PORT);
  16275. {
  16276. auto res = cli.Get(
  16277. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16279. EXPECT_EQ("Page Content Page Content", res->body);
  16280. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16281. }
  16282. {
  16283. auto res = cli.Get(
  16284. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16286. EXPECT_EQ("Page Content Page Content", res->body);
  16287. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16288. }
  16289. }
  16290. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16291. auto handled = false;
  16292. Server svr;
  16293. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16294. thread t = thread([&] { svr.listen(HOST, PORT); });
  16295. auto se = detail::scope_exit([&] {
  16296. svr.stop();
  16297. t.join();
  16298. ASSERT_FALSE(svr.is_running());
  16299. ASSERT_FALSE(handled);
  16300. });
  16301. svr.wait_until_ready();
  16302. auto req = "POST /test HTTP/1.1\r\n"
  16303. "Content-Length: x\r\n"
  16304. "\r\n";
  16305. std::string response;
  16306. ASSERT_TRUE(send_request(1, req, &response));
  16307. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16308. response.substr(0, response.find("\r\n")));
  16309. }
  16310. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16311. // case-insensitive, and a server that receives a 100-continue expectation in
  16312. // an HTTP/1.0 request MUST ignore it.
  16313. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16314. std::string response;
  16315. ASSERT_TRUE(send_request(1, req, &response, port));
  16316. *got_100 = response.find("100 Continue") != std::string::npos;
  16317. }
  16318. class ExpectTokenTest : public ::testing::Test {
  16319. protected:
  16320. void SetUp() override {
  16321. svr_.Post("/p", [](const Request &, Response &res) {
  16322. res.set_content("ok", "text/plain");
  16323. });
  16324. port_ = svr_.bind_to_any_port(HOST);
  16325. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16326. svr_.wait_until_ready();
  16327. }
  16328. void TearDown() override {
  16329. svr_.stop();
  16330. if (thread_.joinable()) { thread_.join(); }
  16331. }
  16332. std::string request(const char *version, const char *expect_value) const {
  16333. return std::string("POST /p ") + version +
  16334. "\r\n"
  16335. "Host: localhost\r\n"
  16336. "Content-Length: 2\r\n"
  16337. "Connection: close\r\n"
  16338. "Expect: " +
  16339. expect_value +
  16340. "\r\n"
  16341. "\r\n"
  16342. "hi";
  16343. }
  16344. Server svr_;
  16345. int port_ = 0;
  16346. thread thread_;
  16347. };
  16348. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16349. bool got_100 = false;
  16350. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16351. EXPECT_TRUE(got_100);
  16352. }
  16353. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16354. bool got_100 = true;
  16355. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16356. EXPECT_FALSE(got_100);
  16357. }
  16358. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16359. bool got_100 = false;
  16360. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16361. EXPECT_TRUE(got_100);
  16362. }
  16363. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16364. bool got_100 = false;
  16365. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16366. EXPECT_TRUE(got_100);
  16367. }
  16368. // `100 Continue` is sent only when the server starts reading the body, so a
  16369. // request rejected before that never invites the client to send it. The
  16370. // requests below carry the expectation but withhold the body, as a client
  16371. // waiting for `100 Continue` would.
  16372. // A POST that expects `100 Continue` and withholds its two-byte body.
  16373. static std::string expect_headers_only(const std::string &path) {
  16374. return "POST " + path +
  16375. " HTTP/1.1\r\n"
  16376. "Host: localhost\r\n"
  16377. "Content-Length: 2\r\n"
  16378. "Expect: 100-continue\r\n"
  16379. "\r\n";
  16380. }
  16381. class ExpectLazyContinueTest : public ::testing::Test {
  16382. protected:
  16383. void SetUp() override {
  16384. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16385. if (req.path == "/pre-routing") {
  16386. res.status = StatusCode::Unauthorized_401;
  16387. return Server::HandlerResponse::Handled;
  16388. }
  16389. return Server::HandlerResponse::Unhandled;
  16390. });
  16391. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16392. if (req.matched_route == "/pre-request") {
  16393. res.status = StatusCode::Forbidden_403;
  16394. return Server::HandlerResponse::Handled;
  16395. }
  16396. return Server::HandlerResponse::Unhandled;
  16397. });
  16398. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16399. res.set_content("ok", "text/plain");
  16400. });
  16401. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16402. res.set_content("ok", "text/plain");
  16403. });
  16404. svr_.Post("/reader-used", [](const Request &, Response &res,
  16405. const ContentReader &content_reader) {
  16406. std::string body;
  16407. content_reader([&](const char *data, size_t len) {
  16408. body.append(data, len);
  16409. return true;
  16410. });
  16411. res.set_content(body, "text/plain");
  16412. });
  16413. svr_.Post("/reader-unused",
  16414. [](const Request &, Response &res, const ContentReader &) {
  16415. res.set_content("ignored", "text/plain");
  16416. });
  16417. port_ = svr_.bind_to_any_port(HOST);
  16418. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16419. svr_.wait_until_ready();
  16420. }
  16421. void TearDown() override {
  16422. svr_.stop();
  16423. if (thread_.joinable()) { thread_.join(); }
  16424. }
  16425. // Sends `req` and reads until the server closes the connection. Returns
  16426. // false if the read had to wait for the client-side timeout instead.
  16427. bool send_until_closed(const std::string &req, std::string *resp) const {
  16428. auto start = std::chrono::steady_clock::now();
  16429. if (!send_request(3, req, resp, port_)) { return false; }
  16430. auto elapsed = std::chrono::steady_clock::now() - start;
  16431. return elapsed < std::chrono::seconds(2);
  16432. }
  16433. // The final response comes without `100 Continue`, and the server closes
  16434. // the connection since the body may or may not follow.
  16435. void expect_final_without_interim(const std::string &path,
  16436. const char *status_line) const {
  16437. std::string resp;
  16438. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16439. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16440. EXPECT_EQ(0u, resp.find(status_line));
  16441. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16442. }
  16443. Server svr_;
  16444. int port_ = 0;
  16445. thread thread_;
  16446. };
  16447. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16448. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16449. }
  16450. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16451. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16452. }
  16453. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16454. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16455. }
  16456. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16457. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16458. }
  16459. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16460. // The body follows once `100 Continue` has had time to arrive.
  16461. auto req = expect_headers_only("/reader-used");
  16462. req.insert(req.size() - 2, "Connection: close\r\n");
  16463. std::string resp;
  16464. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16465. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16466. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16467. EXPECT_NE(std::string::npos, resp.find("hi"));
  16468. }
  16469. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16470. // Large enough for the client to add `Expect: 100-continue` itself.
  16471. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16472. std::atomic<bool> body_sent{false};
  16473. Client cli(HOST, port_);
  16474. auto res = cli.Post(
  16475. "/pre-request", length,
  16476. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16477. body_sent = true;
  16478. std::string chunk(len, 'x');
  16479. sink.write(chunk.data(), chunk.size());
  16480. return true;
  16481. },
  16482. "application/octet-stream");
  16483. ASSERT_TRUE(res);
  16484. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16485. EXPECT_FALSE(body_sent);
  16486. }
  16487. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16488. Server svr;
  16489. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16490. return StatusCode::ExpectationFailed_417;
  16491. });
  16492. svr.Post("/p", [](const Request &, Response &res) {
  16493. res.set_content("ok", "text/plain");
  16494. });
  16495. auto port = svr.bind_to_any_port(HOST);
  16496. thread t = thread([&] { svr.listen_after_bind(); });
  16497. auto se = detail::scope_exit([&] {
  16498. svr.stop();
  16499. t.join();
  16500. });
  16501. svr.wait_until_ready();
  16502. std::string resp;
  16503. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16504. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16505. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16506. // Exactly one response: the route handler must not run after the 417.
  16507. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16508. }
  16509. #ifndef _WIN32
  16510. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16511. static constexpr char reject[] = "Unauthorized";
  16512. static constexpr char accept[] = "Upload accepted";
  16513. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16514. Server svr;
  16515. svr.set_expect_100_continue_handler(
  16516. [](const Request & /*req*/, Response &res) {
  16517. res.status = StatusCode::Unauthorized_401;
  16518. res.set_content(reject, "text/plain");
  16519. return res.status;
  16520. });
  16521. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16522. res.set_content(accept, "text/plain");
  16523. });
  16524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16525. auto se = detail::scope_exit([&] {
  16526. svr.stop();
  16527. thread.join();
  16528. ASSERT_FALSE(svr.is_running());
  16529. });
  16530. svr.wait_until_ready();
  16531. {
  16532. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16533. curl_easy_init(), &curl_easy_cleanup};
  16534. ASSERT_NE(curl, nullptr);
  16535. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16536. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16537. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16538. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16539. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16540. &curl_slist_free_all};
  16541. ASSERT_NE(list, nullptr);
  16542. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16543. struct read_data {
  16544. size_t read_size;
  16545. size_t total_size;
  16546. } data = {0, total_size};
  16547. using read_callback_t =
  16548. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16549. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16550. void *userdata) -> size_t {
  16551. read_data *d = (read_data *)userdata;
  16552. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16553. std::fill_n(ptr, size * nmemb, 'A');
  16554. d->read_size += size * nmemb;
  16555. return size * nmemb;
  16556. };
  16557. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16558. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16559. std::vector<char> buffer;
  16560. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16561. using write_callback_t =
  16562. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16563. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16564. void *userdata) -> size_t {
  16565. std::vector<char> *buf = (std::vector<char> *)userdata;
  16566. buf->reserve(buf->size() + size * nmemb + 1);
  16567. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16568. return size * nmemb;
  16569. };
  16570. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16571. {
  16572. const auto res = curl_easy_perform(curl.get());
  16573. ASSERT_EQ(res, CURLE_OK);
  16574. }
  16575. {
  16576. auto response_code = long{};
  16577. const auto res =
  16578. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16579. ASSERT_EQ(res, CURLE_OK);
  16580. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16581. }
  16582. {
  16583. auto dl = curl_off_t{};
  16584. const auto res =
  16585. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16586. ASSERT_EQ(res, CURLE_OK);
  16587. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16588. }
  16589. {
  16590. buffer.push_back('\0');
  16591. ASSERT_STRCASEEQ(buffer.data(), reject);
  16592. }
  16593. }
  16594. }
  16595. #endif
  16596. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16597. // Regression test for #2458.
  16598. //
  16599. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16600. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16601. // ticket can make the client socket spuriously readable during the
  16602. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16603. // the client withholds the body and then blocks reading a response that never
  16604. // comes, failing with `Failed to read connection`.
  16605. //
  16606. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16607. // within the timeout. This raw OpenSSL server deliberately never sends
  16608. // `100 Continue`; the client must still deliver the body and receive 200.
  16609. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16610. signal(SIGPIPE, SIG_IGN);
  16611. const auto port = PORT + 4;
  16612. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16613. ASSERT_NE(srv, INVALID_SOCKET);
  16614. int opt = 1;
  16615. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16616. sockaddr_in addr{};
  16617. addr.sin_family = AF_INET;
  16618. addr.sin_port = htons(static_cast<uint16_t>(port));
  16619. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16620. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16621. ASSERT_EQ(0, ::listen(srv, 1));
  16622. std::atomic<size_t> server_body_bytes{0};
  16623. auto server_thread = std::thread([&] {
  16624. sockaddr_in cli_addr{};
  16625. socklen_t cli_len = sizeof(cli_addr);
  16626. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16627. if (cli == INVALID_SOCKET) { return; }
  16628. // Bound the lifetime of the server side so a buggy client (which never
  16629. // sends the body) cannot make this thread block forever on join.
  16630. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16631. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16632. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16633. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16634. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16635. SSL *ssl = SSL_new(ctx);
  16636. SSL_set_fd(ssl, static_cast<int>(cli));
  16637. if (SSL_accept(ssl) > 0) {
  16638. // Read the request headers. Reading here also flushes the TLS 1.3
  16639. // session tickets to the client. Deliberately do NOT send
  16640. // `100 Continue`.
  16641. std::string buf;
  16642. char tmp[1024];
  16643. while (buf.find("\r\n\r\n") == std::string::npos) {
  16644. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16645. if (n <= 0) { break; }
  16646. buf.append(tmp, static_cast<size_t>(n));
  16647. }
  16648. // A correct client sends the body now; count what arrives.
  16649. auto pos = buf.find("\r\n\r\n");
  16650. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16651. while (body < 4096) {
  16652. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16653. if (n <= 0) { break; }
  16654. body += static_cast<size_t>(n);
  16655. }
  16656. server_body_bytes = body;
  16657. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16658. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16659. SSL_shutdown(ssl);
  16660. }
  16661. SSL_free(ssl);
  16662. detail::close_socket(cli);
  16663. SSL_CTX_free(ctx);
  16664. });
  16665. auto se = detail::scope_exit([&] {
  16666. server_thread.join();
  16667. detail::close_socket(srv);
  16668. });
  16669. SSLClient cli("127.0.0.1", port);
  16670. cli.enable_server_certificate_verification(false);
  16671. cli.set_connection_timeout(5, 0);
  16672. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16673. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16674. std::string body(4096, 'A');
  16675. auto res = cli.Put("/api/test", body, "application/json");
  16676. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16677. EXPECT_EQ(StatusCode::OK_200, res->status);
  16678. EXPECT_EQ(body.size(), server_body_bytes.load());
  16679. }
  16680. #endif
  16681. template <typename S, typename C>
  16682. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16683. svr.Get("/stream", [&](const Request &, Response &res) {
  16684. auto data = new std::string("01234567890123456789");
  16685. res.set_content_provider(
  16686. data->size(), "text/plain",
  16687. [&, data](size_t offset, size_t length, DataSink &sink) {
  16688. const size_t DATA_CHUNK_SIZE = 4;
  16689. const auto &d = *data;
  16690. std::this_thread::sleep_for(std::chrono::seconds(1));
  16691. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16692. return true;
  16693. },
  16694. [data](bool success) {
  16695. EXPECT_FALSE(success);
  16696. delete data;
  16697. });
  16698. });
  16699. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16700. auto i = new size_t(0);
  16701. res.set_content_provider(
  16702. "text/plain",
  16703. [i](size_t, DataSink &sink) {
  16704. if (*i < 5) {
  16705. std::this_thread::sleep_for(std::chrono::seconds(1));
  16706. sink.write("abcd", 4);
  16707. (*i)++;
  16708. } else {
  16709. sink.done();
  16710. }
  16711. return true;
  16712. },
  16713. [i](bool success) {
  16714. EXPECT_FALSE(success);
  16715. delete i;
  16716. });
  16717. });
  16718. svr.Get("/chunked", [&](const Request &, Response &res) {
  16719. auto i = new size_t(0);
  16720. res.set_chunked_content_provider(
  16721. "text/plain",
  16722. [i](size_t, DataSink &sink) {
  16723. if (*i < 5) {
  16724. std::this_thread::sleep_for(std::chrono::seconds(1));
  16725. sink.os << "abcd";
  16726. (*i)++;
  16727. } else {
  16728. sink.done();
  16729. }
  16730. return true;
  16731. },
  16732. [i](bool success) {
  16733. EXPECT_FALSE(success);
  16734. delete i;
  16735. });
  16736. });
  16737. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16738. auto se = detail::scope_exit([&] {
  16739. svr.stop();
  16740. listen_thread.join();
  16741. ASSERT_FALSE(svr.is_running());
  16742. });
  16743. svr.wait_until_ready();
  16744. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16745. {
  16746. auto start = std::chrono::steady_clock::now();
  16747. auto res = cli.Get("/stream");
  16748. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16749. std::chrono::steady_clock::now() - start)
  16750. .count();
  16751. ASSERT_FALSE(res);
  16752. EXPECT_EQ(Error::Read, res.error());
  16753. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16754. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16755. }
  16756. {
  16757. auto start = std::chrono::steady_clock::now();
  16758. auto res = cli.Get("/stream_without_length");
  16759. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16760. std::chrono::steady_clock::now() - start)
  16761. .count();
  16762. ASSERT_FALSE(res);
  16763. EXPECT_EQ(Error::Read, res.error());
  16764. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16765. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16766. }
  16767. {
  16768. auto start = std::chrono::steady_clock::now();
  16769. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16770. EXPECT_EQ("abcd", string(data, data_length));
  16771. return true;
  16772. });
  16773. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16774. std::chrono::steady_clock::now() - start)
  16775. .count();
  16776. ASSERT_FALSE(res);
  16777. EXPECT_EQ(Error::Read, res.error());
  16778. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16779. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16780. }
  16781. }
  16782. TEST(MaxTimeoutTest, ContentStream) {
  16783. time_t timeout = 2000;
  16784. time_t threshold = 200;
  16785. Server svr;
  16786. Client cli("localhost", PORT);
  16787. max_timeout_test(svr, cli, timeout, threshold);
  16788. }
  16789. #ifdef CPPHTTPLIB_SSL_ENABLED
  16790. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16791. time_t timeout = 2000;
  16792. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16794. SSLClient cli("localhost", PORT);
  16795. cli.enable_server_certificate_verification(false);
  16796. max_timeout_test(svr, cli, timeout, threshold);
  16797. }
  16798. #endif
  16799. class EventDispatcher {
  16800. public:
  16801. EventDispatcher() {}
  16802. bool wait_event(DataSink *sink) {
  16803. unique_lock<mutex> lk(m_);
  16804. int id = id_;
  16805. // Wait with timeout to prevent hanging if client disconnects
  16806. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16807. [&] { return cid_ == id; })) {
  16808. return false; // Timeout occurred
  16809. }
  16810. sink->write(message_.data(), message_.size());
  16811. return true;
  16812. }
  16813. void send_event(const string &message) {
  16814. lock_guard<mutex> lk(m_);
  16815. cid_ = id_++;
  16816. message_ = message;
  16817. cv_.notify_all();
  16818. }
  16819. private:
  16820. mutex m_;
  16821. condition_variable cv_;
  16822. atomic_int id_{0};
  16823. atomic_int cid_{-1};
  16824. string message_;
  16825. };
  16826. TEST(ClientInThreadTest, Issue2068) {
  16827. EventDispatcher ed;
  16828. Server svr;
  16829. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16830. res.set_chunked_content_provider("text/event-stream",
  16831. [&](size_t /*offset*/, DataSink &sink) {
  16832. return ed.wait_event(&sink);
  16833. });
  16834. });
  16835. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16836. svr.wait_until_ready();
  16837. thread event_thread([&] {
  16838. int id = 0;
  16839. while (svr.is_running()) {
  16840. this_thread::sleep_for(chrono::milliseconds(500));
  16841. std::stringstream ss;
  16842. ss << "data: " << id << "\n\n";
  16843. ed.send_event(ss.str());
  16844. id++;
  16845. }
  16846. });
  16847. auto se = detail::scope_exit([&] {
  16848. svr.stop();
  16849. listen_thread.join();
  16850. event_thread.join();
  16851. ASSERT_FALSE(svr.is_running());
  16852. });
  16853. {
  16854. auto client = detail::make_unique<Client>(HOST, PORT);
  16855. client->set_read_timeout(std::chrono::minutes(10));
  16856. std::atomic<bool> stop{false};
  16857. std::thread t([&] {
  16858. client->Get("/event1",
  16859. [&](const char *, size_t) -> bool { return !stop; });
  16860. });
  16861. std::this_thread::sleep_for(std::chrono::seconds(2));
  16862. stop = true;
  16863. client->stop();
  16864. t.join();
  16865. // Reset client after thread has finished
  16866. client.reset();
  16867. }
  16868. }
  16869. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16870. auto handled = false;
  16871. Server svr;
  16872. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16874. auto se = detail::scope_exit([&] {
  16875. svr.stop();
  16876. t.join();
  16877. ASSERT_FALSE(svr.is_running());
  16878. ASSERT_FALSE(handled);
  16879. });
  16880. svr.wait_until_ready();
  16881. // Two Content-Length headers with different values — must be rejected
  16882. auto req = "POST /test HTTP/1.1\r\n"
  16883. "Content-Length: 5\r\n"
  16884. "Content-Length: 10\r\n"
  16885. "\r\n"
  16886. "hello";
  16887. std::string response;
  16888. ASSERT_TRUE(send_request(1, req, &response));
  16889. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16890. response.substr(0, response.find("\r\n")));
  16891. }
  16892. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16893. auto handled = false;
  16894. Server svr;
  16895. svr.Post("/test", [&](const Request &, Response &res) {
  16896. handled = true;
  16897. res.set_content("ok", "text/plain");
  16898. });
  16899. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16900. auto se = detail::scope_exit([&] {
  16901. svr.stop();
  16902. t.join();
  16903. ASSERT_FALSE(svr.is_running());
  16904. ASSERT_TRUE(handled);
  16905. });
  16906. svr.wait_until_ready();
  16907. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16908. auto req = "POST /test HTTP/1.1\r\n"
  16909. "Content-Length: 5\r\n"
  16910. "Content-Length: 5\r\n"
  16911. "\r\n"
  16912. "hello";
  16913. std::string response;
  16914. ASSERT_TRUE(send_request(1, req, &response));
  16915. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16916. }
  16917. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16918. Server svr;
  16919. svr.Get("/test", [](const Request &, Response &res) {
  16920. res.set_content("ok", "text/plain");
  16921. });
  16922. auto port = svr.bind_to_any_port(HOST);
  16923. thread t = thread([&] { svr.listen_after_bind(); });
  16924. auto se = detail::scope_exit([&] {
  16925. svr.stop();
  16926. t.join();
  16927. ASSERT_FALSE(svr.is_running());
  16928. });
  16929. svr.wait_until_ready();
  16930. auto status_line = [&](const std::string &host_lines) {
  16931. std::string res;
  16932. send_request(
  16933. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16934. &res, port);
  16935. return res.substr(0, res.find("\r\n"));
  16936. };
  16937. const char *accepted[] = {
  16938. "Host: localhost\r\n",
  16939. "Host: a.example:8080\r\n",
  16940. "Host: my_service\r\n",
  16941. "Host: [::1]:8080\r\n",
  16942. "Host: [fe80::1%25eth0]\r\n",
  16943. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16944. };
  16945. for (auto host_lines : accepted) {
  16946. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16947. }
  16948. const char *rejected[] = {
  16949. "Host: a.example\r\nHost: b.example\r\n",
  16950. "Host: a.example\r\nHost: a.example\r\n",
  16951. "Host: a@b.example\r\n",
  16952. "Host: a.example/b\r\n",
  16953. "Host: a.example\\b\r\n",
  16954. "Host: a.example?b\r\n",
  16955. "Host: a.example#b\r\n",
  16956. "Host: a.example b.example\r\n",
  16957. };
  16958. for (auto host_lines : rejected) {
  16959. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16960. << host_lines;
  16961. }
  16962. }
  16963. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16964. Server svr;
  16965. svr.Get("/", [](const Request &req, Response &res) {
  16966. EXPECT_EQ(2U, req.trailers.size());
  16967. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16968. // Denied
  16969. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16970. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16971. // Accepted
  16972. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16973. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16974. EXPECT_TRUE(req.has_trailer("X-World"));
  16975. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16976. res.set_content("ok", "text/plain");
  16977. });
  16978. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. t.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. const std::string req = "GET / HTTP/1.1\r\n"
  16986. "Transfer-Encoding: chunked\r\n"
  16987. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16988. "\r\n"
  16989. "0\r\n"
  16990. "Content-Length: 10\r\n"
  16991. "Host: internal.local\r\n"
  16992. "Content-Type: malicious/content\r\n"
  16993. "Cookie: any\r\n"
  16994. "Set-Cookie: any\r\n"
  16995. "X-Forwarded-For: attacker.com\r\n"
  16996. "X-Real-Ip: 1.1.1.1\r\n"
  16997. "X-Hello: hello\r\n"
  16998. "X-World: world\r\n"
  16999. "\r\n";
  17000. std::string res;
  17001. ASSERT_TRUE(send_request(1, req, &res));
  17002. }
  17003. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17004. // several field lines, and the combined value is what has to be parsed. A
  17005. // Trailer field split across lines therefore declares every name it lists;
  17006. // reading only the first line silently drops the trailers the later lines
  17007. // declare. The prohibited-trailer filter still applies to every line.
  17008. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17009. Server svr;
  17010. size_t observed_trailer_count = 0;
  17011. std::string observed_hello;
  17012. std::string observed_world;
  17013. bool observed_content_length = true;
  17014. svr.Get("/", [&](const Request &req, Response &res) {
  17015. observed_trailer_count = req.trailers.size();
  17016. observed_hello = req.get_trailer_value("X-Hello");
  17017. observed_world = req.get_trailer_value("X-World");
  17018. observed_content_length = req.has_trailer("Content-Length");
  17019. res.set_content("ok", "text/plain");
  17020. });
  17021. auto port = svr.bind_to_any_port(HOST);
  17022. thread t = thread([&]() { svr.listen_after_bind(); });
  17023. auto se = detail::scope_exit([&] {
  17024. svr.stop();
  17025. t.join();
  17026. ASSERT_FALSE(svr.is_running());
  17027. });
  17028. svr.wait_until_ready();
  17029. const std::string req = "GET / HTTP/1.1\r\n"
  17030. "Transfer-Encoding: chunked\r\n"
  17031. "Trailer: X-Hello\r\n"
  17032. "Trailer: X-World, Content-Length\r\n"
  17033. "\r\n"
  17034. "0\r\n"
  17035. "X-Hello: hello\r\n"
  17036. "X-World: world\r\n"
  17037. "Content-Length: 10\r\n"
  17038. "\r\n";
  17039. std::string res;
  17040. ASSERT_TRUE(send_request(1, req, &res, port));
  17041. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17042. // Accepted: both field lines contribute to the declared set
  17043. EXPECT_EQ(2U, observed_trailer_count);
  17044. EXPECT_EQ(observed_hello, "hello");
  17045. EXPECT_EQ(observed_world, "world");
  17046. // Denied: a prohibited name stays prohibited on a later field line
  17047. EXPECT_FALSE(observed_content_length);
  17048. }
  17049. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17050. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17051. // unbounded run of fields that are never declared, because the counter would
  17052. // only advance for declared fields.
  17053. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17054. Server svr;
  17055. bool handler_called = false;
  17056. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17057. handler_called = true;
  17058. res.set_content("ok", "text/plain");
  17059. });
  17060. auto port = svr.bind_to_any_port(HOST);
  17061. thread t = thread([&]() { svr.listen_after_bind(); });
  17062. auto se = detail::scope_exit([&] {
  17063. svr.stop();
  17064. t.join();
  17065. ASSERT_FALSE(svr.is_running());
  17066. });
  17067. svr.wait_until_ready();
  17068. // Declare nothing, then send far more undeclared trailer fields than the
  17069. // header-count limit. Parsing must stop and reject the request rather than
  17070. // read every line.
  17071. std::string req = "GET / HTTP/1.1\r\n"
  17072. "Transfer-Encoding: chunked\r\n"
  17073. "\r\n"
  17074. "0\r\n";
  17075. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17076. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17077. }
  17078. req += "\r\n";
  17079. std::string res;
  17080. ASSERT_TRUE(send_request(1, req, &res, port));
  17081. // The request is rejected before the handler runs.
  17082. EXPECT_FALSE(handler_called);
  17083. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17084. }
  17085. // The set of declared trailer names is capped so a peer cannot grow it without
  17086. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17087. // declared past the cap is not honored, even if the field is actually sent.
  17088. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17089. Server svr;
  17090. // One name inside the cap and one past it, so the test tracks the cap rather
  17091. // than a fixed count.
  17092. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17093. const std::string within_cap_name = "X-T-0";
  17094. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17095. bool observed_within_cap = false;
  17096. bool observed_past_cap = false;
  17097. svr.Get("/", [&](const Request &req, Response &res) {
  17098. observed_within_cap = req.has_trailer(within_cap_name);
  17099. observed_past_cap = req.has_trailer(past_cap_name);
  17100. res.set_content("ok", "text/plain");
  17101. });
  17102. auto port = svr.bind_to_any_port(HOST);
  17103. thread t = thread([&]() { svr.listen_after_bind(); });
  17104. auto se = detail::scope_exit([&] {
  17105. svr.stop();
  17106. t.join();
  17107. ASSERT_FALSE(svr.is_running());
  17108. });
  17109. svr.wait_until_ready();
  17110. // Declare more trailer names than the cap in a single Trailer field, then
  17111. // actually send the first (within the cap) and the last (past it).
  17112. std::string trailer_decl = "Trailer: ";
  17113. for (int i = 0; i < declared_count; i++) {
  17114. if (i != 0) { trailer_decl += ", "; }
  17115. trailer_decl += "X-T-" + std::to_string(i);
  17116. }
  17117. trailer_decl += "\r\n";
  17118. const std::string req = "GET / HTTP/1.1\r\n"
  17119. "Transfer-Encoding: chunked\r\n" +
  17120. trailer_decl +
  17121. "\r\n"
  17122. "0\r\n" +
  17123. within_cap_name + ": a\r\n" + past_cap_name +
  17124. ": b\r\n"
  17125. "\r\n";
  17126. std::string res;
  17127. ASSERT_TRUE(send_request(1, req, &res, port));
  17128. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17129. // A name within the cap is honored; one declared past the cap is dropped.
  17130. EXPECT_TRUE(observed_within_cap);
  17131. EXPECT_FALSE(observed_past_cap);
  17132. }
  17133. // A direct client that is not listed in trusted_proxies must not be able to
  17134. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17135. // the peer address on the actual TCP connection determines whether the
  17136. // header is honored.
  17137. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17138. Server svr;
  17139. // Deliberately does NOT include the loopback address the test client
  17140. // actually connects from, so the direct connection is not a trusted proxy.
  17141. svr.set_trusted_proxies({"203.0.113.66"});
  17142. std::string observed_remote_addr;
  17143. svr.Get("/ip", [&](const Request &req, Response &res) {
  17144. observed_remote_addr = req.remote_addr;
  17145. res.set_content("ok", "text/plain");
  17146. });
  17147. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17148. auto se = detail::scope_exit([&] {
  17149. svr.stop();
  17150. t.join();
  17151. ASSERT_FALSE(svr.is_running());
  17152. });
  17153. svr.wait_until_ready();
  17154. Client cli(HOST, PORT);
  17155. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17157. EXPECT_EQ(StatusCode::OK_200, res->status);
  17158. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17159. // ignored entirely and the real connection-level address retained.
  17160. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17161. observed_remote_addr == "127.0.0.1");
  17162. }
  17163. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17164. Server svr;
  17165. std::string observed_remote_addr;
  17166. std::string observed_xff;
  17167. svr.Get("/ip", [&](const Request &req, Response &res) {
  17168. observed_remote_addr = req.remote_addr;
  17169. observed_xff = req.get_header_value("X-Forwarded-For");
  17170. res.set_content("ok", "text/plain");
  17171. });
  17172. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17173. auto se = detail::scope_exit([&] {
  17174. svr.stop();
  17175. t.join();
  17176. ASSERT_FALSE(svr.is_running());
  17177. });
  17178. svr.wait_until_ready();
  17179. Client cli(HOST, PORT);
  17180. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17182. EXPECT_EQ(StatusCode::OK_200, res->status);
  17183. EXPECT_EQ(observed_xff, "203.0.113.66");
  17184. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17185. observed_remote_addr == "127.0.0.1");
  17186. }
  17187. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17188. Server svr;
  17189. svr.set_trusted_proxies({"203.0.113.66"});
  17190. std::string observed_remote_addr;
  17191. std::string observed_xff;
  17192. svr.Get("/ip", [&](const Request &req, Response &res) {
  17193. observed_remote_addr = req.remote_addr;
  17194. observed_xff = req.get_header_value("X-Forwarded-For");
  17195. res.set_content("ok", "text/plain");
  17196. });
  17197. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17198. auto se = detail::scope_exit([&] {
  17199. svr.stop();
  17200. t.join();
  17201. ASSERT_FALSE(svr.is_running());
  17202. });
  17203. svr.wait_until_ready();
  17204. Client cli(HOST, PORT);
  17205. auto res = cli.Get("/ip");
  17206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17207. EXPECT_EQ(StatusCode::OK_200, res->status);
  17208. EXPECT_EQ(observed_xff, "");
  17209. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17210. observed_remote_addr == "127.0.0.1");
  17211. }
  17212. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17213. Server svr;
  17214. // Include the loopback address the test client actually connects from, so
  17215. // the direct connection itself is recognized as the trusted proxy hop.
  17216. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17217. std::string observed_remote_addr;
  17218. std::string observed_xff;
  17219. svr.Get("/ip", [&](const Request &req, Response &res) {
  17220. observed_remote_addr = req.remote_addr;
  17221. observed_xff = req.get_header_value("X-Forwarded-For");
  17222. res.set_content("ok", "text/plain");
  17223. });
  17224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17225. auto se = detail::scope_exit([&] {
  17226. svr.stop();
  17227. t.join();
  17228. ASSERT_FALSE(svr.is_running());
  17229. });
  17230. svr.wait_until_ready();
  17231. Client cli(HOST, PORT);
  17232. auto res = cli.Get(
  17233. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17235. EXPECT_EQ(StatusCode::OK_200, res->status);
  17236. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17237. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17238. }
  17239. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17240. Server svr;
  17241. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17242. std::string observed_remote_addr;
  17243. std::string observed_xff;
  17244. svr.Get("/ip", [&](const Request &req, Response &res) {
  17245. observed_remote_addr = req.remote_addr;
  17246. observed_xff = req.get_header_value("X-Forwarded-For");
  17247. res.set_content("ok", "text/plain");
  17248. });
  17249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17250. auto se = detail::scope_exit([&] {
  17251. svr.stop();
  17252. t.join();
  17253. ASSERT_FALSE(svr.is_running());
  17254. });
  17255. svr.wait_until_ready();
  17256. Client cli(HOST, PORT);
  17257. auto res = cli.Get(
  17258. "/ip",
  17259. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17261. EXPECT_EQ(StatusCode::OK_200, res->status);
  17262. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17263. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17264. }
  17265. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17266. Server svr;
  17267. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17268. std::string observed_remote_addr;
  17269. std::string observed_xff;
  17270. svr.Get("/ip", [&](const Request &req, Response &res) {
  17271. observed_remote_addr = req.remote_addr;
  17272. observed_xff = req.get_header_value("X-Forwarded-For");
  17273. res.set_content("ok", "text/plain");
  17274. });
  17275. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17276. auto se = detail::scope_exit([&] {
  17277. svr.stop();
  17278. t.join();
  17279. ASSERT_FALSE(svr.is_running());
  17280. });
  17281. svr.wait_until_ready();
  17282. Client cli(HOST, PORT);
  17283. auto res = cli.Get(
  17284. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17286. EXPECT_EQ(StatusCode::OK_200, res->status);
  17287. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17288. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17289. // and must not be selected.
  17290. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17291. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17292. }
  17293. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17294. Server svr;
  17295. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17296. std::string observed_remote_addr;
  17297. svr.Get("/ip", [&](const Request &req, Response &res) {
  17298. observed_remote_addr = req.remote_addr;
  17299. res.set_content("ok", "text/plain");
  17300. });
  17301. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17302. auto se = detail::scope_exit([&] {
  17303. svr.stop();
  17304. t.join();
  17305. ASSERT_FALSE(svr.is_running());
  17306. });
  17307. svr.wait_until_ready();
  17308. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17309. // a forged address and the trusted proxy's own address; the forged value must
  17310. // not win over the address the trusted proxy actually recorded.
  17311. Client cli(HOST, PORT);
  17312. auto res = cli.Get(
  17313. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17315. EXPECT_EQ(StatusCode::OK_200, res->status);
  17316. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17317. }
  17318. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17319. Server svr;
  17320. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17321. std::string observed_remote_addr;
  17322. std::string observed_xff;
  17323. svr.Get("/ip", [&](const Request &req, Response &res) {
  17324. observed_remote_addr = req.remote_addr;
  17325. observed_xff = req.get_header_value("X-Forwarded-For");
  17326. res.set_content("ok", "text/plain");
  17327. });
  17328. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17329. auto se = detail::scope_exit([&] {
  17330. svr.stop();
  17331. t.join();
  17332. ASSERT_FALSE(svr.is_running());
  17333. });
  17334. svr.wait_until_ready();
  17335. Client cli(HOST, PORT);
  17336. auto res = cli.Get(
  17337. "/ip",
  17338. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17340. EXPECT_EQ(StatusCode::OK_200, res->status);
  17341. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17342. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17343. }
  17344. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17345. Server svr;
  17346. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17347. std::string observed_remote_addr;
  17348. std::string observed_xff;
  17349. svr.Get("/ip", [&](const Request &req, Response &res) {
  17350. observed_remote_addr = req.remote_addr;
  17351. observed_xff = req.get_header_value("X-Forwarded-For");
  17352. res.set_content("ok", "text/plain");
  17353. });
  17354. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17355. auto se = detail::scope_exit([&] {
  17356. svr.stop();
  17357. t.join();
  17358. ASSERT_FALSE(svr.is_running());
  17359. });
  17360. svr.wait_until_ready();
  17361. std::string raw_req =
  17362. "GET /ip HTTP/1.1\r\n"
  17363. "Host: localhost\r\n"
  17364. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17365. "Connection: close\r\n"
  17366. "\r\n";
  17367. std::string out;
  17368. ASSERT_TRUE(send_request(5, raw_req, &out));
  17369. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17370. // Header parser trims surrounding whitespace of the header value
  17371. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17372. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17373. }
  17374. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17375. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17376. // their own X-Forwarded-For as a separate field line rather than extending the
  17377. // one the client sent, so every occurrence has to be taken into account.
  17378. // Reading only the first one hands back the address the client chose.
  17379. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17380. Server svr;
  17381. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17382. std::string observed_remote_addr;
  17383. size_t observed_xff_count = 0;
  17384. svr.Get("/ip", [&](const Request &req, Response &res) {
  17385. observed_remote_addr = req.remote_addr;
  17386. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17387. res.set_content("ok", "text/plain");
  17388. });
  17389. auto port = svr.bind_to_any_port(HOST);
  17390. thread t = thread([&]() { svr.listen_after_bind(); });
  17391. auto se = detail::scope_exit([&] {
  17392. svr.stop();
  17393. t.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. svr.wait_until_ready();
  17397. // The client supplies the first field line; the trusted proxy appends the
  17398. // address it observed as a second one.
  17399. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17400. "Host: localhost\r\n"
  17401. "X-Forwarded-For: 1.2.3.4\r\n"
  17402. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17403. "Connection: close\r\n"
  17404. "\r\n";
  17405. std::string out;
  17406. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17407. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17408. EXPECT_EQ(observed_xff_count, 2U);
  17409. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17410. // The same chain spread over one field line per hop derives the same client
  17411. // address, i.e. the split and the comma-joined representations agree.
  17412. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17413. "Host: localhost\r\n"
  17414. "X-Forwarded-For: 1.2.3.4\r\n"
  17415. "X-Forwarded-For: 198.51.100.23\r\n"
  17416. "X-Forwarded-For: 192.0.2.45\r\n"
  17417. "Connection: close\r\n"
  17418. "\r\n";
  17419. out.clear();
  17420. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17421. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17422. EXPECT_EQ(observed_xff_count, 3U);
  17423. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17424. }
  17425. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17426. // crash the server (it used to call front() on an empty vector inside
  17427. // get_client_ip). The connection-level remote address must be retained instead.
  17428. static void run_malformed_xff_test(const std::string &xff_value) {
  17429. Server svr;
  17430. svr.set_trusted_proxies({"192.0.2.45"});
  17431. std::string observed_remote_addr;
  17432. svr.Get("/ip", [&](const Request &req, Response &res) {
  17433. observed_remote_addr = req.remote_addr;
  17434. res.set_content("ok", "text/plain");
  17435. });
  17436. int port = 0;
  17437. thread t = thread([&]() {
  17438. port = svr.bind_to_any_port(HOST);
  17439. svr.listen_after_bind();
  17440. });
  17441. auto se = detail::scope_exit([&] {
  17442. svr.stop();
  17443. t.join();
  17444. ASSERT_FALSE(svr.is_running());
  17445. });
  17446. svr.wait_until_ready();
  17447. Client cli(HOST, port);
  17448. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17450. EXPECT_EQ(StatusCode::OK_200, res->status);
  17451. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17452. observed_remote_addr == "127.0.0.1");
  17453. }
  17454. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17455. run_malformed_xff_test("");
  17456. }
  17457. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17458. run_malformed_xff_test(",");
  17459. }
  17460. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17461. run_malformed_xff_test(", , ,");
  17462. }
  17463. // The same rule applies to Accept: a request whose acceptable types are spread
  17464. // over several field lines must be negotiated against all of them.
  17465. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17466. // case-insensitive connection options. Comparing the whole field value against
  17467. // one option misses a client that sends several of them, and misses every
  17468. // casing but the one written in the comparison.
  17469. //
  17470. // Sends req, reads the response, then reuses the same socket for a second
  17471. // request to find out whether the server kept the connection.
  17472. static void probe_connection_reuse(int port, const std::string &req,
  17473. bool *announced_close, bool *reusable) {
  17474. auto error = Error::Success;
  17475. auto sock = detail::create_client_socket(
  17476. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17477. /*connection_timeout_sec=*/5, 0,
  17478. /*read_timeout_sec=*/1, 0,
  17479. /*write_timeout_sec=*/5, 0, std::string(), error);
  17480. ASSERT_NE(sock, INVALID_SOCKET);
  17481. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17482. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17483. "Host: localhost\r\n"
  17484. "Connection: close\r\n"
  17485. "\r\n";
  17486. std::string first_response;
  17487. std::string second_response;
  17488. detail::process_client_socket(
  17489. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17490. [&](Stream &strm) {
  17491. if (strm.write(req.data(), req.size()) !=
  17492. static_cast<ssize_t>(req.size())) {
  17493. return false;
  17494. }
  17495. char buf[512];
  17496. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17497. // Headers plus the two-byte body of the handler below
  17498. while (reader.getline()) {
  17499. first_response += reader.ptr();
  17500. if (first_response.find("ok") != std::string::npos) { break; }
  17501. }
  17502. if (strm.write(second.data(), second.size()) !=
  17503. static_cast<ssize_t>(second.size())) {
  17504. return true;
  17505. }
  17506. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17507. while (reader2.getline()) {
  17508. second_response += reader2.ptr();
  17509. if (second_response.find("ok") != std::string::npos) { break; }
  17510. }
  17511. return true;
  17512. });
  17513. *announced_close =
  17514. first_response.find("Connection: close") != std::string::npos;
  17515. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17516. }
  17517. class ConnectionTokenTest : public ::testing::Test {
  17518. protected:
  17519. void SetUp() override {
  17520. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17521. res.set_content("ok", "text/plain");
  17522. });
  17523. port_ = svr_.bind_to_any_port(HOST);
  17524. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17525. svr_.wait_until_ready();
  17526. }
  17527. void TearDown() override {
  17528. svr_.stop();
  17529. if (thread_.joinable()) { thread_.join(); }
  17530. }
  17531. Server svr_;
  17532. int port_ = 0;
  17533. thread thread_;
  17534. };
  17535. // "close" alongside another option still closes the connection, and the
  17536. // response says so rather than leaving the peer to discover it.
  17537. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17538. bool announced_close = false;
  17539. bool reusable = true;
  17540. probe_connection_reuse(port_,
  17541. "GET /keepalive HTTP/1.1\r\n"
  17542. "Host: localhost\r\n"
  17543. "Connection: keep-alive, close\r\n"
  17544. "\r\n",
  17545. &announced_close, &reusable);
  17546. EXPECT_TRUE(announced_close);
  17547. EXPECT_FALSE(reusable);
  17548. }
  17549. // "close" split over two field lines is the same list, so it is honored too.
  17550. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17551. bool announced_close = false;
  17552. bool reusable = true;
  17553. probe_connection_reuse(port_,
  17554. "GET /keepalive HTTP/1.1\r\n"
  17555. "Host: localhost\r\n"
  17556. "Connection: keep-alive\r\n"
  17557. "Connection: close\r\n"
  17558. "\r\n",
  17559. &announced_close, &reusable);
  17560. EXPECT_TRUE(announced_close);
  17561. EXPECT_FALSE(reusable);
  17562. }
  17563. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17564. // keep-alive in the spelling everyone actually sends keeps its connection.
  17565. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17566. bool announced_close = false;
  17567. bool reusable = false;
  17568. probe_connection_reuse(port_,
  17569. "GET /keepalive HTTP/1.0\r\n"
  17570. "Host: localhost\r\n"
  17571. "Connection: keep-alive\r\n"
  17572. "\r\n",
  17573. &announced_close, &reusable);
  17574. EXPECT_FALSE(announced_close);
  17575. EXPECT_TRUE(reusable);
  17576. }
  17577. // A token the value merely contains is not the token itself.
  17578. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17579. bool announced_close = false;
  17580. bool reusable = false;
  17581. probe_connection_reuse(port_,
  17582. "GET /keepalive HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Connection: notclose\r\n"
  17585. "\r\n",
  17586. &announced_close, &reusable);
  17587. EXPECT_FALSE(announced_close);
  17588. EXPECT_TRUE(reusable);
  17589. }
  17590. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17591. Server svr;
  17592. std::vector<std::string> observed_types;
  17593. svr.Get("/", [&](const Request &req, Response &res) {
  17594. observed_types = req.accept_content_types;
  17595. res.set_content("ok", "text/plain");
  17596. });
  17597. auto port = svr.bind_to_any_port(HOST);
  17598. thread t = thread([&]() { svr.listen_after_bind(); });
  17599. auto se = detail::scope_exit([&] {
  17600. svr.stop();
  17601. t.join();
  17602. ASSERT_FALSE(svr.is_running());
  17603. });
  17604. svr.wait_until_ready();
  17605. Client cli(HOST, port);
  17606. Headers headers;
  17607. headers.emplace("Accept", "text/plain;q=0.5");
  17608. headers.emplace("Accept", "application/json");
  17609. auto res = cli.Get("/", headers);
  17610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17611. EXPECT_EQ(StatusCode::OK_200, res->status);
  17612. // Sorted by q-value, so the second field line's type comes first
  17613. ASSERT_EQ(2U, observed_types.size());
  17614. EXPECT_EQ("application/json", observed_types[0]);
  17615. EXPECT_EQ("text/plain", observed_types[1]);
  17616. }
  17617. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17618. // empty field line must not contribute a bare comma to the combined value.
  17619. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17620. Server svr;
  17621. std::vector<std::string> observed_types;
  17622. svr.Get("/", [&](const Request &req, Response &res) {
  17623. observed_types = req.accept_content_types;
  17624. res.set_content("ok", "text/plain");
  17625. });
  17626. auto port = svr.bind_to_any_port(HOST);
  17627. thread t = thread([&]() { svr.listen_after_bind(); });
  17628. auto se = detail::scope_exit([&] {
  17629. svr.stop();
  17630. t.join();
  17631. ASSERT_FALSE(svr.is_running());
  17632. });
  17633. svr.wait_until_ready();
  17634. // Empty first field line, then a real one
  17635. std::string raw_req = "GET / HTTP/1.1\r\n"
  17636. "Host: localhost\r\n"
  17637. "Accept:\r\n"
  17638. "Accept: application/json\r\n"
  17639. "Connection: close\r\n"
  17640. "\r\n";
  17641. std::string out;
  17642. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17643. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17644. ASSERT_EQ(1U, observed_types.size());
  17645. EXPECT_EQ("application/json", observed_types[0]);
  17646. }
  17647. // The skip in get_combined_header_value() is what keeps an empty field line
  17648. // from contributing a bare comma. Only a trailing empty field line exercises
  17649. // it: a leading one is already covered by the "combined is still empty" check,
  17650. // and parse_accept_header() now ignores the empty element either way, so the
  17651. // request-level test above can no longer tell the two apart.
  17652. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17653. Headers headers;
  17654. headers.emplace("Accept", "text/html");
  17655. headers.emplace("Accept", "");
  17656. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17657. headers.clear();
  17658. headers.emplace("Accept", "");
  17659. headers.emplace("Accept", "application/json");
  17660. EXPECT_EQ("application/json",
  17661. detail::get_combined_header_value(headers, "Accept"));
  17662. }
  17663. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17664. // An encoding offered on a later Accept-Encoding field line is still offered.
  17665. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17666. Server svr;
  17667. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17668. res.set_content(std::string(1024, 'x'), "text/plain");
  17669. });
  17670. auto port = svr.bind_to_any_port(HOST);
  17671. thread t = thread([&]() { svr.listen_after_bind(); });
  17672. auto se = detail::scope_exit([&] {
  17673. svr.stop();
  17674. t.join();
  17675. ASSERT_FALSE(svr.is_running());
  17676. });
  17677. svr.wait_until_ready();
  17678. Client cli(HOST, port);
  17679. cli.set_decompress(false);
  17680. Headers headers;
  17681. headers.emplace("Accept-Encoding", "identity");
  17682. headers.emplace("Accept-Encoding", "gzip");
  17683. auto res = cli.Get("/", headers);
  17684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17685. EXPECT_EQ(StatusCode::OK_200, res->status);
  17686. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17687. }
  17688. #endif
  17689. #ifndef _WIN32
  17690. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17691. Server svr;
  17692. svr.Post("/post", [&](const Request &req, Response &res) {
  17693. res.set_content(req.body, "text/plain");
  17694. });
  17695. svr.Put("/put", [&](const Request &req, Response &res) {
  17696. res.set_content(req.body, "text/plain");
  17697. });
  17698. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17699. res.set_content(req.body, "text/plain");
  17700. });
  17701. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17702. res.set_content(req.body, "text/plain");
  17703. });
  17704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17705. auto se = detail::scope_exit([&] {
  17706. svr.stop();
  17707. t.join();
  17708. ASSERT_FALSE(svr.is_running());
  17709. });
  17710. svr.wait_until_ready();
  17711. std::string resp;
  17712. // POST without Content-Length
  17713. ASSERT_TRUE(send_request(5,
  17714. "POST /post HTTP/1.1\r\n"
  17715. "Host: localhost\r\n"
  17716. "Connection: close\r\n"
  17717. "\r\n",
  17718. &resp));
  17719. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17720. // PUT without Content-Length
  17721. resp.clear();
  17722. ASSERT_TRUE(send_request(5,
  17723. "PUT /put HTTP/1.1\r\n"
  17724. "Host: localhost\r\n"
  17725. "Connection: close\r\n"
  17726. "\r\n",
  17727. &resp));
  17728. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17729. // PATCH without Content-Length
  17730. resp.clear();
  17731. ASSERT_TRUE(send_request(5,
  17732. "PATCH /patch HTTP/1.1\r\n"
  17733. "Host: localhost\r\n"
  17734. "Connection: close\r\n"
  17735. "\r\n",
  17736. &resp));
  17737. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17738. // DELETE without Content-Length
  17739. resp.clear();
  17740. ASSERT_TRUE(send_request(5,
  17741. "DELETE /delete HTTP/1.1\r\n"
  17742. "Host: localhost\r\n"
  17743. "Connection: close\r\n"
  17744. "\r\n",
  17745. &resp));
  17746. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17747. }
  17748. #endif
  17749. //==============================================================================
  17750. // open_stream() Tests
  17751. //==============================================================================
  17752. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17753. std::string result;
  17754. char buf[8192];
  17755. ssize_t n;
  17756. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17757. result.append(buf, static_cast<size_t>(n));
  17758. }
  17759. return result;
  17760. }
  17761. // Mock stream for unit tests
  17762. class MockStream : public Stream {
  17763. public:
  17764. std::string data;
  17765. size_t pos = 0;
  17766. ssize_t error_after = -1; // -1 = no error
  17767. explicit MockStream(const std::string &d, ssize_t err = -1)
  17768. : data(d), error_after(err) {}
  17769. bool is_readable() const override { return true; }
  17770. bool wait_readable() const override { return true; }
  17771. bool wait_writable() const override { return true; }
  17772. ssize_t read(char *ptr, size_t size) override {
  17773. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17774. if (pos >= data.size()) return 0;
  17775. size_t limit =
  17776. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17777. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17778. std::memcpy(ptr, data.data() + pos, to_read);
  17779. pos += to_read;
  17780. return static_cast<ssize_t>(to_read);
  17781. }
  17782. ssize_t write(const char *, size_t) override { return -1; }
  17783. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17784. ip = "127.0.0.1";
  17785. port = 0;
  17786. }
  17787. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17788. ip = "127.0.0.1";
  17789. port = 0;
  17790. }
  17791. socket_t socket() const override { return INVALID_SOCKET; }
  17792. time_t duration() const override { return 0; }
  17793. };
  17794. TEST(StreamHandleTest, Basic) {
  17795. ClientImpl::StreamHandle handle;
  17796. EXPECT_FALSE(handle.is_valid());
  17797. handle.response = detail::make_unique<Response>();
  17798. handle.error = Error::Connection;
  17799. EXPECT_FALSE(handle.is_valid());
  17800. handle.error = Error::Success;
  17801. EXPECT_TRUE(handle.is_valid());
  17802. }
  17803. TEST(BodyReaderTest, Basic) {
  17804. MockStream stream("Hello, World!");
  17805. detail::BodyReader reader;
  17806. reader.stream = &stream;
  17807. reader.content_length = 13;
  17808. char buf[32];
  17809. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17810. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17811. EXPECT_TRUE(reader.eof);
  17812. }
  17813. TEST(BodyReaderTest, NoStream) {
  17814. detail::BodyReader reader;
  17815. char buf[32];
  17816. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17817. EXPECT_EQ(Error::Connection, reader.last_error);
  17818. }
  17819. TEST(BodyReaderTest, Error) {
  17820. MockStream stream("Hello, World!", 5);
  17821. detail::BodyReader reader;
  17822. reader.stream = &stream;
  17823. reader.content_length = 13;
  17824. char buf[32];
  17825. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17826. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17827. EXPECT_EQ(Error::Read, reader.last_error);
  17828. }
  17829. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17830. // Mock-based StreamHandle tests relying on private internals are removed.
  17831. class OpenStreamTest : public ::testing::Test {
  17832. protected:
  17833. void SetUp() override {
  17834. svr_.Get("/hello", [](const Request &, Response &res) {
  17835. res.set_content("Hello World!", "text/plain");
  17836. });
  17837. svr_.Get("/large", [](const Request &, Response &res) {
  17838. res.set_content(std::string(10000, 'X'), "text/plain");
  17839. });
  17840. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17841. res.set_content("Hello World!", "image/jpeg");
  17842. res.set_header("Content-Encoding", "UTF-8");
  17843. });
  17844. svr_.Get("/chunked", [](const Request &, Response &res) {
  17845. res.set_chunked_content_provider("text/plain",
  17846. [](size_t offset, DataSink &sink) {
  17847. if (offset < 15) {
  17848. sink.write("chunk", 5);
  17849. return true;
  17850. }
  17851. sink.done();
  17852. return true;
  17853. });
  17854. });
  17855. svr_.Get("/compressible", [](const Request &, Response &res) {
  17856. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17857. DataSink &sink) {
  17858. if (offset < 100 * 1024) {
  17859. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17860. sink.write(chunk.data(), chunk.size());
  17861. return true;
  17862. }
  17863. sink.done();
  17864. return true;
  17865. });
  17866. });
  17867. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17868. [](const Request & /*req*/, Response &res) {
  17869. auto i = new int(0);
  17870. res.set_header("Trailer", "Content-Length, X-Allowed");
  17871. res.set_chunked_content_provider(
  17872. "text/plain",
  17873. [i](size_t /*offset*/, DataSink &sink) {
  17874. switch (*i) {
  17875. case 0: sink.os << "123"; break;
  17876. case 1: sink.os << "456"; break;
  17877. case 2: sink.os << "789"; break;
  17878. case 3: {
  17879. sink.done_with_trailer(
  17880. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17881. } break;
  17882. }
  17883. (*i)++;
  17884. return true;
  17885. },
  17886. [i](bool success) {
  17887. EXPECT_TRUE(success);
  17888. delete i;
  17889. });
  17890. });
  17891. // Echo headers endpoint for header-related tests
  17892. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17893. std::string body;
  17894. for (const auto &h : req.headers) {
  17895. body.append(h.first);
  17896. body.push_back(':');
  17897. body.append(h.second);
  17898. body.push_back('\n');
  17899. }
  17900. res.set_content(body, "text/plain");
  17901. });
  17902. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17903. std::string body;
  17904. for (const auto &h : req.headers) {
  17905. body.append(h.first);
  17906. body.push_back(':');
  17907. body.append(h.second);
  17908. body.push_back('\n');
  17909. }
  17910. res.set_content(body, "text/plain");
  17911. });
  17912. port_ = svr_.bind_to_any_port("127.0.0.1");
  17913. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17914. svr_.wait_until_ready();
  17915. }
  17916. void TearDown() override {
  17917. svr_.stop();
  17918. if (thread_.joinable()) thread_.join();
  17919. }
  17920. Server svr_;
  17921. std::thread thread_;
  17922. int port_ = 0;
  17923. };
  17924. TEST_F(OpenStreamTest, Basic) {
  17925. Client cli("127.0.0.1", port_);
  17926. auto handle = cli.open_stream("GET", "/hello");
  17927. EXPECT_TRUE(handle.is_valid());
  17928. EXPECT_EQ("Hello World!", read_all(handle));
  17929. }
  17930. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17931. Client cli("127.0.0.1", port_);
  17932. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17933. ASSERT_TRUE(handle.is_valid());
  17934. EXPECT_EQ("Hello World!", read_all(handle));
  17935. }
  17936. TEST_F(OpenStreamTest, SmallBuffer) {
  17937. Client cli("127.0.0.1", port_);
  17938. auto handle = cli.open_stream("GET", "/hello");
  17939. std::string result;
  17940. char buf[4];
  17941. ssize_t n;
  17942. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17943. result.append(buf, static_cast<size_t>(n));
  17944. EXPECT_EQ("Hello World!", result);
  17945. }
  17946. TEST_F(OpenStreamTest, DefaultHeaders) {
  17947. Client cli("127.0.0.1", port_);
  17948. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17949. {
  17950. auto handle = cli.open_stream("GET", "/echo-headers");
  17951. ASSERT_TRUE(handle.is_valid());
  17952. auto body = read_all(handle);
  17953. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17954. std::string::npos);
  17955. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17956. std::string::npos);
  17957. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17958. }
  17959. // open_stream POST with body and no explicit content_type should NOT add
  17960. // text/plain Content-Type (behavior differs from non-streaming path), but
  17961. // should include Content-Length
  17962. {
  17963. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17964. ASSERT_TRUE(handle.is_valid());
  17965. auto body = read_all(handle);
  17966. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17967. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17968. }
  17969. // open_stream POST with explicit Content-Type should preserve it
  17970. {
  17971. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17972. {{"Content-Type", "application/custom"}},
  17973. "{}", "application/custom");
  17974. ASSERT_TRUE(handle.is_valid());
  17975. auto body = read_all(handle);
  17976. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17977. }
  17978. // User-specified User-Agent must not be overwritten for stream API
  17979. {
  17980. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17981. {{"User-Agent", "MyAgent/1.2"}});
  17982. ASSERT_TRUE(handle.is_valid());
  17983. auto body = read_all(handle);
  17984. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17985. }
  17986. }
  17987. TEST_F(OpenStreamTest, Large) {
  17988. Client cli("127.0.0.1", port_);
  17989. auto handle = cli.open_stream("GET", "/large");
  17990. EXPECT_EQ(10000u, read_all(handle).size());
  17991. }
  17992. TEST_F(OpenStreamTest, ConnectionError) {
  17993. Client cli("127.0.0.1", 9999);
  17994. auto handle = cli.open_stream("GET", "/hello");
  17995. EXPECT_FALSE(handle.is_valid());
  17996. }
  17997. TEST_F(OpenStreamTest, Chunked) {
  17998. Client cli("127.0.0.1", port_);
  17999. auto handle = cli.open_stream("GET", "/chunked");
  18000. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18001. "Transfer-Encoding") == "chunked");
  18002. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18003. }
  18004. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18005. Client cli("127.0.0.1", port_);
  18006. auto handle =
  18007. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18008. ASSERT_TRUE(handle.is_valid());
  18009. // Consume body to allow trailers to be received/parsed
  18010. auto body = read_all(handle);
  18011. // Explicitly parse trailers (ensure trailers are available for assertion)
  18012. handle.parse_trailers_if_needed();
  18013. EXPECT_EQ(std::string("123456789"), body);
  18014. // The response should include a Trailer header declaring both names
  18015. ASSERT_TRUE(handle.response);
  18016. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18017. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18018. handle.response->get_header_value("Trailer"));
  18019. // Prohibited trailer must not be present
  18020. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18021. // Allowed trailer should be present
  18022. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18023. EXPECT_EQ(std::string("yes"),
  18024. handle.response->get_trailer_value("X-Allowed"));
  18025. // Verify trailers are NOT present as regular headers
  18026. EXPECT_EQ(std::string(""),
  18027. handle.response->get_header_value("Content-Length"));
  18028. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18029. }
  18030. static std::thread serve_single_response(std::promise<int> &port_promise,
  18031. const std::string &response) {
  18032. return std::thread([&port_promise, response] {
  18033. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18034. default_socket_options(srv);
  18035. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18036. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18037. sockaddr_in addr{};
  18038. addr.sin_family = AF_INET;
  18039. addr.sin_port = htons(0); // Let OS assign a free port
  18040. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18041. int opt = 1;
  18042. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18043. #ifdef _WIN32
  18044. reinterpret_cast<const char *>(&opt),
  18045. #else
  18046. &opt,
  18047. #endif
  18048. sizeof(opt));
  18049. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18050. ::listen(srv, 1) != 0) {
  18051. port_promise.set_value(-1);
  18052. detail::close_socket(srv);
  18053. return;
  18054. }
  18055. socklen_t addr_len = sizeof(addr);
  18056. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18057. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18058. sockaddr_in cli_addr{};
  18059. socklen_t cli_len = sizeof(cli_addr);
  18060. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18061. if (cli != INVALID_SOCKET) {
  18062. // Read the complete HTTP request (until the blank line that terminates
  18063. // headers) before sending the response. If the server closes the socket
  18064. // while the client's request data is still unread in the kernel receive
  18065. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18066. // connection on both sides: it discards the client's receive buffer
  18067. // (which already holds our response) and causes any in-progress write on
  18068. // the client to fail with ECONNRESET. Reading all request data first
  18069. // ensures close() emits a graceful FIN.
  18070. {
  18071. char rbuf[256];
  18072. std::string req;
  18073. while (req.find("\r\n\r\n") == std::string::npos) {
  18074. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18075. if (n <= 0) { break; }
  18076. req.append(rbuf, static_cast<size_t>(n));
  18077. }
  18078. }
  18079. ::send(cli,
  18080. #ifdef _WIN32
  18081. static_cast<const char *>(response.c_str()),
  18082. static_cast<int>(response.size()),
  18083. #else
  18084. response.c_str(), response.size(),
  18085. #endif
  18086. 0);
  18087. detail::close_socket(cli);
  18088. }
  18089. detail::close_socket(srv);
  18090. });
  18091. }
  18092. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18093. #ifndef _WIN32
  18094. signal(SIGPIPE, SIG_IGN);
  18095. #endif
  18096. std::promise<int> port_promise;
  18097. auto port_future = port_promise.get_future();
  18098. auto server_thread =
  18099. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18100. "Content-Type: text/plain\r\n"
  18101. "Content-Length: not-a-number\r\n"
  18102. "Connection: close\r\n"
  18103. "\r\n"
  18104. "hello");
  18105. auto port = port_future.get();
  18106. ASSERT_GT(port, 0);
  18107. Client cli("127.0.0.1", port);
  18108. auto handle = cli.open_stream("GET", "/");
  18109. EXPECT_FALSE(handle.is_valid());
  18110. server_thread.join();
  18111. }
  18112. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18113. #ifndef _WIN32
  18114. signal(SIGPIPE, SIG_IGN);
  18115. #endif
  18116. std::promise<int> port_promise;
  18117. auto port_future = port_promise.get_future();
  18118. auto server_thread = serve_single_response(
  18119. port_promise, "HTTP/1.1 200 OK\r\n"
  18120. "Content-Type: text/plain\r\n"
  18121. "Content-Length: 99999999999999999999999999\r\n"
  18122. "Connection: close\r\n"
  18123. "\r\n"
  18124. "hello");
  18125. auto port = port_future.get();
  18126. ASSERT_GT(port, 0);
  18127. // Historically std::stoull would throw std::out_of_range here and crash
  18128. // the process, then parsing silently clamped to a bogus framing length and
  18129. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18130. // so the stream fails to open, matching the not-a-number case above. The
  18131. // process still must NOT terminate.
  18132. Client cli("127.0.0.1", port);
  18133. auto handle = cli.open_stream("GET", "/");
  18134. EXPECT_FALSE(handle.is_valid());
  18135. server_thread.join();
  18136. }
  18137. // Serves `response` to the single request `fn` makes with a fresh client.
  18138. template <typename Fn>
  18139. static void with_single_response(const std::string &response, Fn fn) {
  18140. #ifndef _WIN32
  18141. signal(SIGPIPE, SIG_IGN);
  18142. #endif
  18143. std::promise<int> port_promise;
  18144. auto port_future = port_promise.get_future();
  18145. auto server_thread = serve_single_response(port_promise, response);
  18146. auto se = detail::scope_exit([&] { server_thread.join(); });
  18147. auto port = port_future.get();
  18148. ASSERT_GT(port, 0);
  18149. Client cli("127.0.0.1", port);
  18150. fn(cli);
  18151. }
  18152. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18153. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18154. // the chunked coding and drop Content-Length, so a front-end that trusts
  18155. // Content-Length would disagree about where the body ends (response
  18156. // smuggling). The client must reject such a response.
  18157. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18158. for (const char *te : {"chunked", "gzip, chunked"}) {
  18159. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18160. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18161. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18162. "5\r\nhello\r\n0\r\n\r\n";
  18163. with_single_response(response, [&](Client &cli) {
  18164. auto res = cli.Get("/");
  18165. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18166. EXPECT_EQ(Error::Read, res.error()) << te;
  18167. });
  18168. with_single_response(response, [&](Client &cli) {
  18169. auto handle = cli.open_stream("GET", "/");
  18170. EXPECT_FALSE(handle.is_valid()) << te;
  18171. EXPECT_EQ(Error::Read, handle.error) << te;
  18172. });
  18173. }
  18174. }
  18175. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18176. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18177. // closing the connection (unlike a request, which must be rejected).
  18178. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18179. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18180. "Transfer-Encoding: chunked\r\n"
  18181. "Connection: close\r\n"
  18182. "\r\n"
  18183. "5\r\nhello\r\n0\r\n\r\n",
  18184. "HTTP/1.1 200 OK\r\n"
  18185. "Transfer-Encoding: gzip\r\n"
  18186. "Connection: close\r\n"
  18187. "\r\n"
  18188. "hello"}) {
  18189. with_single_response(response, [&](Client &cli) {
  18190. auto res = cli.Get("/");
  18191. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18192. EXPECT_EQ("hello", res->body);
  18193. });
  18194. with_single_response(response, [&](Client &cli) {
  18195. auto handle = cli.open_stream("GET", "/");
  18196. ASSERT_TRUE(handle.is_valid()) << response;
  18197. EXPECT_EQ("hello", read_all(handle));
  18198. });
  18199. }
  18200. }
  18201. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18202. // framing headers describe nothing to read and must not be rejected.
  18203. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18204. const std::string framing = "Content-Length: 5\r\n"
  18205. "Transfer-Encoding: chunked\r\n"
  18206. "Connection: close\r\n"
  18207. "\r\n";
  18208. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18209. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18210. });
  18211. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18212. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18213. });
  18214. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18215. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18216. with_single_response(response, [&](Client &cli) {
  18217. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18218. });
  18219. with_single_response(response, [&](Client &cli) {
  18220. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18221. });
  18222. }
  18223. }
  18224. // A payload max length of 0 means no limit, however the body is framed.
  18225. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18226. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18227. "Transfer-Encoding: chunked\r\n"
  18228. "\r\n"
  18229. "5\r\nhello\r\n0\r\n\r\n",
  18230. "HTTP/1.1 200 OK\r\n"
  18231. "Connection: close\r\n"
  18232. "\r\n"
  18233. "hello"}) {
  18234. with_single_response(response, [&](Client &cli) {
  18235. cli.set_payload_max_length(0);
  18236. auto res = cli.Get("/");
  18237. ASSERT_TRUE(res) << response;
  18238. EXPECT_EQ("hello", res->body) << response;
  18239. });
  18240. }
  18241. }
  18242. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18243. Server svr;
  18244. svr.set_payload_max_length(0);
  18245. svr.Post("/echo", [](const Request &req, Response &res) {
  18246. res.set_content(req.body, "text/plain");
  18247. });
  18248. auto port = svr.bind_to_any_port(HOST);
  18249. thread t = thread([&] { svr.listen_after_bind(); });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. t.join();
  18253. ASSERT_FALSE(svr.is_running());
  18254. });
  18255. svr.wait_until_ready();
  18256. Client cli(HOST, port);
  18257. auto res = cli.Post(
  18258. "/echo",
  18259. [](size_t /*offset*/, DataSink &sink) {
  18260. sink.write("hello", 5);
  18261. sink.done();
  18262. return true;
  18263. },
  18264. "text/plain");
  18265. ASSERT_TRUE(res);
  18266. EXPECT_EQ(StatusCode::OK_200, res->status);
  18267. EXPECT_EQ("hello", res->body);
  18268. }
  18269. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18270. TEST_F(OpenStreamTest, Gzip) {
  18271. Client cli("127.0.0.1", port_);
  18272. auto handle = cli.open_stream("GET", "/compressible", {},
  18273. {{"Accept-Encoding", "gzip"}});
  18274. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18275. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18276. }
  18277. #endif
  18278. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18279. TEST_F(OpenStreamTest, Brotli) {
  18280. Client cli("127.0.0.1", port_);
  18281. auto handle =
  18282. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18283. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18284. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18285. }
  18286. #endif
  18287. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18288. TEST_F(OpenStreamTest, Zstd) {
  18289. Client cli("127.0.0.1", port_);
  18290. auto handle = cli.open_stream("GET", "/compressible", {},
  18291. {{"Accept-Encoding", "zstd"}});
  18292. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18293. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18294. }
  18295. #endif
  18296. #ifdef CPPHTTPLIB_SSL_ENABLED
  18297. class SSLOpenStreamTest : public ::testing::Test {
  18298. protected:
  18299. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18300. void SetUp() override {
  18301. svr_.Get("/hello", [](const Request &, Response &res) {
  18302. res.set_content("Hello SSL World!", "text/plain");
  18303. });
  18304. svr_.Get("/chunked", [](const Request &, Response &res) {
  18305. res.set_chunked_content_provider("text/plain",
  18306. [](size_t offset, DataSink &sink) {
  18307. if (offset < 15) {
  18308. sink.write("chunk", 5);
  18309. return true;
  18310. }
  18311. sink.done();
  18312. return true;
  18313. });
  18314. });
  18315. svr_.Post("/echo", [](const Request &req, Response &res) {
  18316. res.set_content(req.body, req.get_header_value("Content-Type"));
  18317. });
  18318. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18319. std::string body = req.body;
  18320. res.set_chunked_content_provider(
  18321. "text/plain", [body](size_t offset, DataSink &sink) {
  18322. if (offset < body.size()) {
  18323. sink.write(body.data() + offset, body.size() - offset);
  18324. }
  18325. sink.done();
  18326. return true;
  18327. });
  18328. });
  18329. port_ = svr_.bind_to_any_port("127.0.0.1");
  18330. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18331. svr_.wait_until_ready();
  18332. }
  18333. void TearDown() override {
  18334. svr_.stop();
  18335. if (thread_.joinable()) thread_.join();
  18336. }
  18337. SSLServer svr_;
  18338. std::thread thread_;
  18339. int port_ = 0;
  18340. };
  18341. TEST_F(SSLOpenStreamTest, Basic) {
  18342. SSLClient cli("127.0.0.1", port_);
  18343. cli.enable_server_certificate_verification(false);
  18344. auto handle = cli.open_stream("GET", "/hello");
  18345. ASSERT_TRUE(handle.is_valid());
  18346. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18347. }
  18348. TEST_F(SSLOpenStreamTest, Chunked) {
  18349. SSLClient cli("127.0.0.1", port_);
  18350. cli.enable_server_certificate_verification(false);
  18351. auto handle = cli.open_stream("GET", "/chunked");
  18352. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18353. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18354. "Transfer-Encoding") == "chunked");
  18355. auto body = read_all(handle);
  18356. EXPECT_EQ("chunkchunkchunk", body);
  18357. }
  18358. TEST_F(SSLOpenStreamTest, Post) {
  18359. SSLClient cli("127.0.0.1", port_);
  18360. cli.enable_server_certificate_verification(false);
  18361. auto handle =
  18362. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18363. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18364. EXPECT_EQ(200, handle.response->status);
  18365. auto body = read_all(handle);
  18366. EXPECT_EQ("Hello SSL POST", body);
  18367. }
  18368. TEST_F(SSLOpenStreamTest, PostChunked) {
  18369. SSLClient cli("127.0.0.1", port_);
  18370. cli.enable_server_certificate_verification(false);
  18371. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18372. "Chunked SSL Data", "text/plain");
  18373. ASSERT_TRUE(handle.is_valid());
  18374. EXPECT_EQ(200, handle.response->status);
  18375. auto body = read_all(handle);
  18376. EXPECT_EQ("Chunked SSL Data", body);
  18377. }
  18378. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18379. // Content-Length is terminated by the server closing the connection. When the
  18380. // SSL peer sends a close_notify after the body, the client must treat it as a
  18381. // clean EOF and return a successful response rather than an error.
  18382. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18384. ASSERT_TRUE(svr.is_valid());
  18385. svr.set_keep_alive_max_count(1);
  18386. const std::string expected_body = "Hello from connection-close response!";
  18387. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18388. res.set_content_provider("text/plain",
  18389. [&](size_t offset, DataSink &sink) -> bool {
  18390. if (offset < expected_body.size()) {
  18391. sink.write(expected_body.data() + offset,
  18392. expected_body.size() - offset);
  18393. }
  18394. sink.done();
  18395. return true;
  18396. });
  18397. });
  18398. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18399. auto se = detail::scope_exit([&] {
  18400. svr.stop();
  18401. listen_thread.join();
  18402. ASSERT_FALSE(svr.is_running());
  18403. });
  18404. svr.wait_until_ready();
  18405. SSLClient cli(HOST, PORT);
  18406. cli.enable_server_certificate_verification(false);
  18407. auto res = cli.Get("/no-content-length");
  18408. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18409. EXPECT_EQ(StatusCode::OK_200, res->status);
  18410. EXPECT_EQ(expected_body, res->body);
  18411. }
  18412. #endif // CPPHTTPLIB_SSL_ENABLED
  18413. //==============================================================================
  18414. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18415. // results for various scenarios.
  18416. //==============================================================================
  18417. TEST(ParityTest, GetVsOpenStream) {
  18418. Server svr;
  18419. const std::string path = "/parity";
  18420. const std::string content = "Parity test content: hello world";
  18421. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18422. res.set_content(content, "text/plain");
  18423. });
  18424. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18425. auto se = detail::scope_exit([&] {
  18426. svr.stop();
  18427. t.join();
  18428. ASSERT_FALSE(svr.is_running());
  18429. });
  18430. svr.wait_until_ready();
  18431. Client cli(HOST, PORT);
  18432. // Non-stream path
  18433. auto r1 = cli.Get(path);
  18434. ASSERT_TRUE(r1);
  18435. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18436. // Stream path
  18437. auto h = cli.open_stream("GET", path);
  18438. ASSERT_TRUE(h.is_valid());
  18439. EXPECT_EQ(r1->body, read_all(h));
  18440. }
  18441. // Helper to compress data with provided compressor type T
  18442. template <typename Compressor>
  18443. static std::string compress_payload_for_parity(const std::string &in) {
  18444. std::string out;
  18445. Compressor compressor;
  18446. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18447. [&](const char *data, size_t n) {
  18448. out.append(data, n);
  18449. return true;
  18450. });
  18451. EXPECT_TRUE(ok);
  18452. return out;
  18453. }
  18454. // Helper function for compression parity tests
  18455. template <typename Compressor>
  18456. static void test_compression_parity(const std::string &original,
  18457. const std::string &path,
  18458. const std::string &encoding) {
  18459. const std::string compressed =
  18460. compress_payload_for_parity<Compressor>(original);
  18461. Server svr;
  18462. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18463. res.set_content(compressed, "application/octet-stream");
  18464. res.set_header("Content-Encoding", encoding);
  18465. });
  18466. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18467. auto se = detail::scope_exit([&] {
  18468. svr.stop();
  18469. t.join();
  18470. ASSERT_FALSE(svr.is_running());
  18471. });
  18472. svr.wait_until_ready();
  18473. Client cli(HOST, PORT);
  18474. // Non-streaming
  18475. {
  18476. auto res = cli.Get(path);
  18477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18478. EXPECT_EQ(StatusCode::OK_200, res->status);
  18479. EXPECT_EQ(original, res->body);
  18480. }
  18481. // Streaming
  18482. {
  18483. auto h = cli.open_stream("GET", path);
  18484. ASSERT_TRUE(h.is_valid());
  18485. EXPECT_EQ(original, read_all(h));
  18486. }
  18487. }
  18488. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18489. TEST(ParityTest, Gzip) {
  18490. test_compression_parity<detail::gzip_compressor>(
  18491. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18492. }
  18493. #endif
  18494. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18495. TEST(ParityTest, Brotli) {
  18496. test_compression_parity<detail::brotli_compressor>(
  18497. "Hello, brotli parity test payload", "/parity-br", "br");
  18498. }
  18499. #endif
  18500. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18501. TEST(ParityTest, Zstd) {
  18502. test_compression_parity<detail::zstd_compressor>(
  18503. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18504. }
  18505. #endif
  18506. //==============================================================================
  18507. // New Stream API Tests
  18508. //==============================================================================
  18509. inline std::string read_body(httplib::stream::Result &result) {
  18510. std::string body;
  18511. while (result.next()) {
  18512. body.append(result.data(), result.size());
  18513. }
  18514. return body;
  18515. }
  18516. TEST(ClientConnectionTest, Basic) {
  18517. httplib::ClientConnection conn;
  18518. EXPECT_FALSE(conn.is_open());
  18519. conn.sock = 1;
  18520. EXPECT_TRUE(conn.is_open());
  18521. httplib::ClientConnection conn2(std::move(conn));
  18522. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18523. conn2.sock = INVALID_SOCKET;
  18524. }
  18525. // Unified test server for all stream::* tests
  18526. class StreamApiTest : public ::testing::Test {
  18527. protected:
  18528. void SetUp() override {
  18529. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18530. res.set_content("Hello World!", "text/plain");
  18531. });
  18532. svr_.Get("/echo-params",
  18533. [](const httplib::Request &req, httplib::Response &res) {
  18534. std::string r;
  18535. for (const auto &p : req.params) {
  18536. if (!r.empty()) r += "&";
  18537. r += p.first + "=" + p.second;
  18538. }
  18539. res.set_content(r, "text/plain");
  18540. });
  18541. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18542. res.set_content(req.body, req.get_header_value("Content-Type"));
  18543. });
  18544. svr_.Post("/echo-headers",
  18545. [](const httplib::Request &req, httplib::Response &res) {
  18546. std::string r;
  18547. for (const auto &h : req.headers)
  18548. r += h.first + ": " + h.second + "\n";
  18549. res.set_content(r, "text/plain");
  18550. });
  18551. svr_.Post("/echo-params",
  18552. [](const httplib::Request &req, httplib::Response &res) {
  18553. std::string r = "params:";
  18554. for (const auto &p : req.params)
  18555. r += p.first + "=" + p.second + ";";
  18556. res.set_content(r + " body:" + req.body, "text/plain");
  18557. });
  18558. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18559. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18560. });
  18561. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18562. res.set_content("PUT:" + req.body, "text/plain");
  18563. });
  18564. svr_.Patch("/echo",
  18565. [](const httplib::Request &req, httplib::Response &res) {
  18566. res.set_content("PATCH:" + req.body, "text/plain");
  18567. });
  18568. svr_.Delete(
  18569. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18570. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18571. "text/plain");
  18572. });
  18573. svr_.Get("/head-test",
  18574. [](const httplib::Request &, httplib::Response &res) {
  18575. res.set_content("body for HEAD", "text/plain");
  18576. });
  18577. svr_.Options("/options",
  18578. [](const httplib::Request &, httplib::Response &res) {
  18579. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18580. });
  18581. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18582. svr_.wait_until_ready();
  18583. }
  18584. void TearDown() override {
  18585. svr_.stop();
  18586. if (thread_.joinable()) thread_.join();
  18587. }
  18588. httplib::Server svr_;
  18589. std::thread thread_;
  18590. };
  18591. // stream::Get tests
  18592. TEST_F(StreamApiTest, GetBasic) {
  18593. httplib::Client cli(HOST, PORT);
  18594. auto result = httplib::stream::Get(cli, "/hello");
  18595. ASSERT_TRUE(result.is_valid());
  18596. EXPECT_EQ(200, result.status());
  18597. EXPECT_EQ("Hello World!", read_body(result));
  18598. }
  18599. TEST_F(StreamApiTest, GetWithParams) {
  18600. httplib::Client cli(HOST, PORT);
  18601. httplib::Params params{{"foo", "bar"}};
  18602. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18603. ASSERT_TRUE(result.is_valid());
  18604. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18605. }
  18606. TEST_F(StreamApiTest, GetConnectionError) {
  18607. httplib::Client cli(HOST, 9999);
  18608. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18609. }
  18610. TEST_F(StreamApiTest, Get404) {
  18611. httplib::Client cli(HOST, PORT);
  18612. auto result = httplib::stream::Get(cli, "/nonexistent");
  18613. EXPECT_TRUE(result.is_valid());
  18614. EXPECT_EQ(404, result.status());
  18615. }
  18616. // stream::Post tests
  18617. TEST_F(StreamApiTest, PostBasic) {
  18618. httplib::Client cli(HOST, PORT);
  18619. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18620. "application/json");
  18621. ASSERT_TRUE(result.is_valid());
  18622. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18623. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18624. }
  18625. TEST_F(StreamApiTest, PostWithHeaders) {
  18626. httplib::Client cli(HOST, PORT);
  18627. httplib::Headers headers{{"X-Custom", "value"}};
  18628. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18629. "text/plain");
  18630. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18631. }
  18632. TEST_F(StreamApiTest, PostWithParams) {
  18633. httplib::Client cli(HOST, PORT);
  18634. httplib::Params params{{"k", "v"}};
  18635. auto result =
  18636. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18637. auto body = read_body(result);
  18638. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18639. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18640. }
  18641. TEST_F(StreamApiTest, PostLarge) {
  18642. httplib::Client cli(HOST, PORT);
  18643. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18644. size_t total = 0;
  18645. while (result.next()) {
  18646. total += result.size();
  18647. }
  18648. EXPECT_EQ(100u * 1024u, total);
  18649. }
  18650. // stream::Put/Patch tests
  18651. TEST_F(StreamApiTest, PutAndPatch) {
  18652. httplib::Client cli(HOST, PORT);
  18653. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18654. EXPECT_EQ("PUT:test", read_body(put));
  18655. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18656. EXPECT_EQ("PATCH:test", read_body(patch));
  18657. }
  18658. // stream::Delete tests
  18659. TEST_F(StreamApiTest, Delete) {
  18660. httplib::Client cli(HOST, PORT);
  18661. auto del1 = httplib::stream::Delete(cli, "/resource");
  18662. EXPECT_EQ("Deleted", read_body(del1));
  18663. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18664. EXPECT_EQ("Deleted:data", read_body(del2));
  18665. }
  18666. // stream::Head/Options tests
  18667. TEST_F(StreamApiTest, HeadAndOptions) {
  18668. httplib::Client cli(HOST, PORT);
  18669. auto head = httplib::stream::Head(cli, "/head-test");
  18670. EXPECT_TRUE(head.is_valid());
  18671. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18672. auto opts = httplib::stream::Options(cli, "/options");
  18673. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18674. }
  18675. // SSL stream::* tests
  18676. #ifdef CPPHTTPLIB_SSL_ENABLED
  18677. class SSLStreamApiTest : public ::testing::Test {
  18678. protected:
  18679. void SetUp() override {
  18680. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18681. res.set_content("Hello SSL!", "text/plain");
  18682. });
  18683. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18684. res.set_content(req.body, "text/plain");
  18685. });
  18686. port_ = svr_.bind_to_any_port("127.0.0.1");
  18687. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18688. svr_.wait_until_ready();
  18689. }
  18690. void TearDown() override {
  18691. svr_.stop();
  18692. if (thread_.joinable()) thread_.join();
  18693. }
  18694. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18695. std::thread thread_;
  18696. int port_ = 0;
  18697. };
  18698. TEST_F(SSLStreamApiTest, GetAndPost) {
  18699. httplib::SSLClient cli("127.0.0.1", port_);
  18700. cli.enable_server_certificate_verification(false);
  18701. auto get = httplib::stream::Get(cli, "/hello");
  18702. EXPECT_EQ("Hello SSL!", read_body(get));
  18703. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18704. EXPECT_EQ("test", read_body(post));
  18705. }
  18706. #endif
  18707. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18708. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18709. // BodyReader
  18710. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18711. // Test that read timeout during streaming is detected
  18712. // Use a large content-length response where server delays mid-stream
  18713. Server svr;
  18714. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18715. // Send a large response with delay in the middle
  18716. res.set_content_provider(
  18717. 1000, // content_length
  18718. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18719. if (offset < 100) {
  18720. // Send first 100 bytes immediately
  18721. std::string data(100, 'A');
  18722. sink.write(data.c_str(), data.size());
  18723. return true;
  18724. }
  18725. // Then delay longer than client timeout
  18726. std::this_thread::sleep_for(std::chrono::seconds(3));
  18727. std::string data(900, 'B');
  18728. sink.write(data.c_str(), data.size());
  18729. return true;
  18730. });
  18731. });
  18732. auto port = 8091;
  18733. std::thread t([&]() { svr.listen("localhost", port); });
  18734. svr.wait_until_ready();
  18735. Client cli("localhost", port);
  18736. cli.set_read_timeout(1, 0); // 1 second timeout
  18737. auto handle = cli.open_stream("GET", "/slow-stream");
  18738. ASSERT_TRUE(handle.is_valid());
  18739. char buf[256];
  18740. ssize_t total = 0;
  18741. ssize_t n;
  18742. bool got_error = false;
  18743. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18744. total += n;
  18745. }
  18746. if (n < 0) {
  18747. got_error = true;
  18748. // Should be timeout or read error
  18749. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18750. handle.get_read_error() == Error::Read)
  18751. << "Actual error: " << to_string(handle.get_read_error());
  18752. }
  18753. // Either we got an error, or we got less data than expected
  18754. EXPECT_TRUE(got_error || total < 1000)
  18755. << "Expected timeout but got all " << total << " bytes";
  18756. svr.stop();
  18757. t.join();
  18758. }
  18759. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18760. // Test connection closed detection via BodyReader
  18761. Server svr;
  18762. std::atomic<bool> close_now{false};
  18763. svr.Get("/will-close", [&](const Request &, Response &res) {
  18764. res.set_content_provider(
  18765. 10000, // Large content_length that we won't fully send
  18766. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18767. if (offset < 100) {
  18768. std::string data(100, 'X');
  18769. sink.write(data.c_str(), data.size());
  18770. return true;
  18771. }
  18772. // Wait for signal then abort
  18773. while (!close_now) {
  18774. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18775. }
  18776. return false; // Abort - server will close connection
  18777. });
  18778. });
  18779. auto port = 8092;
  18780. std::thread t([&]() { svr.listen("localhost", port); });
  18781. svr.wait_until_ready();
  18782. Client cli("localhost", port);
  18783. auto handle = cli.open_stream("GET", "/will-close");
  18784. ASSERT_TRUE(handle.is_valid());
  18785. char buf[256];
  18786. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18787. EXPECT_GT(n, 0) << "First read should succeed";
  18788. // Signal server to close
  18789. close_now = true;
  18790. // Keep reading until error or EOF
  18791. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18792. // Keep reading
  18793. }
  18794. // Should get an error since content_length wasn't satisfied
  18795. if (n < 0) {
  18796. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18797. handle.get_read_error() == Error::Read)
  18798. << "Actual error: " << to_string(handle.get_read_error());
  18799. }
  18800. svr.stop();
  18801. t.join();
  18802. }
  18803. #ifdef CPPHTTPLIB_SSL_ENABLED
  18804. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18805. // Test that read timeout during SSL streaming is detected
  18806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18807. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18808. res.set_content_provider(
  18809. 1000, "text/plain",
  18810. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18811. if (offset < 100) {
  18812. std::string data(100, 'A');
  18813. sink.write(data.c_str(), data.size());
  18814. return true;
  18815. }
  18816. std::this_thread::sleep_for(std::chrono::seconds(3));
  18817. std::string data(900, 'B');
  18818. sink.write(data.c_str(), data.size());
  18819. return true;
  18820. });
  18821. });
  18822. auto port = 8093;
  18823. std::thread t([&]() { svr.listen("localhost", port); });
  18824. svr.wait_until_ready();
  18825. SSLClient cli("localhost", port);
  18826. cli.enable_server_certificate_verification(false);
  18827. cli.set_read_timeout(1, 0); // 1 second timeout
  18828. auto handle = cli.open_stream("GET", "/slow-stream");
  18829. ASSERT_TRUE(handle.is_valid());
  18830. char buf[256];
  18831. ssize_t total = 0;
  18832. ssize_t n;
  18833. bool got_error = false;
  18834. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18835. total += n;
  18836. }
  18837. if (n < 0) {
  18838. got_error = true;
  18839. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18840. handle.get_read_error() == Error::Read)
  18841. << "Actual error: " << to_string(handle.get_read_error());
  18842. }
  18843. EXPECT_TRUE(got_error || total < 1000)
  18844. << "Expected timeout but got all " << total << " bytes";
  18845. svr.stop();
  18846. t.join();
  18847. }
  18848. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18849. // Test SSL connection closed detection
  18850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18851. std::atomic<bool> close_now{false};
  18852. svr.Get("/will-close", [&](const Request &, Response &res) {
  18853. res.set_content_provider(
  18854. 10000, "text/plain",
  18855. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18856. if (offset < 100) {
  18857. std::string data(100, 'X');
  18858. sink.write(data.c_str(), data.size());
  18859. return true;
  18860. }
  18861. while (!close_now) {
  18862. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18863. }
  18864. return false;
  18865. });
  18866. });
  18867. auto port = 8094;
  18868. std::thread t([&]() { svr.listen("localhost", port); });
  18869. svr.wait_until_ready();
  18870. SSLClient cli("localhost", port);
  18871. cli.enable_server_certificate_verification(false);
  18872. auto handle = cli.open_stream("GET", "/will-close");
  18873. ASSERT_TRUE(handle.is_valid());
  18874. char buf[256];
  18875. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18876. EXPECT_GT(n, 0);
  18877. // Signal server to close
  18878. close_now = true;
  18879. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18880. // Keep reading
  18881. }
  18882. if (n < 0) {
  18883. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18884. handle.get_read_error() == Error::Read)
  18885. << "Actual error: " << to_string(handle.get_read_error());
  18886. }
  18887. svr.stop();
  18888. t.join();
  18889. }
  18890. #endif
  18891. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18892. using namespace httplib;
  18893. // Create a test file
  18894. const char *fname = "etag_testfile.txt";
  18895. const char *content = "etag-content";
  18896. {
  18897. std::ofstream ofs(fname);
  18898. ofs << content;
  18899. ASSERT_TRUE(ofs.good());
  18900. }
  18901. Server svr;
  18902. svr.set_mount_point("/static", ".");
  18903. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18904. svr.wait_until_ready();
  18905. Client cli(HOST, PORT);
  18906. // First request: should get 200 with ETag header
  18907. auto res1 = cli.Get("/static/etag_testfile.txt");
  18908. ASSERT_TRUE(res1);
  18909. ASSERT_EQ(200, res1->status);
  18910. ASSERT_TRUE(res1->has_header("ETag"));
  18911. std::string etag = res1->get_header_value("ETag");
  18912. EXPECT_FALSE(etag.empty());
  18913. // Verify ETag format: W/"hex-hex"
  18914. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18915. EXPECT_EQ('W', etag[0]);
  18916. EXPECT_EQ('/', etag[1]);
  18917. EXPECT_EQ('"', etag[2]);
  18918. EXPECT_EQ('"', etag.back());
  18919. // Exact match: expect 304 Not Modified
  18920. Headers h2 = {{"If-None-Match", etag}};
  18921. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18922. ASSERT_TRUE(res2);
  18923. EXPECT_EQ(304, res2->status);
  18924. // Wildcard match: expect 304 Not Modified
  18925. Headers h3 = {{"If-None-Match", "*"}};
  18926. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18927. ASSERT_TRUE(res3);
  18928. EXPECT_EQ(304, res3->status);
  18929. // Non-matching ETag: expect 200
  18930. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18931. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18932. ASSERT_TRUE(res4);
  18933. EXPECT_EQ(200, res4->status);
  18934. // Multiple ETags with one matching: expect 304
  18935. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18936. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18937. ASSERT_TRUE(res5);
  18938. EXPECT_EQ(304, res5->status);
  18939. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18940. // that equivalent to the single comma-separated list above, so the match on
  18941. // the second line must still be found.
  18942. Headers h6;
  18943. h6.emplace("If-None-Match", "W/\"other\"");
  18944. h6.emplace("If-None-Match", etag);
  18945. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18946. ASSERT_TRUE(res6);
  18947. EXPECT_EQ(304, res6->status);
  18948. svr.stop();
  18949. t.join();
  18950. std::remove(fname);
  18951. }
  18952. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18953. using namespace httplib;
  18954. Server svr;
  18955. svr.set_mount_point("/static", ".");
  18956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18957. svr.wait_until_ready();
  18958. Client cli(HOST, PORT);
  18959. // Send If-None-Match: * to a non-existent file
  18960. Headers h = {{"If-None-Match", "*"}};
  18961. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18963. EXPECT_EQ(404, res->status);
  18964. svr.stop();
  18965. t.join();
  18966. }
  18967. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18968. using namespace httplib;
  18969. // Create a test file
  18970. const char *fname = "etag_boundary_testfile.txt";
  18971. const char *content = "boundary-test";
  18972. {
  18973. std::ofstream ofs(fname);
  18974. ofs << content;
  18975. ASSERT_TRUE(ofs.good());
  18976. }
  18977. Server svr;
  18978. svr.set_mount_point("/static", ".");
  18979. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18980. svr.wait_until_ready();
  18981. Client cli(HOST, PORT);
  18982. // Get the actual ETag
  18983. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18984. ASSERT_TRUE(res1);
  18985. ASSERT_EQ(200, res1->status);
  18986. ASSERT_TRUE(res1->has_header("ETag"));
  18987. std::string etag = res1->get_header_value("ETag");
  18988. // Test 1: Very long ETag value (longer than actual ETag)
  18989. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18990. Headers h1 = {{"If-None-Match", "W/"
  18991. "\"very-long-etag-value-that-is-much-longer-"
  18992. "than-the-actual-etag-value\""}};
  18993. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18994. ASSERT_TRUE(res2);
  18995. EXPECT_EQ(200, res2->status); // Should not match
  18996. // Test 2: Long string followed by wildcard
  18997. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18998. // string)
  18999. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19000. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19001. ASSERT_TRUE(res3);
  19002. EXPECT_EQ(304, res3->status); // Should match on "*"
  19003. // Test 3: Wildcard followed by long string
  19004. // Should match on "*" immediately and return 304
  19005. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19006. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19007. ASSERT_TRUE(res4);
  19008. EXPECT_EQ(304, res4->status); // Should match on "*"
  19009. // Test 4: Multiple long non-matching values
  19010. // Should NOT match and return 200 (test that all comparisons are safe)
  19011. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19012. "W/\"second-long-non-matching-value\", "
  19013. "W/\"third-long-non-matching-value\""}};
  19014. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19015. ASSERT_TRUE(res5);
  19016. EXPECT_EQ(200, res5->status); // Should not match
  19017. // Test 5: Single character that is not "*" (edge case)
  19018. Headers h5 = {{"If-None-Match", "X"}};
  19019. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19020. ASSERT_TRUE(res6);
  19021. EXPECT_EQ(200, res6->status); // Should not match
  19022. svr.stop();
  19023. t.join();
  19024. std::remove(fname);
  19025. }
  19026. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19027. using namespace httplib;
  19028. // Create a test file
  19029. const char *fname = "ims_testfile.txt";
  19030. const char *content = "if-modified-since-test";
  19031. {
  19032. std::ofstream ofs(fname);
  19033. ofs << content;
  19034. ASSERT_TRUE(ofs.good());
  19035. }
  19036. Server svr;
  19037. svr.set_mount_point("/static", ".");
  19038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. // First request: should get 200 with Last-Modified header
  19042. auto res1 = cli.Get("/static/ims_testfile.txt");
  19043. ASSERT_TRUE(res1);
  19044. ASSERT_EQ(200, res1->status);
  19045. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19046. std::string last_modified = res1->get_header_value("Last-Modified");
  19047. EXPECT_FALSE(last_modified.empty());
  19048. // If-Modified-Since with same time: expect 304
  19049. Headers h2 = {{"If-Modified-Since", last_modified}};
  19050. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19051. ASSERT_TRUE(res2);
  19052. EXPECT_EQ(304, res2->status);
  19053. // If-Modified-Since with future time: expect 304
  19054. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19055. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19056. ASSERT_TRUE(res3);
  19057. EXPECT_EQ(304, res3->status);
  19058. // If-Modified-Since with past time: expect 200
  19059. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19060. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19061. ASSERT_TRUE(res4);
  19062. EXPECT_EQ(200, res4->status);
  19063. // If-None-Match takes precedence over If-Modified-Since
  19064. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19065. ASSERT_TRUE(res1->has_header("ETag"));
  19066. std::string etag = res1->get_header_value("ETag");
  19067. Headers h5 = {{"If-None-Match", etag},
  19068. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19069. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19070. ASSERT_TRUE(res5);
  19071. EXPECT_EQ(304, res5->status);
  19072. svr.stop();
  19073. t.join();
  19074. std::remove(fname);
  19075. }
  19076. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19077. using namespace httplib;
  19078. Server svr;
  19079. // Endpoint that returns compressible content
  19080. svr.Get("/compressible", [](const Request &, Response &res) {
  19081. // Return a large enough body to trigger compression
  19082. std::string body(1000, 'a');
  19083. res.set_content(body, "text/plain");
  19084. });
  19085. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19086. svr.wait_until_ready();
  19087. Client cli(HOST, PORT);
  19088. // Request with gzip support: should get Vary header when compressed
  19089. cli.set_compress(true);
  19090. auto res1 = cli.Get("/compressible");
  19091. ASSERT_TRUE(res1);
  19092. EXPECT_EQ(200, res1->status);
  19093. // If Content-Encoding is set, Vary should also be set
  19094. if (res1->has_header("Content-Encoding")) {
  19095. EXPECT_TRUE(res1->has_header("Vary"));
  19096. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19097. }
  19098. // Request without Accept-Encoding header: should not have compression
  19099. Headers h_no_compress;
  19100. auto res2 = cli.Get("/compressible", h_no_compress);
  19101. ASSERT_TRUE(res2);
  19102. EXPECT_EQ(200, res2->status);
  19103. // Verify Vary header is present when compression is applied
  19104. // (the exact behavior depends on server configuration)
  19105. svr.stop();
  19106. t.join();
  19107. }
  19108. TEST(ETagTest, IfRangeWithETag) {
  19109. using namespace httplib;
  19110. // Create a test file with known content
  19111. const char *fname = "if_range_testfile.txt";
  19112. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19113. {
  19114. std::ofstream ofs(fname);
  19115. ofs << content;
  19116. ASSERT_TRUE(ofs.good());
  19117. }
  19118. Server svr;
  19119. svr.set_mount_point("/static", ".");
  19120. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19121. svr.wait_until_ready();
  19122. Client cli(HOST, PORT);
  19123. // First request: get ETag
  19124. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19125. ASSERT_TRUE(res1);
  19126. ASSERT_EQ(200, res1->status);
  19127. ASSERT_TRUE(res1->has_header("ETag"));
  19128. std::string etag = res1->get_header_value("ETag");
  19129. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19130. // Since our server generates weak ETags (W/"..."), If-Range with our
  19131. // ETag should NOT result in partial content - it should return full content.
  19132. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19133. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19134. ASSERT_TRUE(res2);
  19135. // Weak ETag in If-Range -> full content (200), not partial (206)
  19136. EXPECT_EQ(200, res2->status);
  19137. EXPECT_EQ(content, res2->body);
  19138. EXPECT_FALSE(res2->has_header("Content-Range"));
  19139. // Range request with non-matching If-Range (ETag): should get 200 (full
  19140. // content)
  19141. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19142. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19143. ASSERT_TRUE(res3);
  19144. EXPECT_EQ(200, res3->status);
  19145. EXPECT_EQ(content, res3->body);
  19146. EXPECT_FALSE(res3->has_header("Content-Range"));
  19147. // Range request with strong ETag (hypothetical - our server doesn't generate
  19148. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19149. // should return full content)
  19150. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19151. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19152. ASSERT_TRUE(res4);
  19153. EXPECT_EQ(200, res4->status);
  19154. EXPECT_EQ(content, res4->body);
  19155. EXPECT_FALSE(res4->has_header("Content-Range"));
  19156. svr.stop();
  19157. t.join();
  19158. std::remove(fname);
  19159. }
  19160. TEST(ETagTest, IfRangeWithDate) {
  19161. using namespace httplib;
  19162. // Create a test file
  19163. const char *fname = "if_range_date_testfile.txt";
  19164. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19165. {
  19166. std::ofstream ofs(fname);
  19167. ofs << content;
  19168. ASSERT_TRUE(ofs.good());
  19169. }
  19170. Server svr;
  19171. svr.set_mount_point("/static", ".");
  19172. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19173. svr.wait_until_ready();
  19174. Client cli(HOST, PORT);
  19175. // First request: get Last-Modified
  19176. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19177. ASSERT_TRUE(res1);
  19178. ASSERT_EQ(200, res1->status);
  19179. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19180. std::string last_modified = res1->get_header_value("Last-Modified");
  19181. // Range request with matching If-Range (date): should get 206
  19182. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19183. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19184. ASSERT_TRUE(res2);
  19185. EXPECT_EQ(206, res2->status);
  19186. EXPECT_EQ("FGHIJ", res2->body);
  19187. // Range request with old If-Range date: should get 200 (full content)
  19188. Headers h3 = {{"Range", "bytes=5-9"},
  19189. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19190. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19191. ASSERT_TRUE(res3);
  19192. EXPECT_EQ(200, res3->status);
  19193. EXPECT_EQ(content, res3->body);
  19194. // Range request with future If-Range date: should get 206
  19195. Headers h4 = {{"Range", "bytes=0-4"},
  19196. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19197. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19198. ASSERT_TRUE(res4);
  19199. EXPECT_EQ(206, res4->status);
  19200. EXPECT_EQ("ABCDE", res4->body);
  19201. svr.stop();
  19202. t.join();
  19203. std::remove(fname);
  19204. }
  19205. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19206. using namespace httplib;
  19207. const char *fname = "etag_malformed.txt";
  19208. const char *content = "malformed-etag";
  19209. {
  19210. std::ofstream ofs(fname);
  19211. ofs << content;
  19212. ASSERT_TRUE(ofs.good());
  19213. }
  19214. Server svr;
  19215. svr.set_mount_point("/static", ".");
  19216. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19217. svr.wait_until_ready();
  19218. Client cli(HOST, PORT);
  19219. // baseline: should get 200 and an ETag
  19220. auto res1 = cli.Get("/static/etag_malformed.txt");
  19221. ASSERT_TRUE(res1);
  19222. ASSERT_EQ(200, res1->status);
  19223. ASSERT_TRUE(res1->has_header("ETag"));
  19224. // Malformed ETag value (missing quotes) should be treated as non-matching
  19225. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19226. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19227. ASSERT_TRUE(res_bad);
  19228. EXPECT_EQ(200, res_bad->status);
  19229. // Whitespace-only header value should be considered invalid / non-matching
  19230. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19231. "Host: localhost\r\n"
  19232. "If-None-Match: \r\n"
  19233. "Connection: close\r\n"
  19234. "\r\n";
  19235. std::string out;
  19236. ASSERT_TRUE(send_request(5, raw_req, &out));
  19237. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19238. svr.stop();
  19239. t.join();
  19240. std::remove(fname);
  19241. }
  19242. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19243. using namespace httplib;
  19244. const char *fname = "ims_invalid_format.txt";
  19245. const char *content = "ims-bad-format";
  19246. {
  19247. std::ofstream ofs(fname);
  19248. ofs << content;
  19249. ASSERT_TRUE(ofs.good());
  19250. }
  19251. Server svr;
  19252. svr.set_mount_point("/static", ".");
  19253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19254. svr.wait_until_ready();
  19255. Client cli(HOST, PORT);
  19256. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19257. ASSERT_TRUE(res1);
  19258. ASSERT_EQ(200, res1->status);
  19259. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19260. // If-Modified-Since with invalid format should not result in 304
  19261. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19262. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19263. ASSERT_TRUE(res_bad);
  19264. EXPECT_EQ(200, res_bad->status);
  19265. // If-Range with invalid date format should be treated as mismatch -> full
  19266. // content (200)
  19267. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19268. {"If-Range", "invalid-date"}};
  19269. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19270. ASSERT_TRUE(res_ifrange);
  19271. EXPECT_EQ(200, res_ifrange->status);
  19272. svr.stop();
  19273. t.join();
  19274. std::remove(fname);
  19275. }
  19276. TEST(ETagTest, IfRangeWithMalformedETag) {
  19277. using namespace httplib;
  19278. const char *fname = "ifrange_malformed.txt";
  19279. const std::string content = "0123456789";
  19280. {
  19281. std::ofstream ofs(fname);
  19282. ofs << content;
  19283. ASSERT_TRUE(ofs.good());
  19284. }
  19285. Server svr;
  19286. svr.set_mount_point("/static", ".");
  19287. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19288. svr.wait_until_ready();
  19289. Client cli(HOST, PORT);
  19290. // First request: get ETag
  19291. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19292. ASSERT_TRUE(res1);
  19293. ASSERT_EQ(200, res1->status);
  19294. ASSERT_TRUE(res1->has_header("ETag"));
  19295. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19296. // full content (200)
  19297. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19298. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19299. ASSERT_TRUE(res2);
  19300. EXPECT_EQ(200, res2->status);
  19301. EXPECT_EQ(content, res2->body);
  19302. svr.stop();
  19303. t.join();
  19304. std::remove(fname);
  19305. }
  19306. TEST(ETagTest, ExtremeLargeDateValues) {
  19307. using namespace httplib;
  19308. const char *fname = "ims_extreme_date.txt";
  19309. const char *content = "ims-extreme-date";
  19310. {
  19311. std::ofstream ofs(fname);
  19312. ofs << content;
  19313. ASSERT_TRUE(ofs.good());
  19314. }
  19315. Server svr;
  19316. svr.set_mount_point("/static", ".");
  19317. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19318. svr.wait_until_ready();
  19319. Client cli(HOST, PORT);
  19320. auto res1 = cli.Get(std::string("/static/") + fname);
  19321. ASSERT_TRUE(res1);
  19322. ASSERT_EQ(200, res1->status);
  19323. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19324. // Extremely large year that may overflow date parsing routines.
  19325. Headers h_large_date = {
  19326. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19327. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19328. ASSERT_TRUE(res_bad);
  19329. // Expect server to treat this as invalid/mismatch and return full content
  19330. EXPECT_EQ(200, res_bad->status);
  19331. // If-Range with extremely large date should be treated as mismatch -> full
  19332. // content (200)
  19333. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19334. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19335. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19336. ASSERT_TRUE(res_ifrange);
  19337. EXPECT_EQ(200, res_ifrange->status);
  19338. svr.stop();
  19339. t.join();
  19340. std::remove(fname);
  19341. }
  19342. TEST(ETagTest, NegativeFileModificationTime) {
  19343. using namespace httplib;
  19344. const char *fname = "ims_negative_mtime.txt";
  19345. const std::string content = "negative-mtime";
  19346. {
  19347. std::ofstream ofs(fname);
  19348. ofs << content;
  19349. ASSERT_TRUE(ofs.good());
  19350. }
  19351. // Try to set file mtime to a negative value. This may fail on some
  19352. // platforms/filesystems; if it fails, the test will still verify server
  19353. // behaves safely by performing a regular conditional request.
  19354. #if defined(__APPLE__) || defined(__linux__)
  19355. bool set_negative = false;
  19356. do {
  19357. struct timeval times[2];
  19358. // access time: now
  19359. times[0].tv_sec = time(nullptr);
  19360. times[0].tv_usec = 0;
  19361. // modification time: negative (e.g., -1)
  19362. times[1].tv_sec = -1;
  19363. times[1].tv_usec = 0;
  19364. if (utimes(fname, times) == 0) { set_negative = true; }
  19365. } while (0);
  19366. #else
  19367. bool set_negative = false;
  19368. #endif
  19369. Server svr;
  19370. svr.set_mount_point("/static", ".");
  19371. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19372. svr.wait_until_ready();
  19373. Client cli(HOST, PORT);
  19374. auto res1 = cli.Get(std::string("/static/") + fname);
  19375. ASSERT_TRUE(res1);
  19376. ASSERT_EQ(200, res1->status);
  19377. bool has_last_modified = res1->has_header("Last-Modified");
  19378. std::string last_modified;
  19379. if (has_last_modified) {
  19380. last_modified = res1->get_header_value("Last-Modified");
  19381. }
  19382. if (set_negative) {
  19383. // If we successfully set a negative mtime, ensure server returns a
  19384. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19385. // with an old date and ensure server handles it without crash.
  19386. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19387. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19388. ASSERT_TRUE(res2);
  19389. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19390. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19391. } else {
  19392. // Could not set negative mtime on this platform; fall back to verifying
  19393. // that normal invalid/malformed dates are treated safely (non-304).
  19394. Headers h_bad_date = {
  19395. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19396. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19397. ASSERT_TRUE(res_bad);
  19398. EXPECT_EQ(200, res_bad->status);
  19399. }
  19400. svr.stop();
  19401. t.join();
  19402. std::remove(fname);
  19403. }
  19404. //==============================================================================
  19405. // Integration Tests with Server
  19406. //==============================================================================
  19407. class SSEIntegrationTest : public ::testing::Test {
  19408. protected:
  19409. void SetUp() override {
  19410. stop_server_.store(false);
  19411. events_.clear();
  19412. server_ = httplib::detail::make_unique<Server>();
  19413. setup_server();
  19414. start_server();
  19415. }
  19416. void TearDown() override {
  19417. stop_server_.store(true);
  19418. event_cv_.notify_all();
  19419. server_->stop();
  19420. if (server_thread_.joinable()) { server_thread_.join(); }
  19421. }
  19422. void setup_server() {
  19423. // Simple SSE endpoint
  19424. server_->Get("/events", [this](const Request &req, Response &res) {
  19425. auto last_id = req.get_header_value("Last-Event-ID");
  19426. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19427. res.set_chunked_content_provider(
  19428. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19429. std::unique_lock<std::mutex> lock(event_mutex_);
  19430. if (event_cv_.wait_for(
  19431. lock, std::chrono::milliseconds(200), [this] {
  19432. return !events_.empty() || stop_server_.load();
  19433. })) {
  19434. if (stop_server_.load()) { return false; }
  19435. if (!events_.empty()) {
  19436. std::string event = events_.front();
  19437. events_.erase(events_.begin());
  19438. sink.write(event.data(), event.size());
  19439. return true;
  19440. }
  19441. }
  19442. return !stop_server_.load();
  19443. });
  19444. });
  19445. // Endpoint that returns error
  19446. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19447. res.status = 500;
  19448. res.set_content("Internal Server Error", "text/plain");
  19449. });
  19450. // Endpoint for custom event types
  19451. server_->Get("/custom-events", [](const Request &, Response &res) {
  19452. res.set_chunked_content_provider(
  19453. "text/event-stream", [](size_t offset, DataSink &sink) {
  19454. if (offset == 0) {
  19455. std::string event = "event: update\ndata: updated\n\n"
  19456. "event: delete\ndata: deleted\n\n";
  19457. sink.write(event.data(), event.size());
  19458. }
  19459. return false; // End stream after sending
  19460. });
  19461. });
  19462. }
  19463. void start_server() {
  19464. port_ = server_->bind_to_any_port(HOST);
  19465. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19466. // Wait for server to start
  19467. while (!server_->is_running()) {
  19468. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19469. }
  19470. }
  19471. int get_port() const { return port_; }
  19472. void send_event(const std::string &event) {
  19473. std::lock_guard<std::mutex> lock(event_mutex_);
  19474. events_.push_back(event);
  19475. event_cv_.notify_all();
  19476. }
  19477. std::unique_ptr<Server> server_;
  19478. std::thread server_thread_;
  19479. std::mutex event_mutex_;
  19480. std::condition_variable event_cv_;
  19481. std::vector<std::string> events_;
  19482. std::atomic<bool> stop_server_{false};
  19483. std::string last_received_event_id_;
  19484. int port_ = 0;
  19485. };
  19486. //==============================================================================
  19487. // SSE Parsing Tests
  19488. //==============================================================================
  19489. class SSEParsingTest : public SSEIntegrationTest {
  19490. protected:
  19491. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19492. // A trailing sentinel event tells when the whole stream has been parsed.
  19493. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19494. auto body = stream + "event: end\ndata: end\n\n";
  19495. server_->Get("/parse", [body](const Request &, Response &res) {
  19496. res.set_content(body, "text/event-stream");
  19497. });
  19498. return collect("/parse");
  19499. }
  19500. // Runs SSEClient against path until an "end" event arrives and returns the
  19501. // messages dispatched before it
  19502. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19503. Client client(HOST, get_port());
  19504. sse::SSEClient sse(client, path);
  19505. std::mutex mutex;
  19506. std::condition_variable cv;
  19507. std::vector<sse::SSEMessage> messages;
  19508. auto done = false;
  19509. sse.on_message([&](const sse::SSEMessage &msg) {
  19510. std::lock_guard<std::mutex> lock(mutex);
  19511. // Ignore a replay from a reconnect that races with stop()
  19512. if (!done) { messages.push_back(msg); }
  19513. });
  19514. sse.on_event("end", [&](const sse::SSEMessage &) {
  19515. std::lock_guard<std::mutex> lock(mutex);
  19516. done = true;
  19517. cv.notify_all();
  19518. });
  19519. sse.set_reconnect_interval(100);
  19520. sse.start_async();
  19521. {
  19522. std::unique_lock<std::mutex> lock(mutex);
  19523. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19524. }
  19525. sse.stop();
  19526. EXPECT_TRUE(done);
  19527. return messages;
  19528. }
  19529. };
  19530. TEST_F(SSEParsingTest, SingleLineData) {
  19531. auto msgs = parse("data: hello\n\n");
  19532. ASSERT_EQ(msgs.size(), 1u);
  19533. EXPECT_EQ(msgs[0].data, "hello");
  19534. EXPECT_EQ(msgs[0].event, "message");
  19535. }
  19536. TEST_F(SSEParsingTest, MultiLineData) {
  19537. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19538. ASSERT_EQ(msgs.size(), 1u);
  19539. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19540. }
  19541. TEST_F(SSEParsingTest, CustomEventType) {
  19542. auto msgs = parse("event: update\ndata: payload\n\n");
  19543. ASSERT_EQ(msgs.size(), 1u);
  19544. EXPECT_EQ(msgs[0].event, "update");
  19545. EXPECT_EQ(msgs[0].data, "payload");
  19546. }
  19547. TEST_F(SSEParsingTest, EventIdHandling) {
  19548. auto msgs = parse("id: 12345\ndata: test\n\n");
  19549. ASSERT_EQ(msgs.size(), 1u);
  19550. EXPECT_EQ(msgs[0].id, "12345");
  19551. }
  19552. TEST_F(SSEParsingTest, EmptyEventId) {
  19553. auto msgs = parse("id:\ndata: test\n\n");
  19554. ASSERT_EQ(msgs.size(), 1u);
  19555. EXPECT_EQ(msgs[0].id, "");
  19556. }
  19557. TEST_F(SSEParsingTest, CommentsIgnored) {
  19558. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19559. ASSERT_EQ(msgs.size(), 1u);
  19560. EXPECT_EQ(msgs[0].data, "hello");
  19561. EXPECT_EQ(msgs[0].event, "message");
  19562. }
  19563. TEST_F(SSEParsingTest, ColonInValue) {
  19564. auto msgs = parse("data: hello:world:test\n\n");
  19565. ASSERT_EQ(msgs.size(), 1u);
  19566. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19567. }
  19568. TEST_F(SSEParsingTest, FieldNameOnly) {
  19569. // A line without a colon is a field name with an empty value
  19570. auto msgs = parse("data\n\n");
  19571. ASSERT_EQ(msgs.size(), 1u);
  19572. EXPECT_EQ(msgs[0].data, "");
  19573. }
  19574. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19575. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19576. ASSERT_EQ(msgs.size(), 1u);
  19577. EXPECT_EQ(msgs[0].event, "update");
  19578. EXPECT_EQ(msgs[0].data, "hello");
  19579. }
  19580. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19581. auto msgs = parse("data\r\n\r\n");
  19582. ASSERT_EQ(msgs.size(), 1u);
  19583. EXPECT_EQ(msgs[0].data, "");
  19584. }
  19585. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19586. auto msgs = parse("event: update\rdata: hello\r\r");
  19587. ASSERT_EQ(msgs.size(), 1u);
  19588. EXPECT_EQ(msgs[0].event, "update");
  19589. EXPECT_EQ(msgs[0].data, "hello");
  19590. }
  19591. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19592. // Chunk boundaries fall inside every \r\n and right before the first one
  19593. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19594. "\n\r", "\nevent: end\ndata: end\n\n"};
  19595. server_->Get("/split", [chunks](const Request &, Response &res) {
  19596. auto i = std::make_shared<size_t>(0);
  19597. res.set_chunked_content_provider(
  19598. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19599. if (*i == chunks.size()) {
  19600. sink.done();
  19601. } else {
  19602. sink.write(chunks[*i].data(), chunks[*i].size());
  19603. (*i)++;
  19604. }
  19605. return true;
  19606. });
  19607. });
  19608. auto msgs = collect("/split");
  19609. ASSERT_EQ(msgs.size(), 1u);
  19610. EXPECT_EQ(msgs[0].event, "update");
  19611. EXPECT_EQ(msgs[0].data, "hello");
  19612. }
  19613. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19614. // Only a BOM at the start of the stream is ignored
  19615. auto msgs = parse("\xEF\xBB\xBF"
  19616. "data: first\n\n"
  19617. "\xEF\xBB\xBF"
  19618. "data: second\n\n");
  19619. ASSERT_EQ(msgs.size(), 1u);
  19620. EXPECT_EQ(msgs[0].data, "first");
  19621. }
  19622. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19623. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19624. ASSERT_EQ(msgs.size(), 1u);
  19625. EXPECT_EQ(msgs[0].data, "hello");
  19626. EXPECT_EQ(msgs[0].event, "message");
  19627. }
  19628. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19629. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19630. ASSERT_EQ(msgs.size(), 2u);
  19631. EXPECT_EQ(msgs[0].data, "hello");
  19632. EXPECT_EQ(msgs[1].data, "hello");
  19633. }
  19634. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19635. // An event without data is not dispatched, and its type must not leak
  19636. // into the next event
  19637. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19638. ASSERT_EQ(msgs.size(), 1u);
  19639. EXPECT_EQ(msgs[0].event, "message");
  19640. EXPECT_EQ(msgs[0].data, "hello");
  19641. }
  19642. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19643. // The first connection sends only an id; the second echoes back the
  19644. // Last-Event-ID it was reconnected with
  19645. std::atomic<int> connection_count{0};
  19646. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19647. if (connection_count++ == 0) {
  19648. res.set_content("id: 42\n\n", "text/event-stream");
  19649. } else {
  19650. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19651. "\n\nevent: end\ndata: end\n\n",
  19652. "text/event-stream");
  19653. }
  19654. });
  19655. auto msgs = collect("/id-only");
  19656. ASSERT_EQ(msgs.size(), 1u);
  19657. EXPECT_EQ(msgs[0].data, "42");
  19658. }
  19659. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19660. // The first connection sets an id and then clears it with an empty one; the
  19661. // second reports whether it was reconnected with a Last-Event-ID
  19662. std::atomic<int> connection_count{0};
  19663. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19664. if (connection_count++ == 0) {
  19665. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19666. "text/event-stream");
  19667. } else {
  19668. res.set_content(
  19669. std::string("data: ") +
  19670. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19671. "\n\nevent: end\ndata: end\n\n",
  19672. "text/event-stream");
  19673. }
  19674. });
  19675. auto msgs = collect("/id-clear");
  19676. ASSERT_EQ(msgs.size(), 3u);
  19677. EXPECT_EQ(msgs[0].id, "1");
  19678. EXPECT_EQ(msgs[1].id, "");
  19679. EXPECT_EQ(msgs[2].data, "not sent");
  19680. }
  19681. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19682. // The first connection sets an id and then sends ids that cannot be carried
  19683. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19684. // with
  19685. std::atomic<int> connection_count{0};
  19686. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19687. if (connection_count++ == 0) {
  19688. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19689. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19690. "text/event-stream");
  19691. } else {
  19692. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19693. "\n\nevent: end\ndata: end\n\n",
  19694. "text/event-stream");
  19695. }
  19696. });
  19697. auto msgs = collect("/id-unsendable");
  19698. ASSERT_EQ(msgs.size(), 1u);
  19699. EXPECT_EQ(msgs[0].data, "42");
  19700. }
  19701. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19702. auto msgs = parse("event: notification\nid: evt-42\n"
  19703. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19704. ASSERT_EQ(msgs.size(), 1u);
  19705. EXPECT_EQ(msgs[0].event, "notification");
  19706. EXPECT_EQ(msgs[0].id, "evt-42");
  19707. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19708. }
  19709. TEST(SSEMessageTest, Clear) {
  19710. sse::SSEMessage msg;
  19711. msg.event = "custom";
  19712. msg.data = "some data";
  19713. msg.id = "123";
  19714. msg.clear();
  19715. EXPECT_EQ(msg.event, "message");
  19716. EXPECT_EQ(msg.data, "");
  19717. EXPECT_EQ(msg.id, "");
  19718. }
  19719. //==============================================================================
  19720. // SSE Integration Tests
  19721. //==============================================================================
  19722. // Test: Successful connection and on_open callback
  19723. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19724. // Add a simple endpoint that sends one event and closes
  19725. server_->Get("/simple-event", [](const Request &, Response &res) {
  19726. res.set_chunked_content_provider(
  19727. "text/event-stream", [](size_t offset, DataSink &sink) {
  19728. if (offset == 0) {
  19729. std::string event = "data: hello\n\n";
  19730. sink.write(event.data(), event.size());
  19731. }
  19732. return false; // Close stream after sending
  19733. });
  19734. });
  19735. Client client("localhost", get_port());
  19736. sse::SSEClient sse(client, "/simple-event");
  19737. std::atomic<bool> open_called{false};
  19738. std::atomic<bool> message_received{false};
  19739. sse.on_open([&open_called]() { open_called.store(true); });
  19740. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19741. if (msg.data == "hello") { message_received.store(true); }
  19742. });
  19743. sse.set_reconnect_interval(100);
  19744. sse.set_max_reconnect_attempts(1);
  19745. // Start async
  19746. sse.start_async();
  19747. // Wait for message to be processed
  19748. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19749. sse.stop();
  19750. EXPECT_TRUE(open_called.load());
  19751. EXPECT_TRUE(message_received.load());
  19752. }
  19753. // Test: on_message callback
  19754. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19755. // Endpoint that sends multiple events then closes
  19756. server_->Get("/multi-event", [](const Request &, Response &res) {
  19757. res.set_chunked_content_provider(
  19758. "text/event-stream", [](size_t offset, DataSink &sink) {
  19759. if (offset == 0) {
  19760. std::string events = "data: message1\n\ndata: message2\n\n";
  19761. sink.write(events.data(), events.size());
  19762. }
  19763. return false;
  19764. });
  19765. });
  19766. Client client("localhost", get_port());
  19767. sse::SSEClient sse(client, "/multi-event");
  19768. std::vector<std::string> received_messages;
  19769. std::mutex messages_mutex;
  19770. sse.on_message([&](const sse::SSEMessage &msg) {
  19771. std::lock_guard<std::mutex> lock(messages_mutex);
  19772. received_messages.push_back(msg.data);
  19773. });
  19774. sse.set_reconnect_interval(100);
  19775. sse.set_max_reconnect_attempts(1);
  19776. sse.start_async();
  19777. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19778. sse.stop();
  19779. std::lock_guard<std::mutex> lock(messages_mutex);
  19780. EXPECT_GE(received_messages.size(), 2u);
  19781. if (received_messages.size() >= 2) {
  19782. EXPECT_EQ(received_messages[0], "message1");
  19783. EXPECT_EQ(received_messages[1], "message2");
  19784. }
  19785. }
  19786. // Test: on_event for specific types
  19787. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19788. Client client("localhost", get_port());
  19789. sse::SSEClient sse(client, "/custom-events");
  19790. std::atomic<bool> update_received{false};
  19791. std::atomic<bool> delete_received{false};
  19792. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19793. if (msg.data == "updated") { update_received.store(true); }
  19794. });
  19795. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19796. if (msg.data == "deleted") { delete_received.store(true); }
  19797. });
  19798. sse.set_max_reconnect_attempts(1);
  19799. sse.start_async();
  19800. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19801. sse.stop();
  19802. EXPECT_TRUE(update_received.load());
  19803. EXPECT_TRUE(delete_received.load());
  19804. }
  19805. // Test: on_error callback on connection failure
  19806. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19807. // Connect to a non-existent port
  19808. Client client("localhost", 59999);
  19809. sse::SSEClient sse(client, "/events");
  19810. std::atomic<bool> error_called{false};
  19811. Error received_error = Error::Success;
  19812. sse.on_error([&](Error err) {
  19813. error_called.store(true);
  19814. received_error = err;
  19815. });
  19816. sse.set_reconnect_interval(50);
  19817. sse.set_max_reconnect_attempts(1);
  19818. sse.start_async();
  19819. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19820. sse.stop();
  19821. EXPECT_TRUE(error_called.load());
  19822. EXPECT_NE(received_error, Error::Success);
  19823. }
  19824. // Test: Last-Event-ID header sent on reconnect
  19825. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19826. // Endpoint that sends event with ID
  19827. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19828. res.set_chunked_content_provider(
  19829. "text/event-stream", [](size_t offset, DataSink &sink) {
  19830. if (offset == 0) {
  19831. std::string event = "id: evt-123\ndata: test\n\n";
  19832. sink.write(event.data(), event.size());
  19833. }
  19834. return false;
  19835. });
  19836. });
  19837. Client client("localhost", get_port());
  19838. sse::SSEClient sse(client, "/event-with-id");
  19839. std::atomic<bool> id_received{false};
  19840. sse.on_message([&](const sse::SSEMessage &msg) {
  19841. if (!msg.id.empty()) { id_received.store(true); }
  19842. });
  19843. sse.set_reconnect_interval(100);
  19844. sse.set_max_reconnect_attempts(1);
  19845. sse.start_async();
  19846. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19847. sse.stop();
  19848. EXPECT_TRUE(id_received.load());
  19849. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19850. }
  19851. // Test: Manual stop
  19852. TEST_F(SSEIntegrationTest, ManualStop) {
  19853. // Endpoint that sends one event and stays open briefly
  19854. std::atomic<bool> handler_running{true};
  19855. server_->Get("/stay-open", [&handler_running](const Request &,
  19856. Response &res) {
  19857. res.set_chunked_content_provider(
  19858. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19859. if (offset == 0) {
  19860. std::string event = "data: connected\n\n";
  19861. sink.write(event.data(), event.size());
  19862. }
  19863. // Keep connection open while handler_running is true
  19864. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19865. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19866. }
  19867. return false;
  19868. });
  19869. });
  19870. Client client("localhost", get_port());
  19871. sse::SSEClient sse(client, "/stay-open");
  19872. std::atomic<bool> connected{false};
  19873. sse.on_open([&connected]() { connected.store(true); });
  19874. sse.set_reconnect_interval(100);
  19875. sse.set_max_reconnect_attempts(1);
  19876. sse.start_async();
  19877. // Wait for connection to establish
  19878. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19879. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19880. }
  19881. EXPECT_TRUE(connected.load());
  19882. EXPECT_TRUE(sse.is_connected());
  19883. // Signal handler to stop
  19884. handler_running.store(false);
  19885. // Stop SSE client
  19886. sse.stop();
  19887. EXPECT_FALSE(sse.is_connected());
  19888. }
  19889. // Test: SSEClient with custom headers
  19890. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19891. // Setup a server endpoint that checks for custom header
  19892. std::atomic<bool> header_received{false};
  19893. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19894. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19895. header_received.store(true);
  19896. }
  19897. res.set_chunked_content_provider("text/event-stream",
  19898. [](size_t, DataSink &) { return false; });
  19899. });
  19900. Client client("localhost", get_port());
  19901. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19902. sse::SSEClient sse(client, "/header-check", headers);
  19903. sse.set_max_reconnect_attempts(1);
  19904. sse.start_async();
  19905. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19906. sse.stop();
  19907. EXPECT_TRUE(header_received.load());
  19908. }
  19909. // Test: Reconnect interval configuration
  19910. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19911. Client client("localhost", get_port());
  19912. sse::SSEClient sse(client, "/events");
  19913. auto &result = sse.set_reconnect_interval(500);
  19914. // Builder pattern should return reference to self
  19915. EXPECT_EQ(&result, &sse);
  19916. }
  19917. // Test: Max reconnect attempts
  19918. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19919. // Connect to non-existent port to force reconnects
  19920. Client client("localhost", 59998);
  19921. sse::SSEClient sse(client, "/events");
  19922. std::atomic<int> error_count{0};
  19923. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19924. sse.set_reconnect_interval(50);
  19925. sse.set_max_reconnect_attempts(2);
  19926. auto start = std::chrono::steady_clock::now();
  19927. sse.start(); // Blocking call
  19928. auto end = std::chrono::steady_clock::now();
  19929. // Should have stopped after 2 failed attempts
  19930. EXPECT_GE(error_count.load(), 2);
  19931. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19932. auto duration =
  19933. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19934. #ifdef _WIN32
  19935. // Windows is much slower for socket connection failures
  19936. EXPECT_LT(duration.count(), 7000);
  19937. #else
  19938. EXPECT_LT(duration.count(), 1000);
  19939. #endif
  19940. }
  19941. // Test: Multi-line data in integration
  19942. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19943. // Endpoint with multi-line data
  19944. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19945. res.set_chunked_content_provider(
  19946. "text/event-stream", [](size_t offset, DataSink &sink) {
  19947. if (offset == 0) {
  19948. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19949. sink.write(event.data(), event.size());
  19950. }
  19951. return false;
  19952. });
  19953. });
  19954. Client client("localhost", get_port());
  19955. sse::SSEClient sse(client, "/multiline-data");
  19956. std::string received_data;
  19957. std::mutex data_mutex;
  19958. sse.on_message([&](const sse::SSEMessage &msg) {
  19959. std::lock_guard<std::mutex> lock(data_mutex);
  19960. received_data = msg.data;
  19961. });
  19962. sse.set_reconnect_interval(100);
  19963. sse.set_max_reconnect_attempts(1);
  19964. sse.start_async();
  19965. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19966. sse.stop();
  19967. std::lock_guard<std::mutex> lock(data_mutex);
  19968. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19969. }
  19970. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19971. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19972. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19973. DataSink &sink) {
  19974. if (offset == 0) {
  19975. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19976. sink.write(events.data(), events.size());
  19977. }
  19978. return false;
  19979. });
  19980. });
  19981. Client client("localhost", get_port());
  19982. sse::SSEClient sse(client, "/empty-data-lines");
  19983. std::mutex mutex;
  19984. std::condition_variable cv;
  19985. std::vector<std::string> received;
  19986. sse.on_message([&](const sse::SSEMessage &msg) {
  19987. std::lock_guard<std::mutex> lock(mutex);
  19988. received.push_back(msg.data);
  19989. cv.notify_all();
  19990. });
  19991. sse.set_max_reconnect_attempts(1);
  19992. sse.start_async();
  19993. {
  19994. std::unique_lock<std::mutex> lock(mutex);
  19995. cv.wait_for(lock, std::chrono::seconds(2),
  19996. [&] { return received.size() >= 3; });
  19997. }
  19998. sse.stop();
  19999. ASSERT_GE(received.size(), 3u);
  20000. EXPECT_EQ(received[0], "");
  20001. EXPECT_EQ(received[1], "\nhello");
  20002. EXPECT_EQ(received[2], "");
  20003. }
  20004. // Test: Auto-reconnect after server disconnection
  20005. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20006. std::atomic<int> connection_count{0};
  20007. std::atomic<int> message_count{0};
  20008. // Endpoint that sends one event and closes, forcing reconnect
  20009. server_->Get("/reconnect-test",
  20010. [&connection_count](const Request &, Response &res) {
  20011. connection_count.fetch_add(1);
  20012. res.set_chunked_content_provider(
  20013. "text/event-stream", [](size_t offset, DataSink &sink) {
  20014. if (offset == 0) {
  20015. std::string event = "data: hello\n\n";
  20016. sink.write(event.data(), event.size());
  20017. }
  20018. return false; // Close connection after sending
  20019. });
  20020. });
  20021. Client client("localhost", get_port());
  20022. sse::SSEClient sse(client, "/reconnect-test");
  20023. sse.on_message([&message_count](const sse::SSEMessage &) {
  20024. message_count.fetch_add(1);
  20025. });
  20026. sse.set_reconnect_interval(100);
  20027. sse.set_max_reconnect_attempts(3);
  20028. sse.start_async();
  20029. // Wait long enough for multiple reconnects
  20030. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20031. sse.stop();
  20032. // Should have connected multiple times (initial + reconnects)
  20033. EXPECT_GE(connection_count.load(), 2);
  20034. // Should have received messages from multiple connections
  20035. EXPECT_GE(message_count.load(), 2);
  20036. }
  20037. // Test: A retry field that is not all ASCII digits is ignored
  20038. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20039. std::atomic<int> connection_count{0};
  20040. server_->Get("/bad-retry",
  20041. [&connection_count](const Request &, Response &res) {
  20042. connection_count.fetch_add(1);
  20043. res.set_chunked_content_provider(
  20044. "text/event-stream", [](size_t offset, DataSink &sink) {
  20045. if (offset == 0) {
  20046. std::string event = "retry: -1\ndata: hello\n\n";
  20047. sink.write(event.data(), event.size());
  20048. }
  20049. return false;
  20050. });
  20051. });
  20052. Client client("localhost", get_port());
  20053. sse::SSEClient sse(client, "/bad-retry");
  20054. sse.set_reconnect_interval(10000);
  20055. sse.start_async();
  20056. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20057. sse.stop();
  20058. EXPECT_EQ(connection_count.load(), 1);
  20059. }
  20060. // Test: A retry field of all ASCII digits sets the reconnection time
  20061. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20062. std::mutex mutex;
  20063. std::condition_variable cv;
  20064. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20065. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20066. {
  20067. std::lock_guard<std::mutex> lock(mutex);
  20068. connected_at.push_back(std::chrono::steady_clock::now());
  20069. cv.notify_all();
  20070. }
  20071. res.set_chunked_content_provider(
  20072. "text/event-stream", [](size_t offset, DataSink &sink) {
  20073. if (offset == 0) {
  20074. std::string event = "retry: 0\ndata: hello\n\n";
  20075. sink.write(event.data(), event.size());
  20076. }
  20077. return false;
  20078. });
  20079. });
  20080. Client client("localhost", get_port());
  20081. sse::SSEClient sse(client, "/zero-retry");
  20082. sse.set_reconnect_interval(10000);
  20083. sse.start_async();
  20084. {
  20085. std::unique_lock<std::mutex> lock(mutex);
  20086. cv.wait_for(lock, std::chrono::seconds(5),
  20087. [&] { return connected_at.size() >= 2; });
  20088. }
  20089. sse.stop();
  20090. // The server-supplied interval is applied, but never below 100ms, so
  20091. // "retry: 0" does not cause a busy reconnect loop
  20092. std::lock_guard<std::mutex> lock(mutex);
  20093. ASSERT_GE(connected_at.size(), 2u);
  20094. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20095. connected_at[1] - connected_at[0])
  20096. .count();
  20097. EXPECT_GE(interval_ms, 100);
  20098. }
  20099. // Test: Last-Event-ID sent on reconnect
  20100. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20101. std::atomic<int> connection_count{0};
  20102. std::vector<std::string> received_last_event_ids;
  20103. std::mutex id_mutex;
  20104. // Endpoint that checks Last-Event-ID header and sends event with ID
  20105. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20106. int conn = connection_count.fetch_add(1);
  20107. // Capture the Last-Event-ID header from each connection
  20108. {
  20109. std::lock_guard<std::mutex> lock(id_mutex);
  20110. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20111. }
  20112. res.set_chunked_content_provider(
  20113. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20114. if (offset == 0) {
  20115. std::string event =
  20116. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20117. sink.write(event.data(), event.size());
  20118. }
  20119. return false;
  20120. });
  20121. });
  20122. Client client("localhost", get_port());
  20123. sse::SSEClient sse(client, "/reconnect-with-id");
  20124. sse.set_reconnect_interval(100);
  20125. sse.set_max_reconnect_attempts(3);
  20126. sse.start_async();
  20127. // Wait for at least 2 connections
  20128. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20129. sse.stop();
  20130. // Verify behavior
  20131. std::lock_guard<std::mutex> lock(id_mutex);
  20132. EXPECT_GE(received_last_event_ids.size(), 2u);
  20133. // First connection should have no Last-Event-ID
  20134. if (!received_last_event_ids.empty()) {
  20135. EXPECT_EQ(received_last_event_ids[0], "");
  20136. }
  20137. // Second connection should have Last-Event-ID from first connection
  20138. if (received_last_event_ids.size() >= 2) {
  20139. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20140. }
  20141. }
  20142. // Test: set_headers updates headers used on reconnect
  20143. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20144. std::vector<std::string> received_tokens;
  20145. std::mutex token_mutex;
  20146. // Endpoint that captures Authorization header
  20147. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20148. {
  20149. std::lock_guard<std::mutex> lock(token_mutex);
  20150. received_tokens.push_back(req.get_header_value("Authorization"));
  20151. }
  20152. res.set_chunked_content_provider(
  20153. "text/event-stream", [](size_t offset, DataSink &sink) {
  20154. if (offset == 0) {
  20155. std::string event = "data: hello\n\n";
  20156. sink.write(event.data(), event.size());
  20157. }
  20158. return false; // Close connection to trigger reconnect
  20159. });
  20160. });
  20161. Client client("localhost", get_port());
  20162. Headers headers = {{"Authorization", "Bearer old-token"}};
  20163. sse::SSEClient sse(client, "/auth-check", headers);
  20164. // Update headers on each successful connection
  20165. sse.on_open(
  20166. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20167. sse.set_reconnect_interval(100);
  20168. sse.set_max_reconnect_attempts(3);
  20169. sse.start_async();
  20170. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20171. sse.stop();
  20172. std::lock_guard<std::mutex> lock(token_mutex);
  20173. ASSERT_GE(received_tokens.size(), 2u);
  20174. // First connection uses original header
  20175. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20176. // Second connection uses updated header from set_headers
  20177. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20178. }
  20179. // Test: 401 allows reconnection (so on_error can refresh headers)
  20180. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20181. std::atomic<int> connection_count{0};
  20182. // Endpoint: returns 401 on first attempt, 200 on second
  20183. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20184. int conn = connection_count.fetch_add(1);
  20185. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20186. res.status = StatusCode::Unauthorized_401;
  20187. res.set_content("Unauthorized", "text/plain");
  20188. return;
  20189. }
  20190. res.set_chunked_content_provider(
  20191. "text/event-stream", [](size_t offset, DataSink &sink) {
  20192. if (offset == 0) {
  20193. std::string event = "data: authenticated\n\n";
  20194. sink.write(event.data(), event.size());
  20195. }
  20196. return false;
  20197. });
  20198. });
  20199. Client client("localhost", get_port());
  20200. Headers headers = {{"Authorization", "Bearer expired"}};
  20201. sse::SSEClient sse(client, "/auth-retry", headers);
  20202. std::atomic<bool> message_received{false};
  20203. // Refresh token on error
  20204. sse.on_error(
  20205. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20206. sse.on_message([&](const sse::SSEMessage &msg) {
  20207. if (msg.data == "authenticated") { message_received.store(true); }
  20208. });
  20209. sse.set_reconnect_interval(100);
  20210. sse.set_max_reconnect_attempts(3);
  20211. sse.start_async();
  20212. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20213. sse.stop();
  20214. // Should have reconnected after 401 and succeeded with new token
  20215. EXPECT_GE(connection_count.load(), 2);
  20216. EXPECT_TRUE(message_received.load());
  20217. }
  20218. TEST(Issue2318Test, EmptyHostString) {
  20219. {
  20220. httplib::Client cli_empty("", PORT);
  20221. auto res = cli_empty.Get("/");
  20222. ASSERT_FALSE(res);
  20223. EXPECT_EQ(httplib::Error::Connection, res.error());
  20224. }
  20225. {
  20226. httplib::Client cli(" ", PORT);
  20227. auto res = cli.Get("/");
  20228. ASSERT_FALSE(res);
  20229. EXPECT_EQ(httplib::Error::Connection, res.error());
  20230. }
  20231. }
  20232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20233. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20234. Server svr;
  20235. // Set a small payload limit (1KB)
  20236. svr.set_payload_max_length(1024);
  20237. svr.Post("/test", [&](const Request &req, Response &res) {
  20238. res.set_content("Body size: " + std::to_string(req.body.size()),
  20239. "text/plain");
  20240. });
  20241. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20242. auto se = detail::scope_exit([&] {
  20243. svr.stop();
  20244. listen_thread.join();
  20245. });
  20246. svr.wait_until_ready();
  20247. // Create data that compresses well but exceeds limit when decompressed
  20248. // 8KB of repeated null bytes compresses to a very small size
  20249. std::string original_data(8 * 1024, '\0');
  20250. // Compress the data using gzip
  20251. std::string compressed_data;
  20252. detail::gzip_compressor compressor;
  20253. compressor.compress(original_data.data(), original_data.size(), true,
  20254. [&](const char *data, size_t size) {
  20255. compressed_data.append(data, size);
  20256. return true;
  20257. });
  20258. // Verify compression worked (compressed should be much smaller)
  20259. ASSERT_LT(compressed_data.size(), original_data.size());
  20260. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20261. // Send compressed data with Content-Encoding: gzip
  20262. Client cli(HOST, PORT);
  20263. Headers headers = {{"Content-Encoding", "gzip"}};
  20264. auto res =
  20265. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20266. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20268. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20269. }
  20270. #endif
  20271. // ============================================================================
  20272. // OpenSSL-Specific Tests
  20273. // ============================================================================
  20274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20275. X509 *readCertificate(const std::string &strFileName) {
  20276. std::ifstream inStream(strFileName);
  20277. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20278. std::istreambuf_iterator<char>());
  20279. if (strCertPEM.empty()) return (nullptr);
  20280. BIO *pbCert = BIO_new(BIO_s_mem());
  20281. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20282. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20283. BIO_free(pbCert);
  20284. return (pCert);
  20285. }
  20286. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20287. std::ifstream inStream(strFileName);
  20288. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20289. std::istreambuf_iterator<char>());
  20290. if (strPrivateKeyPEM.empty()) return (nullptr);
  20291. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20292. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20293. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20294. BIO_free(pbPrivKey);
  20295. return (pPrivateKey);
  20296. }
  20297. TEST(BindServerTest, UpdateCerts) {
  20298. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20299. int port = svr.bind_to_any_port("0.0.0.0");
  20300. ASSERT_TRUE(svr.is_valid());
  20301. ASSERT_TRUE(port > 0);
  20302. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20303. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20304. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20305. ASSERT_TRUE(cert != nullptr);
  20306. ASSERT_TRUE(ca_cert != nullptr);
  20307. ASSERT_TRUE(key != nullptr);
  20308. X509_STORE *cert_store = X509_STORE_new();
  20309. X509_STORE_add_cert(cert_store, ca_cert);
  20310. // svr.update_certs(cert, key, cert_store); // deprecated
  20311. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20312. CLIENT_CA_CERT_FILE);
  20313. ASSERT_TRUE(svr.is_valid());
  20314. svr.stop();
  20315. X509_STORE_free(cert_store);
  20316. X509_free(cert);
  20317. X509_free(ca_cert);
  20318. EVP_PKEY_free(key);
  20319. }
  20320. // Test that update_certs() updates client CA list correctly
  20321. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20322. // Start with file-based constructor
  20323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20324. ASSERT_TRUE(svr.is_valid());
  20325. // Initially no client CA list should be set
  20326. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20327. ASSERT_TRUE(ssl_ctx != nullptr);
  20328. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20329. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20330. EXPECT_EQ(0, count_before);
  20331. // Now update with client CA (PEM string)
  20332. std::string cert_pem, key_pem, ca_pem;
  20333. read_file(SERVER_CERT_FILE, cert_pem);
  20334. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20335. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20336. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20337. ASSERT_TRUE(svr.is_valid());
  20338. // Now client CA list should be set
  20339. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20340. ASSERT_TRUE(ca_list_after != nullptr);
  20341. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20342. }
  20343. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20344. // Test that the file-path SSLServer constructor properly sets the client CA
  20345. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20346. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20347. ASSERT_TRUE(svr.is_valid());
  20348. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20349. ASSERT_TRUE(ssl_ctx != nullptr);
  20350. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20351. ASSERT_TRUE(ca_list != nullptr);
  20352. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20353. }
  20354. #endif
  20355. // ============================================================================
  20356. // MbedTLS-Specific Tests
  20357. // ============================================================================
  20358. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20359. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20360. using namespace httplib::tls;
  20361. // Track if callback was invoked
  20362. bool callback_invoked = false;
  20363. // The callback receives void* ctx which is actually MbedTlsContext*
  20364. // We can access the mbedtls_ssl_config via the context
  20365. auto setup_callback = [&callback_invoked](void *ctx) {
  20366. callback_invoked = true;
  20367. // Cast to MbedTlsContext* to access the ssl config
  20368. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20369. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20370. // Use static variables to hold certificate data (simplified for test)
  20371. static mbedtls_x509_crt own_cert;
  20372. static mbedtls_pk_context own_key;
  20373. static mbedtls_x509_crt ca_chain;
  20374. static bool initialized = false;
  20375. if (!initialized) {
  20376. mbedtls_x509_crt_init(&own_cert);
  20377. mbedtls_pk_init(&own_key);
  20378. mbedtls_x509_crt_init(&ca_chain);
  20379. // Load server certificate
  20380. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20381. return false;
  20382. }
  20383. // Load server private key.
  20384. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20385. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20386. #if MBEDTLS_VERSION_MAJOR == 3
  20387. ,
  20388. mbedtls_ctr_drbg_random, nullptr
  20389. #endif
  20390. ) != 0) {
  20391. return false;
  20392. }
  20393. // Load CA chain for client verification
  20394. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20395. return false;
  20396. }
  20397. initialized = true;
  20398. }
  20399. // Configure the SSL config
  20400. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20401. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20402. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20403. // Set minimum TLS version using mbedTLS native API
  20404. #if MBEDTLS_VERSION_MAJOR >= 3
  20405. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20406. #else
  20407. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20408. MBEDTLS_SSL_MINOR_VERSION_3);
  20409. #endif
  20410. return true;
  20411. };
  20412. SSLServer svr(setup_callback);
  20413. ASSERT_TRUE(svr.is_valid());
  20414. ASSERT_TRUE(callback_invoked);
  20415. svr.Get("/test", [&](const Request &req, Response &res) {
  20416. res.set_content("test", "text/plain");
  20417. auto cert = req.peer_cert();
  20418. ASSERT_TRUE(static_cast<bool>(cert));
  20419. auto common_name = cert.subject_cn();
  20420. EXPECT_EQ("Common Name", common_name);
  20421. });
  20422. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20423. auto se = detail::scope_exit([&] {
  20424. svr.stop();
  20425. t.join();
  20426. ASSERT_FALSE(svr.is_running());
  20427. });
  20428. svr.wait_until_ready();
  20429. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20430. cli.enable_server_certificate_verification(false);
  20431. cli.set_connection_timeout(30);
  20432. auto res = cli.Get("/test");
  20433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20434. ASSERT_EQ(StatusCode::OK_200, res->status);
  20435. }
  20436. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20437. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20438. // keep-alive SSL session, which reads through that config in
  20439. // mbedtls_ssl_close_notify.
  20440. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20442. ASSERT_TRUE(svr.is_valid());
  20443. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20444. res.set_content("test", "text/plain");
  20445. });
  20446. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20447. auto se = detail::scope_exit([&] {
  20448. svr.stop();
  20449. t.join();
  20450. ASSERT_FALSE(svr.is_running());
  20451. });
  20452. svr.wait_until_ready();
  20453. {
  20454. SSLClient cli(HOST, PORT);
  20455. cli.enable_server_certificate_verification(false);
  20456. cli.set_keep_alive(true);
  20457. auto res = cli.Get("/test");
  20458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20459. ASSERT_EQ(StatusCode::OK_200, res->status);
  20460. // cli is destructed here with the keep-alive SSL session still open.
  20461. }
  20462. }
  20463. #endif
  20464. // WebSocket Tests
  20465. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20466. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20467. // defining the meaning of these bits has been negotiated.
  20468. auto make_frame = [](uint8_t first_byte) {
  20469. std::string frame;
  20470. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20471. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20472. frame += "Hello";
  20473. return frame;
  20474. };
  20475. // RSV1 set (0x40)
  20476. {
  20477. detail::BufferStream strm;
  20478. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20479. ws::Opcode opcode;
  20480. std::string payload;
  20481. bool fin;
  20482. EXPECT_EQ(
  20483. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20484. ws::impl::FrameRead::Fail);
  20485. }
  20486. // RSV2 set (0x20)
  20487. {
  20488. detail::BufferStream strm;
  20489. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20490. ws::Opcode opcode;
  20491. std::string payload;
  20492. bool fin;
  20493. EXPECT_EQ(
  20494. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20495. ws::impl::FrameRead::Fail);
  20496. }
  20497. // RSV3 set (0x10)
  20498. {
  20499. detail::BufferStream strm;
  20500. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20501. ws::Opcode opcode;
  20502. std::string payload;
  20503. bool fin;
  20504. EXPECT_EQ(
  20505. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20506. ws::impl::FrameRead::Fail);
  20507. }
  20508. // No RSV bits set - should succeed
  20509. {
  20510. detail::BufferStream strm;
  20511. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20512. ws::Opcode opcode;
  20513. std::string payload;
  20514. bool fin;
  20515. EXPECT_EQ(
  20516. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20517. ws::impl::FrameRead::Ok);
  20518. EXPECT_EQ(ws::Opcode::Text, opcode);
  20519. EXPECT_EQ("Hello", payload);
  20520. EXPECT_TRUE(fin);
  20521. }
  20522. }
  20523. TEST(WebSocketTest, ControlFrameValidation) {
  20524. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20525. // payload length <= 125.
  20526. // Ping with FIN=0 - must be rejected
  20527. {
  20528. detail::BufferStream strm;
  20529. std::string frame;
  20530. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20531. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20532. strm.write(frame.data(), frame.size());
  20533. ws::Opcode opcode;
  20534. std::string payload;
  20535. bool fin;
  20536. EXPECT_EQ(
  20537. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20538. ws::impl::FrameRead::Fail);
  20539. }
  20540. // Close with FIN=0 - must be rejected
  20541. {
  20542. detail::BufferStream strm;
  20543. std::string frame;
  20544. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20545. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20546. strm.write(frame.data(), frame.size());
  20547. ws::Opcode opcode;
  20548. std::string payload;
  20549. bool fin;
  20550. EXPECT_EQ(
  20551. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20552. ws::impl::FrameRead::Fail);
  20553. }
  20554. // Ping with payload_len=126 (extended length) - must be rejected
  20555. {
  20556. detail::BufferStream strm;
  20557. std::string frame;
  20558. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20559. frame += static_cast<char>(126); // payload_len=126 (>125)
  20560. frame += static_cast<char>(0x00); // extended length high byte
  20561. frame += static_cast<char>(126); // extended length low byte
  20562. frame += std::string(126, 'x');
  20563. strm.write(frame.data(), frame.size());
  20564. ws::Opcode opcode;
  20565. std::string payload;
  20566. bool fin;
  20567. EXPECT_EQ(
  20568. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20569. ws::impl::FrameRead::Fail);
  20570. }
  20571. // Ping with FIN=1 and payload_len=125 - should succeed
  20572. {
  20573. detail::BufferStream strm;
  20574. std::string frame;
  20575. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20576. frame += static_cast<char>(125); // payload_len=125
  20577. frame += std::string(125, 'x');
  20578. strm.write(frame.data(), frame.size());
  20579. ws::Opcode opcode;
  20580. std::string payload;
  20581. bool fin;
  20582. EXPECT_EQ(
  20583. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20584. ws::impl::FrameRead::Ok);
  20585. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20586. EXPECT_EQ(125u, payload.size());
  20587. EXPECT_TRUE(fin);
  20588. }
  20589. }
  20590. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20591. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20592. // length MUST be 0.
  20593. // MSB set - must be rejected
  20594. {
  20595. detail::BufferStream strm;
  20596. std::string frame;
  20597. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20598. frame += static_cast<char>(127); // 64-bit extended length
  20599. frame += static_cast<char>(0x80); // MSB set (invalid)
  20600. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20601. strm.write(frame.data(), frame.size());
  20602. ws::Opcode opcode;
  20603. std::string payload;
  20604. bool fin;
  20605. EXPECT_EQ(
  20606. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20607. ws::impl::FrameRead::Fail);
  20608. }
  20609. // MSB clear - should pass length parsing (will be rejected by max_len,
  20610. // but that's a different check; use a small length to verify)
  20611. {
  20612. detail::BufferStream strm;
  20613. std::string frame;
  20614. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20615. frame += static_cast<char>(127); // 64-bit extended length
  20616. frame += std::string(7, '\0'); // high bytes = 0
  20617. frame += static_cast<char>(0x03); // length = 3
  20618. frame += "abc";
  20619. strm.write(frame.data(), frame.size());
  20620. ws::Opcode opcode;
  20621. std::string payload;
  20622. bool fin;
  20623. EXPECT_EQ(
  20624. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20625. ws::impl::FrameRead::Ok);
  20626. EXPECT_EQ(ws::Opcode::Text, opcode);
  20627. EXPECT_EQ("abc", payload);
  20628. }
  20629. }
  20630. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20631. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20632. // Valid UTF-8
  20633. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20634. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20635. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20636. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20637. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20638. // Invalid UTF-8
  20639. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20640. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20641. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20642. EXPECT_FALSE(
  20643. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20644. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20645. }
  20646. TEST(WebSocketTest, ConnectAndDisconnect) {
  20647. Server svr;
  20648. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20649. std::string msg;
  20650. while (ws.read(msg)) {}
  20651. });
  20652. auto port = svr.bind_to_any_port(HOST);
  20653. std::thread t([&]() { svr.listen_after_bind(); });
  20654. svr.wait_until_ready();
  20655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20656. auto res = client.connect();
  20657. ASSERT_TRUE(res);
  20658. EXPECT_EQ(Error::Success, res.error());
  20659. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20660. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20661. EXPECT_TRUE(client.is_open());
  20662. client.close();
  20663. EXPECT_FALSE(client.is_open());
  20664. svr.stop();
  20665. t.join();
  20666. }
  20667. TEST(WebSocketTest, ValidURL) {
  20668. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20669. EXPECT_TRUE(ws1.is_valid());
  20670. ws::WebSocketClient ws2("ws://example.com/path");
  20671. EXPECT_TRUE(ws2.is_valid());
  20672. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20673. EXPECT_TRUE(ws3.is_valid());
  20674. #ifdef CPPHTTPLIB_SSL_ENABLED
  20675. ws::WebSocketClient wss1("wss://example.com/path");
  20676. EXPECT_TRUE(wss1.is_valid());
  20677. ws::WebSocketClient wss2("wss://example.com:443/path");
  20678. EXPECT_TRUE(wss2.is_valid());
  20679. #endif
  20680. }
  20681. TEST(WebSocketTest, InvalidURL) {
  20682. // No scheme
  20683. ws::WebSocketClient ws1("localhost:8080/path");
  20684. EXPECT_FALSE(ws1.is_valid());
  20685. // No path
  20686. ws::WebSocketClient ws2("ws://localhost:8080");
  20687. EXPECT_FALSE(ws2.is_valid());
  20688. // Empty string
  20689. ws::WebSocketClient ws3("");
  20690. EXPECT_FALSE(ws3.is_valid());
  20691. // Missing host
  20692. ws::WebSocketClient ws4("ws://:8080/path");
  20693. EXPECT_FALSE(ws4.is_valid());
  20694. // Port number overflow — should not crash
  20695. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20696. EXPECT_FALSE(ws5.is_valid());
  20697. // Port out of range
  20698. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20699. EXPECT_FALSE(ws6.is_valid());
  20700. }
  20701. TEST(WebSocketTest, UnsupportedScheme) {
  20702. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20703. ws::WebSocketClient ws1("http://localhost:8080/path");
  20704. EXPECT_FALSE(ws1.is_valid());
  20705. ws::WebSocketClient ws2("https://localhost:8080/path");
  20706. EXPECT_FALSE(ws2.is_valid());
  20707. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20708. EXPECT_FALSE(ws3.is_valid());
  20709. #else
  20710. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20711. std::invalid_argument);
  20712. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20713. std::invalid_argument);
  20714. #endif
  20715. }
  20716. TEST(WebSocketTest, ConnectWhenInvalid) {
  20717. ws::WebSocketClient ws("not a valid url");
  20718. EXPECT_FALSE(ws.is_valid());
  20719. auto res = ws.connect();
  20720. EXPECT_FALSE(res);
  20721. EXPECT_EQ(Error::Connection, res.error());
  20722. EXPECT_EQ(-1, res.status());
  20723. }
  20724. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20725. // Grab a port that is free, then close it again so nothing listens there
  20726. Server svr;
  20727. auto port = svr.bind_to_any_port(HOST);
  20728. svr.stop();
  20729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20730. auto res = client.connect();
  20731. ASSERT_FALSE(res);
  20732. EXPECT_EQ(Error::Connection, res.error());
  20733. EXPECT_EQ(-1, res.status());
  20734. }
  20735. TEST(WebSocketTest, DefaultPort) {
  20736. ws::WebSocketClient ws1("ws://example.com/path");
  20737. EXPECT_TRUE(ws1.is_valid());
  20738. // ws:// defaults to port 80 (verified by successful parse)
  20739. #ifdef CPPHTTPLIB_SSL_ENABLED
  20740. ws::WebSocketClient ws2("wss://example.com/path");
  20741. EXPECT_TRUE(ws2.is_valid());
  20742. // wss:// defaults to port 443 (verified by successful parse)
  20743. #endif
  20744. }
  20745. TEST(WebSocketTest, IPv6LiteralAddress) {
  20746. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20747. EXPECT_TRUE(ws1.is_valid());
  20748. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20749. EXPECT_TRUE(ws2.is_valid());
  20750. }
  20751. TEST(WebSocketTest, ComplexPath) {
  20752. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20753. EXPECT_TRUE(ws1.is_valid());
  20754. ws::WebSocketClient ws2("ws://localhost:8080/");
  20755. EXPECT_TRUE(ws2.is_valid());
  20756. }
  20757. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20758. Server svr;
  20759. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20760. std::string msg;
  20761. while (ws.read(msg)) {}
  20762. });
  20763. auto port = svr.bind_to_any_port(HOST);
  20764. std::thread t([&]() { svr.listen_after_bind(); });
  20765. svr.wait_until_ready();
  20766. auto another_host = "example.com";
  20767. auto wrong_ip = "192.0.2.1";
  20768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20769. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20770. ASSERT_TRUE(client.connect());
  20771. EXPECT_TRUE(client.is_open());
  20772. client.close();
  20773. svr.stop();
  20774. t.join();
  20775. }
  20776. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20777. Server svr;
  20778. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20779. std::string msg;
  20780. while (ws.read(msg)) {}
  20781. });
  20782. auto port = svr.bind_to_any_port(HOST);
  20783. std::thread t([&]() { svr.listen_after_bind(); });
  20784. svr.wait_until_ready();
  20785. auto wrong_ip = "192.0.2.1";
  20786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20787. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20788. client.set_connection_timeout(1);
  20789. client.set_read_timeout(1);
  20790. client.set_write_timeout(1);
  20791. EXPECT_FALSE(client.connect());
  20792. EXPECT_FALSE(client.is_open());
  20793. svr.stop();
  20794. t.join();
  20795. }
  20796. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20797. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20798. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20799. // (RFC 6761) is only a map key and the Host header value.
  20800. auto host = "target.invalid";
  20801. Server svr;
  20802. std::string received_host;
  20803. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20804. received_host = req.get_header_value("Host");
  20805. std::string msg;
  20806. while (ws.read(msg)) {}
  20807. });
  20808. auto port = svr.bind_to_any_port(HOST);
  20809. std::thread t([&]() { svr.listen_after_bind(); });
  20810. // ASSERT_* below returns from the test body, which would leave t joinable
  20811. // and make ~thread call std::terminate.
  20812. auto se = detail::scope_exit([&] {
  20813. svr.stop();
  20814. if (t.joinable()) { t.join(); }
  20815. });
  20816. svr.wait_until_ready();
  20817. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20818. std::to_string(port) + "/ws");
  20819. client.set_hostname_addr_map({{host, HOST}});
  20820. ASSERT_TRUE(client.connect());
  20821. EXPECT_TRUE(client.is_open());
  20822. client.close();
  20823. svr.stop();
  20824. t.join();
  20825. // The mapping only redirects the connection; the identity stays host_.
  20826. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20827. }
  20828. class WebSocketIntegrationTest : public ::testing::Test {
  20829. protected:
  20830. void SetUp() override {
  20831. server_ = httplib::detail::make_unique<Server>();
  20832. setup_server();
  20833. start_server();
  20834. }
  20835. void TearDown() override {
  20836. server_->stop();
  20837. if (server_thread_.joinable()) { server_thread_.join(); }
  20838. }
  20839. void setup_server() {
  20840. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20841. std::string msg;
  20842. ws::ReadResult ret;
  20843. while ((ret = ws.read(msg))) {
  20844. if (ret == ws::Binary) {
  20845. ws.send(msg.data(), msg.size());
  20846. } else {
  20847. ws.send(msg);
  20848. }
  20849. }
  20850. });
  20851. server_->WebSocket("/ws-echo-string",
  20852. [](const Request &, ws::WebSocket &ws) {
  20853. std::string msg;
  20854. while (ws.read(msg)) {
  20855. ws.send("echo: " + msg);
  20856. }
  20857. });
  20858. server_->WebSocket(
  20859. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20860. // Echo back request metadata
  20861. ws.send("path:" + req.path);
  20862. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20863. std::string msg;
  20864. while (ws.read(msg)) {}
  20865. });
  20866. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20867. std::string msg;
  20868. ws.read(msg); // wait for a message
  20869. ws.close();
  20870. });
  20871. server_->WebSocket("/ws-close-status",
  20872. [](const Request &, ws::WebSocket &ws) {
  20873. std::string msg;
  20874. ws.read(msg); // wait for a message
  20875. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20876. });
  20877. server_->WebSocket(
  20878. "/ws-subprotocol",
  20879. [](const Request &, ws::WebSocket &ws) {
  20880. std::string msg;
  20881. while (ws.read(msg)) {
  20882. ws.send(msg);
  20883. }
  20884. },
  20885. [](const std::vector<std::string> &protocols) -> std::string {
  20886. for (const auto &p : protocols) {
  20887. if (p == "graphql-ws") { return p; }
  20888. }
  20889. return "";
  20890. });
  20891. server_->WebSocket(
  20892. "/ws-subprotocol-unoffered",
  20893. [](const Request &, ws::WebSocket &ws) {
  20894. std::string msg;
  20895. while (ws.read(msg)) {
  20896. ws.send(msg);
  20897. }
  20898. },
  20899. [](const std::vector<std::string> &) -> std::string {
  20900. return "admin";
  20901. });
  20902. }
  20903. void start_server() {
  20904. port_ = server_->bind_to_any_port(HOST);
  20905. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20906. server_->wait_until_ready();
  20907. }
  20908. std::unique_ptr<Server> server_;
  20909. std::thread server_thread_;
  20910. int port_ = 0;
  20911. };
  20912. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20914. "/ws-echo");
  20915. ASSERT_TRUE(client.connect());
  20916. ASSERT_TRUE(client.is_open());
  20917. ASSERT_TRUE(client.send("Hello WebSocket"));
  20918. std::string msg;
  20919. EXPECT_EQ(ws::Text, client.read(msg));
  20920. EXPECT_EQ("Hello WebSocket", msg);
  20921. client.close();
  20922. }
  20923. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20925. "/ws-echo");
  20926. ASSERT_TRUE(client.connect());
  20927. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20928. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20929. std::string msg;
  20930. EXPECT_EQ(ws::Binary, client.read(msg));
  20931. EXPECT_EQ(binary_data, msg);
  20932. client.close();
  20933. }
  20934. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20935. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20936. "/ws-echo");
  20937. ASSERT_TRUE(client.connect());
  20938. for (int i = 0; i < 10; i++) {
  20939. auto text = "message " + std::to_string(i);
  20940. ASSERT_TRUE(client.send(text));
  20941. std::string msg;
  20942. ASSERT_TRUE(client.read(msg));
  20943. EXPECT_EQ(text, msg);
  20944. }
  20945. client.close();
  20946. }
  20947. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20948. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20949. "/ws-close");
  20950. ASSERT_TRUE(client.connect());
  20951. // Send a message to trigger the server to close
  20952. ASSERT_TRUE(client.send("trigger close"));
  20953. // The server will close, so read should return false
  20954. std::string msg;
  20955. EXPECT_FALSE(client.read(msg));
  20956. EXPECT_FALSE(client.is_open());
  20957. }
  20958. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20959. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20960. "/ws-echo");
  20961. ASSERT_TRUE(client.connect());
  20962. // 128KB message
  20963. std::string large_data(128 * 1024, 'X');
  20964. ASSERT_TRUE(client.send(large_data));
  20965. std::string msg;
  20966. ASSERT_TRUE(client.read(msg));
  20967. EXPECT_EQ(large_data, msg);
  20968. client.close();
  20969. }
  20970. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20972. "/ws-echo");
  20973. ASSERT_TRUE(client.connect());
  20974. const int num_threads = 4;
  20975. std::vector<std::thread> threads;
  20976. std::atomic<int> send_count{0};
  20977. for (int t = 0; t < num_threads; t++) {
  20978. threads.emplace_back([&client, &send_count, t]() {
  20979. for (int i = 0; i < 5; i++) {
  20980. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20981. if (client.send(text)) { send_count++; }
  20982. }
  20983. });
  20984. }
  20985. for (auto &th : threads) {
  20986. th.join();
  20987. }
  20988. int received = 0;
  20989. std::string msg;
  20990. while (received < send_count.load()) {
  20991. if (!client.read(msg)) { break; }
  20992. received++;
  20993. }
  20994. EXPECT_EQ(send_count.load(), received);
  20995. client.close();
  20996. }
  20997. TEST_F(WebSocketIntegrationTest, ReadString) {
  20998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20999. "/ws-echo-string");
  21000. ASSERT_TRUE(client.connect());
  21001. ASSERT_TRUE(client.send("hello"));
  21002. std::string msg;
  21003. ASSERT_TRUE(client.read(msg));
  21004. EXPECT_EQ("echo: hello", msg);
  21005. ASSERT_TRUE(client.send("world"));
  21006. ASSERT_TRUE(client.read(msg));
  21007. EXPECT_EQ("echo: world", msg);
  21008. client.close();
  21009. }
  21010. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21011. Headers headers = {{"X-Test-Header", "test-value"}};
  21012. ws::WebSocketClient client(
  21013. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21014. ASSERT_TRUE(client.connect());
  21015. std::string msg;
  21016. ASSERT_TRUE(client.read(msg));
  21017. EXPECT_EQ("path:/ws-request-info", msg);
  21018. ASSERT_TRUE(client.read(msg));
  21019. EXPECT_EQ("header:test-value", msg);
  21020. client.close();
  21021. }
  21022. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21023. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21024. "/ws-echo");
  21025. client.set_read_timeout(1, 0); // 1 second
  21026. ASSERT_TRUE(client.connect());
  21027. // Don't send anything — server echo handler waits for a message, so read()
  21028. // should time out. The connection survives it: nothing was consumed.
  21029. std::string msg;
  21030. EXPECT_EQ(client.read(msg), ws::Timeout);
  21031. EXPECT_TRUE(client.is_open());
  21032. // And it is still usable afterwards.
  21033. EXPECT_TRUE(client.send("after timeout"));
  21034. EXPECT_EQ(client.read(msg), ws::Text);
  21035. EXPECT_EQ(msg, "after timeout");
  21036. }
  21037. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21039. "/ws-echo");
  21040. client.set_read_timeout(1, 0);
  21041. ASSERT_TRUE(client.connect());
  21042. ASSERT_TRUE(client.send("first"));
  21043. std::string msg;
  21044. ASSERT_EQ(client.read(msg), ws::Text);
  21045. ASSERT_EQ(msg, "first");
  21046. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21047. // not be used with a read timeout: it would reprocess the previous message.
  21048. EXPECT_EQ(client.read(msg), ws::Timeout);
  21049. EXPECT_EQ(msg, "first");
  21050. }
  21051. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21052. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21053. "/ws-echo");
  21054. ASSERT_TRUE(client.connect());
  21055. // Setting it once the connection is open reaches the live stream, not just
  21056. // the seed for the next connect().
  21057. client.set_read_timeout(1, 0);
  21058. std::string msg;
  21059. EXPECT_EQ(client.read(msg), ws::Timeout);
  21060. EXPECT_TRUE(client.is_open());
  21061. }
  21062. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21063. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21064. "/ws-echo");
  21065. client.set_read_timeout(5, 0);
  21066. ASSERT_TRUE(client.connect());
  21067. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21068. // The server should reject it and close the connection.
  21069. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21070. client.send(oversized);
  21071. // The server's read() should have failed due to payload limit,
  21072. // so our read() should return false (connection closed).
  21073. std::string msg;
  21074. EXPECT_FALSE(client.read(msg));
  21075. }
  21076. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21078. "/ws-echo");
  21079. client.set_read_timeout(10, 0);
  21080. ASSERT_TRUE(client.connect());
  21081. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21082. // This should succeed.
  21083. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21084. ASSERT_TRUE(client.send(at_limit));
  21085. std::string msg;
  21086. ASSERT_TRUE(client.read(msg));
  21087. EXPECT_EQ(at_limit.size(), msg.size());
  21088. client.close();
  21089. }
  21090. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21091. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21092. "/nonexistent");
  21093. auto res = client.connect();
  21094. EXPECT_FALSE(res);
  21095. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21096. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21097. EXPECT_FALSE(client.is_open());
  21098. }
  21099. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21100. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21101. "/ws-echo");
  21102. ASSERT_TRUE(client.connect());
  21103. ASSERT_TRUE(client.send(""));
  21104. std::string msg;
  21105. EXPECT_EQ(ws::Text, client.read(msg));
  21106. EXPECT_EQ("", msg);
  21107. client.close();
  21108. }
  21109. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21111. "/ws-echo");
  21112. // First connection
  21113. ASSERT_TRUE(client.connect());
  21114. ASSERT_TRUE(client.send("first"));
  21115. std::string msg;
  21116. ASSERT_TRUE(client.read(msg));
  21117. EXPECT_EQ("first", msg);
  21118. client.close();
  21119. EXPECT_FALSE(client.is_open());
  21120. // Reconnect using the same client object
  21121. ASSERT_TRUE(client.connect());
  21122. ASSERT_TRUE(client.is_open());
  21123. ASSERT_TRUE(client.send("second"));
  21124. ASSERT_TRUE(client.read(msg));
  21125. EXPECT_EQ("second", msg);
  21126. client.close();
  21127. }
  21128. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21129. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21130. "/ws-close-status");
  21131. ASSERT_TRUE(client.connect());
  21132. // Trigger the server to close with GoingAway status
  21133. ASSERT_TRUE(client.send("trigger"));
  21134. // read() should return false after receiving the close frame
  21135. std::string msg;
  21136. EXPECT_FALSE(client.read(msg));
  21137. EXPECT_FALSE(client.is_open());
  21138. }
  21139. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21141. "/ws-echo");
  21142. ASSERT_TRUE(client.connect());
  21143. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21144. EXPECT_FALSE(client.is_open());
  21145. }
  21146. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21147. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21148. ws::WebSocketClient client(
  21149. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21150. ASSERT_TRUE(client.connect());
  21151. // Server should have selected graphql-ws
  21152. EXPECT_EQ("graphql-ws", client.subprotocol());
  21153. client.close();
  21154. }
  21155. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21156. Headers headers;
  21157. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21158. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21159. ws::WebSocketClient client(
  21160. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21161. ASSERT_TRUE(client.connect());
  21162. // The offer on the second field line counts too, so graphql-ws is selected
  21163. EXPECT_EQ("graphql-ws", client.subprotocol());
  21164. client.close();
  21165. }
  21166. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21167. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21168. ws::WebSocketClient client(
  21169. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21170. ASSERT_TRUE(client.connect());
  21171. // Server should not have selected any subprotocol
  21172. EXPECT_TRUE(client.subprotocol().empty());
  21173. client.close();
  21174. }
  21175. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21176. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21177. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21178. "/ws-subprotocol-unoffered",
  21179. headers);
  21180. ASSERT_TRUE(client.connect());
  21181. EXPECT_TRUE(client.subprotocol().empty());
  21182. client.close();
  21183. }
  21184. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21185. // Connect without requesting any subprotocol
  21186. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21187. "/ws-subprotocol");
  21188. ASSERT_TRUE(client.connect());
  21189. EXPECT_TRUE(client.subprotocol().empty());
  21190. client.close();
  21191. }
  21192. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21193. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21194. "/ws-echo");
  21195. client.set_tcp_nodelay(true);
  21196. client.set_connection_timeout(3, 0);
  21197. bool socket_options_called = false;
  21198. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21199. ASSERT_TRUE(client.connect());
  21200. ASSERT_TRUE(client.is_open());
  21201. EXPECT_TRUE(socket_options_called);
  21202. ASSERT_TRUE(client.send("hello"));
  21203. std::string msg;
  21204. auto result = client.read(msg);
  21205. EXPECT_EQ(result, ws::ReadResult::Text);
  21206. EXPECT_EQ(msg, "hello");
  21207. client.close();
  21208. }
  21209. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21210. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21211. "/ws-echo");
  21212. client.set_connection_timeout(std::chrono::seconds(3));
  21213. client.set_write_timeout(std::chrono::seconds(3));
  21214. // A sub-second remainder exercises the seconds/microseconds split.
  21215. client.set_read_timeout(std::chrono::milliseconds(1500));
  21216. ASSERT_TRUE(client.connect());
  21217. auto start = std::chrono::steady_clock::now();
  21218. std::string msg;
  21219. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21220. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21221. std::chrono::steady_clock::now() - start)
  21222. .count();
  21223. // Above 1s so that dropping the microseconds half of the split fails here.
  21224. // Ignoring the setter altogether would not reach this line at all: a client
  21225. // waits forever by default.
  21226. EXPECT_GE(elapsed, 1400);
  21227. EXPECT_LT(elapsed, 30000);
  21228. }
  21229. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21230. Server svr;
  21231. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21232. if (!req.has_header("Authorization")) {
  21233. res.status = StatusCode::Unauthorized_401;
  21234. res.set_content("Unauthorized", "text/plain");
  21235. return Server::HandlerResponse::Handled;
  21236. }
  21237. return Server::HandlerResponse::Unhandled;
  21238. });
  21239. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21240. std::string msg;
  21241. while (ws.read(msg)) {
  21242. ws.send(msg);
  21243. }
  21244. });
  21245. auto port = svr.bind_to_any_port("localhost");
  21246. std::thread t([&]() { svr.listen_after_bind(); });
  21247. svr.wait_until_ready();
  21248. // Without Authorization header - should be rejected before upgrade
  21249. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21250. EXPECT_FALSE(client1.connect());
  21251. // The rejection is framed like any other HTTP response
  21252. {
  21253. Client cli("localhost", port);
  21254. Headers headers = {{"Upgrade", "websocket"},
  21255. {"Connection", "Upgrade"},
  21256. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21257. {"Sec-WebSocket-Version", "13"}};
  21258. auto res = cli.Get("/ws", headers);
  21259. ASSERT_TRUE(res);
  21260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21261. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21262. EXPECT_EQ("Unauthorized", res->body);
  21263. }
  21264. // With Authorization header - should succeed
  21265. Headers headers = {{"Authorization", "Bearer token123"}};
  21266. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21267. headers);
  21268. ASSERT_TRUE(client2.connect());
  21269. ASSERT_TRUE(client2.send("hello"));
  21270. std::string msg;
  21271. ASSERT_TRUE(client2.read(msg));
  21272. EXPECT_EQ("hello", msg);
  21273. client2.close();
  21274. svr.stop();
  21275. t.join();
  21276. }
  21277. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21278. Server svr;
  21279. std::atomic<int> pre_request_calls{0};
  21280. std::atomic<bool> route_matched{false};
  21281. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21282. pre_request_calls++;
  21283. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21284. if (req.get_header_value("Authorization") != "Bearer token123") {
  21285. res.status = StatusCode::Unauthorized_401;
  21286. res.set_content("Unauthorized", "text/plain");
  21287. return Server::HandlerResponse::Handled;
  21288. }
  21289. return Server::HandlerResponse::Unhandled;
  21290. });
  21291. std::atomic<bool> handler_called{false};
  21292. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21293. handler_called = true;
  21294. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21295. });
  21296. auto port = svr.bind_to_any_port("localhost");
  21297. std::thread t([&]() { svr.listen_after_bind(); });
  21298. svr.wait_until_ready();
  21299. // Without Authorization header - should be rejected before upgrade
  21300. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21301. "/ws/1");
  21302. EXPECT_FALSE(client1.connect());
  21303. EXPECT_FALSE(handler_called);
  21304. EXPECT_EQ(1, pre_request_calls);
  21305. EXPECT_TRUE(route_matched);
  21306. // The rejection is an ordinary HTTP response, not a protocol switch
  21307. {
  21308. Client cli("localhost", port);
  21309. Headers headers = {{"Upgrade", "websocket"},
  21310. {"Connection", "Upgrade"},
  21311. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21312. {"Sec-WebSocket-Version", "13"}};
  21313. auto res = cli.Get("/ws/1", headers);
  21314. ASSERT_TRUE(res);
  21315. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21316. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21317. EXPECT_EQ("Unauthorized", res->body);
  21318. }
  21319. EXPECT_FALSE(handler_called);
  21320. // With Authorization header - should succeed
  21321. Headers headers = {{"Authorization", "Bearer token123"}};
  21322. ws::WebSocketClient client2(
  21323. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21324. ASSERT_TRUE(client2.connect());
  21325. std::string msg;
  21326. ASSERT_TRUE(client2.read(msg));
  21327. EXPECT_EQ("/ws/:id 2", msg);
  21328. EXPECT_TRUE(handler_called);
  21329. client2.close();
  21330. svr.stop();
  21331. t.join();
  21332. }
  21333. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21334. Server svr;
  21335. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21336. // A read timeout is how a handler gets control back. Without it, a handler
  21337. // parked in read() can never write on the connection it is reading.
  21338. ws.set_read_timeout(std::chrono::milliseconds(100));
  21339. std::string msg;
  21340. while (ws.is_open()) {
  21341. auto r = ws.read(msg);
  21342. if (r == httplib::ws::Timeout) {
  21343. ws.send("tick");
  21344. continue;
  21345. }
  21346. if (r == httplib::ws::Fail) { break; }
  21347. ws.send(msg);
  21348. }
  21349. });
  21350. auto port = svr.bind_to_any_port("localhost");
  21351. std::thread t([&]() { svr.listen_after_bind(); });
  21352. svr.wait_until_ready();
  21353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21354. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21355. ASSERT_TRUE(client.connect());
  21356. // The client sends nothing, so anything it receives came out of the
  21357. // handler's timeout path.
  21358. std::string msg;
  21359. ASSERT_EQ(client.read(msg), ws::Text);
  21360. EXPECT_EQ("tick", msg);
  21361. client.close();
  21362. svr.stop();
  21363. t.join();
  21364. }
  21365. // Stream::read may return fewer bytes than asked for. This is that contract at
  21366. // its worst -- one byte per call -- which is what a frame header straddling a
  21367. // read buffer's boundary looks like to the frame parser.
  21368. class WsByteAtATimeStream : public Stream {
  21369. public:
  21370. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21371. bool is_readable() const override { return true; }
  21372. bool wait_readable() const override { return true; }
  21373. bool wait_writable() const override { return true; }
  21374. ssize_t read(char *ptr, size_t size) override {
  21375. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21376. *ptr = data_[pos_++];
  21377. return 1;
  21378. }
  21379. ssize_t write(const char *, size_t size) override {
  21380. return static_cast<ssize_t>(size);
  21381. }
  21382. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21383. ip = "127.0.0.1";
  21384. port = 0;
  21385. }
  21386. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21387. ip = "127.0.0.1";
  21388. port = 0;
  21389. }
  21390. socket_t socket() const override { return INVALID_SOCKET; }
  21391. time_t duration() const override { return 0; }
  21392. private:
  21393. std::string data_;
  21394. size_t pos_ = 0;
  21395. };
  21396. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21397. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21398. // length and the mask key are all multi-byte fields here. Each used to be
  21399. // read with a single read() call, which fails as soon as one is split.
  21400. std::string body(200, 'x');
  21401. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21402. std::string frame;
  21403. frame += static_cast<char>(0x81); // FIN + Text
  21404. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21405. frame += static_cast<char>(body.size() >> 8);
  21406. frame += static_cast<char>(body.size() & 0xff);
  21407. for (size_t i = 0; i < 4; i++) {
  21408. frame += static_cast<char>(mask[i]);
  21409. }
  21410. for (size_t i = 0; i < body.size(); i++) {
  21411. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21412. }
  21413. WsByteAtATimeStream strm(frame);
  21414. ws::Opcode opcode;
  21415. std::string payload;
  21416. bool fin = false;
  21417. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21418. /*expect_masked=*/true, 1024),
  21419. ws::impl::FrameRead::Ok);
  21420. EXPECT_TRUE(fin);
  21421. EXPECT_EQ(opcode, ws::Opcode::Text);
  21422. EXPECT_EQ(payload, body);
  21423. }
  21424. TEST(WebSocketTest, QueryStringInHandshake) {
  21425. Server svr;
  21426. std::mutex mtx;
  21427. std::string received_target;
  21428. std::string received_token;
  21429. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21430. {
  21431. std::lock_guard<std::mutex> lock(mtx);
  21432. received_target = req.target;
  21433. if (req.has_param("token")) {
  21434. received_token = req.get_param_value("token");
  21435. }
  21436. }
  21437. std::string msg;
  21438. while (ws.read(msg)) {
  21439. ws.send(msg);
  21440. }
  21441. });
  21442. auto port = svr.bind_to_any_port("localhost");
  21443. std::thread t([&]() { svr.listen_after_bind(); });
  21444. svr.wait_until_ready();
  21445. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21446. "/ws?token=ABC&session=123");
  21447. ASSERT_TRUE(client.connect());
  21448. // Round-trip ensures the handler has run and captured the request.
  21449. ASSERT_TRUE(client.send("hello"));
  21450. std::string msg;
  21451. ASSERT_TRUE(client.read(msg));
  21452. EXPECT_EQ("hello", msg);
  21453. client.close();
  21454. {
  21455. std::lock_guard<std::mutex> lock(mtx);
  21456. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21457. EXPECT_EQ("ABC", received_token);
  21458. }
  21459. svr.stop();
  21460. t.join();
  21461. }
  21462. // Run a handshake against a throwaway server and hand the request the server
  21463. // received back to the caller, so tests can assert on the headers the client
  21464. // actually put on the wire.
  21465. static void capture_websocket_handshake_request(
  21466. const Headers &client_headers,
  21467. std::function<void(const Request &, int port)> verify) {
  21468. Server svr;
  21469. std::mutex mtx;
  21470. Request received;
  21471. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21472. {
  21473. std::lock_guard<std::mutex> lock(mtx);
  21474. received = req;
  21475. }
  21476. std::string msg;
  21477. while (ws.read(msg)) {
  21478. ws.send(msg);
  21479. }
  21480. });
  21481. auto port = svr.bind_to_any_port("localhost");
  21482. std::thread t([&]() { svr.listen_after_bind(); });
  21483. auto se = detail::scope_exit([&] {
  21484. svr.stop();
  21485. t.join();
  21486. });
  21487. svr.wait_until_ready();
  21488. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21489. client_headers);
  21490. ASSERT_TRUE(client.connect());
  21491. ASSERT_TRUE(client.send("hello"));
  21492. std::string msg;
  21493. ASSERT_TRUE(client.read(msg));
  21494. client.close();
  21495. {
  21496. std::lock_guard<std::mutex> lock(mtx);
  21497. verify(received, port);
  21498. }
  21499. }
  21500. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21501. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21502. // Non-default port must be present in the Host header. Default ports
  21503. // (80/443) are omitted; that logic is covered by
  21504. // MakeHostAndPortStringTest.
  21505. EXPECT_EQ("localhost:" + std::to_string(port),
  21506. req.get_header_value("Host"));
  21507. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21508. req.get_header_value("User-Agent"));
  21509. EXPECT_FALSE(req.has_header("Accept"));
  21510. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21511. EXPECT_FALSE(req.has_header("Content-Length"));
  21512. });
  21513. }
  21514. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21515. capture_websocket_handshake_request(
  21516. {{"Host", "example.com"},
  21517. {"User-Agent", "custom-agent"},
  21518. {"X-Custom", "value"}},
  21519. [](const Request &req, int) {
  21520. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21521. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21522. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21523. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21524. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21525. });
  21526. }
  21527. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21528. capture_websocket_handshake_request(
  21529. {{"Upgrade", "bogus"},
  21530. {"Connection", "close"},
  21531. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21532. {"Sec-WebSocket-Version", "8"}},
  21533. [](const Request &req, int) {
  21534. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21535. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21536. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21537. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21538. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21539. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21540. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21541. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21542. req.get_header_value("Sec-WebSocket-Key"));
  21543. });
  21544. }
  21545. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21546. // A header the client refuses to send must abort the handshake before any
  21547. // part of it reaches the wire; a lone request line would otherwise sit in
  21548. // the peer's buffer as a truncated request.
  21549. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21550. ASSERT_NE(INVALID_SOCKET, srv);
  21551. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21552. sockaddr_in addr{};
  21553. addr.sin_family = AF_INET;
  21554. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21555. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21556. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21557. ASSERT_EQ(0, ::listen(srv, 1));
  21558. sockaddr_in bound{};
  21559. socklen_t bound_len = sizeof(bound);
  21560. ASSERT_EQ(
  21561. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21562. auto port = ntohs(bound.sin_port);
  21563. ssize_t received = -1;
  21564. std::thread t([&] {
  21565. // Bound every blocking call so a regression fails the test with a bad
  21566. // value instead of hanging the suite.
  21567. fd_set rfds;
  21568. FD_ZERO(&rfds);
  21569. FD_SET(srv, &rfds);
  21570. timeval tv{5, 0};
  21571. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21572. 0) {
  21573. return;
  21574. }
  21575. sockaddr_in cli_addr{};
  21576. socklen_t cli_len = sizeof(cli_addr);
  21577. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21578. if (cli == INVALID_SOCKET) { return; }
  21579. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21580. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21581. char buf[4096];
  21582. received = ::recv(cli, buf, sizeof(buf), 0);
  21583. });
  21584. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21585. // connect() has already shut the socket down by the time it returns false,
  21586. // so the peer sees EOF without waiting for the client to be destroyed.
  21587. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21588. {{"X-Bad", "a\r\nInjected: 1"}});
  21589. EXPECT_FALSE(client.connect());
  21590. t.join();
  21591. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21592. EXPECT_EQ(0, received);
  21593. }
  21594. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21595. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21596. // contains "upgrade" as a substring is a different token and must not
  21597. // start a WebSocket handshake.
  21598. auto make_request = [](const std::vector<std::string> &connection_values) {
  21599. Request req;
  21600. req.method = "GET";
  21601. req.headers.emplace("Upgrade", "websocket");
  21602. for (const auto &value : connection_values) {
  21603. req.headers.emplace("Connection", value);
  21604. }
  21605. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21606. req.headers.emplace("Sec-WebSocket-Version", "13");
  21607. return req;
  21608. };
  21609. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21610. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21611. EXPECT_TRUE(
  21612. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21613. EXPECT_TRUE(
  21614. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21615. EXPECT_TRUE(
  21616. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21617. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21618. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21619. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21620. EXPECT_FALSE(
  21621. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21622. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21623. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21624. }
  21625. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21626. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21627. // asks recipients to match each protocol-name case-insensitively, and RFC
  21628. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21629. // client naming websocket alongside another protocol, or on a second field
  21630. // line, is offering websocket; a value that merely contains "websocket" as a
  21631. // substring is a different protocol name and is not.
  21632. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21633. Request req;
  21634. req.method = "GET";
  21635. for (const auto &value : upgrade_values) {
  21636. req.headers.emplace("Upgrade", value);
  21637. }
  21638. req.headers.emplace("Connection", "Upgrade");
  21639. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21640. req.headers.emplace("Sec-WebSocket-Version", "13");
  21641. return req;
  21642. };
  21643. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21644. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21645. EXPECT_TRUE(
  21646. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21647. EXPECT_TRUE(
  21648. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21649. EXPECT_TRUE(
  21650. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21651. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21652. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21653. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21654. EXPECT_FALSE(
  21655. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21656. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21657. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21658. }
  21659. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21660. Server svr;
  21661. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21662. auto port = svr.bind_to_any_port("localhost");
  21663. std::thread t([&]() { svr.listen_after_bind(); });
  21664. auto se = detail::scope_exit([&] {
  21665. svr.stop();
  21666. t.join();
  21667. });
  21668. svr.wait_until_ready();
  21669. Headers headers = {{"Upgrade", "websocket"},
  21670. {"Connection", "notupgrade"},
  21671. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21672. {"Sec-WebSocket-Version", "13"}};
  21673. Client cli("localhost", port);
  21674. auto res = cli.Get("/ws", headers);
  21675. // The route exists only as a WebSocket route, so a request that fails the
  21676. // handshake check falls through to ordinary routing.
  21677. ASSERT_TRUE(res);
  21678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21679. }
  21680. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21681. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21682. // Connection value is the only thing left for the client to reject.
  21683. Server svr;
  21684. svr.Get("/ws", [](const Request &req, Response &res) {
  21685. res.status = StatusCode::SwitchingProtocol_101;
  21686. res.set_header("Upgrade", "websocket");
  21687. res.set_header("Connection", "notupgrade");
  21688. res.set_header("Sec-WebSocket-Accept",
  21689. detail::websocket_accept_key(
  21690. req.get_header_value("Sec-WebSocket-Key")));
  21691. });
  21692. auto port = svr.bind_to_any_port("localhost");
  21693. std::thread t([&]() { svr.listen_after_bind(); });
  21694. auto se = detail::scope_exit([&] {
  21695. svr.stop();
  21696. t.join();
  21697. });
  21698. svr.wait_until_ready();
  21699. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21700. auto res = client.connect();
  21701. EXPECT_FALSE(res);
  21702. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21703. EXPECT_FALSE(client.is_open());
  21704. }
  21705. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21706. Server svr;
  21707. svr.Get("/ws", [](const Request &req, Response &res) {
  21708. res.status = StatusCode::SwitchingProtocol_101;
  21709. res.set_header("Upgrade", "websocket");
  21710. res.set_header("Connection", "Upgrade");
  21711. res.set_header("Sec-WebSocket-Accept",
  21712. detail::websocket_accept_key(
  21713. req.get_header_value("Sec-WebSocket-Key")));
  21714. res.set_header("Sec-WebSocket-Protocol", "admin");
  21715. });
  21716. auto port = svr.bind_to_any_port("localhost");
  21717. std::thread t([&]() { svr.listen_after_bind(); });
  21718. auto se = detail::scope_exit([&] {
  21719. svr.stop();
  21720. t.join();
  21721. });
  21722. svr.wait_until_ready();
  21723. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21724. // Server selects a subprotocol the client never offered
  21725. {
  21726. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21727. ws::WebSocketClient client(url, headers);
  21728. auto res = client.connect();
  21729. EXPECT_FALSE(res);
  21730. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21731. EXPECT_FALSE(client.is_open());
  21732. EXPECT_TRUE(client.subprotocol().empty());
  21733. }
  21734. // Client offered none but the server named one anyway
  21735. {
  21736. ws::WebSocketClient client(url);
  21737. auto res = client.connect();
  21738. EXPECT_FALSE(res);
  21739. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21740. EXPECT_FALSE(client.is_open());
  21741. EXPECT_TRUE(client.subprotocol().empty());
  21742. }
  21743. }
  21744. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21745. // The socket path doubles as the URL host, so it must not contain '/'.
  21746. const char *shard = getenv("GTEST_SHARD_INDEX");
  21747. const std::string sock_path =
  21748. shard ? std::string("httplib-ws-") + shard + ".sock"
  21749. : std::string("httplib-ws.sock");
  21750. std::remove(sock_path.c_str());
  21751. Server svr;
  21752. std::mutex mtx;
  21753. std::string received_host;
  21754. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21755. {
  21756. std::lock_guard<std::mutex> lock(mtx);
  21757. received_host = req.get_header_value("Host");
  21758. }
  21759. std::string msg;
  21760. while (ws.read(msg)) {
  21761. ws.send(msg);
  21762. }
  21763. });
  21764. svr.set_address_family(AF_UNIX);
  21765. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21766. auto se = detail::scope_exit([&] {
  21767. svr.stop();
  21768. t.join();
  21769. std::remove(sock_path.c_str());
  21770. });
  21771. svr.wait_until_ready();
  21772. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21773. client.set_address_family(AF_UNIX);
  21774. ASSERT_TRUE(client.connect());
  21775. ASSERT_TRUE(client.send("hello"));
  21776. std::string msg;
  21777. ASSERT_TRUE(client.read(msg));
  21778. client.close();
  21779. {
  21780. std::lock_guard<std::mutex> lock(mtx);
  21781. // There is no host:port for a Unix socket, so the same "localhost"
  21782. // placeholder the HTTP client uses is expected.
  21783. EXPECT_EQ("localhost", received_host);
  21784. }
  21785. }
  21786. // Two threads must never parse WebSocket frames from the same stream.
  21787. // close() used to read the peer's Close reply with its own frame read, so it
  21788. // raced a reader thread that was in the middle of a payload: the payload loop
  21789. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21790. // so bytes taken by close() were replaced with bytes from further along the
  21791. // stream. The message kept its length and silently changed content.
  21792. //
  21793. // The raw peer below sends a frame header plus part of the payload, waits for
  21794. // the handler to call close(), and only then sends the rest. Whichever thread
  21795. // would win the race for those bytes, the message must arrive intact, because
  21796. // close() must not touch the stream while read() owns it.
  21797. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21798. #ifndef _WIN32
  21799. signal(SIGPIPE, SIG_IGN);
  21800. #endif
  21801. const size_t payload_len = 120; // fits the 7-bit length field
  21802. const size_t prefix_len = 8;
  21803. const int attempts = 8;
  21804. std::string expected(payload_len, '\0');
  21805. for (size_t i = 0; i < payload_len; i++) {
  21806. expected[i] = static_cast<char>('a' + i % 26);
  21807. }
  21808. std::atomic<bool> peer_stalled{false};
  21809. std::atomic<bool> handler_done{false};
  21810. std::mutex received_mutex;
  21811. std::vector<std::string> received;
  21812. // Bound every wait, so a regression fails the test instead of hanging the
  21813. // suite.
  21814. auto wait_for = [](const std::atomic<bool> &flag) {
  21815. for (int i = 0; i < 500 && !flag; i++) {
  21816. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21817. }
  21818. };
  21819. Server svr;
  21820. svr.set_websocket_ping_interval(0);
  21821. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21822. std::thread reader([&]() {
  21823. std::string msg;
  21824. while (ws.read(msg)) {
  21825. std::lock_guard<std::mutex> guard(received_mutex);
  21826. received.push_back(msg);
  21827. }
  21828. });
  21829. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21830. // inside read_websocket_frame() when close() runs.
  21831. wait_for(peer_stalled);
  21832. ws.close();
  21833. reader.join();
  21834. handler_done = true;
  21835. });
  21836. auto port = svr.bind_to_any_port("127.0.0.1");
  21837. std::thread t([&]() { svr.listen_after_bind(); });
  21838. auto se = detail::scope_exit([&] {
  21839. svr.stop();
  21840. t.join();
  21841. });
  21842. svr.wait_until_ready();
  21843. auto send_bytes = [](socket_t s, const std::string &data) {
  21844. #ifdef _WIN32
  21845. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21846. #else
  21847. auto n = ::send(s, data.data(), data.size(), 0);
  21848. #endif
  21849. return n == static_cast<decltype(n)>(data.size());
  21850. };
  21851. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21852. // Every length used here fits the 7-bit length field.
  21853. auto masked_header = [](uint8_t first_byte, size_t len) {
  21854. std::string h;
  21855. h += static_cast<char>(first_byte);
  21856. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21857. h.append(4, '\0'); // mask key
  21858. return h;
  21859. };
  21860. for (int attempt = 0; attempt < attempts; attempt++) {
  21861. peer_stalled = false;
  21862. handler_done = false;
  21863. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21864. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21865. auto se_sock = detail::scope_exit([&] {
  21866. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21867. });
  21868. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21869. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21870. sockaddr_in addr{};
  21871. addr.sin_family = AF_INET;
  21872. addr.sin_port = htons(static_cast<uint16_t>(port));
  21873. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21874. ASSERT_EQ(
  21875. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21876. << "attempt " << attempt;
  21877. ASSERT_TRUE(send_bytes(sock,
  21878. "GET /ws HTTP/1.1\r\n"
  21879. "Host: 127.0.0.1\r\n"
  21880. "Upgrade: websocket\r\n"
  21881. "Connection: Upgrade\r\n"
  21882. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21883. "Sec-WebSocket-Version: 13\r\n"
  21884. "\r\n"))
  21885. << "attempt " << attempt;
  21886. std::string response;
  21887. while (response.find("\r\n\r\n") == std::string::npos) {
  21888. char buf[512];
  21889. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21890. if (n <= 0) { break; }
  21891. response.append(buf, static_cast<size_t>(n));
  21892. }
  21893. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21894. << "attempt " << attempt;
  21895. // Send the header of a Binary message but only the first prefix_len bytes
  21896. // of its payload, leaving the reader thread stalled inside the payload.
  21897. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21898. expected.substr(0, prefix_len)))
  21899. << "attempt " << attempt;
  21900. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21901. peer_stalled = true;
  21902. // Let close() send its Close frame and park in its own read before the
  21903. // rest of the payload arrives, so both threads are waiting for it.
  21904. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21905. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21906. close_frame += static_cast<char>(0x03); // status 1000
  21907. close_frame += static_cast<char>(0xE8);
  21908. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21909. << "attempt " << attempt;
  21910. // Closing the peer releases the reader thread even on the buggy path,
  21911. // where it waits for bytes another thread already consumed.
  21912. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21913. detail::close_socket(sock);
  21914. sock = INVALID_SOCKET;
  21915. wait_for(handler_done);
  21916. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21917. }
  21918. std::lock_guard<std::mutex> guard(received_mutex);
  21919. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21920. << "a message in flight when close() ran was dropped";
  21921. for (size_t i = 0; i < received.size(); i++) {
  21922. EXPECT_EQ(expected, received[i]) << "message " << i;
  21923. }
  21924. }
  21925. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21926. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21927. protected:
  21928. void SetUp() override {
  21929. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21930. SERVER_PRIVATE_KEY_FILE);
  21931. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21932. std::string msg;
  21933. ws::ReadResult ret;
  21934. while ((ret = ws.read(msg))) {
  21935. if (ret == ws::Binary) {
  21936. ws.send(msg.data(), msg.size());
  21937. } else {
  21938. ws.send(msg);
  21939. }
  21940. }
  21941. });
  21942. port_ = server_->bind_to_any_port(HOST);
  21943. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21944. server_->wait_until_ready();
  21945. }
  21946. void TearDown() override {
  21947. server_->stop();
  21948. if (server_thread_.joinable()) { server_thread_.join(); }
  21949. }
  21950. std::unique_ptr<SSLServer> server_;
  21951. std::thread server_thread_;
  21952. int port_ = 0;
  21953. };
  21954. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21955. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21956. "/ws-echo");
  21957. client.enable_server_certificate_verification(false);
  21958. ASSERT_TRUE(client.connect());
  21959. ASSERT_TRUE(client.is_open());
  21960. ASSERT_TRUE(client.send("Hello WSS"));
  21961. std::string msg;
  21962. EXPECT_EQ(ws::Text, client.read(msg));
  21963. EXPECT_EQ("Hello WSS", msg);
  21964. client.close();
  21965. }
  21966. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21967. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21968. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21969. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21970. // client (without calling close() first) is the only path that runs
  21971. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21972. // bug exactly.
  21973. //
  21974. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21975. // when linked against an instrumented libssl; run under Valgrind to catch it
  21976. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21977. // suite (the freed session otherwise stalls on the close handshake) — this test
  21978. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21979. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21980. {
  21981. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21982. "/ws-echo");
  21983. client.enable_server_certificate_verification(false);
  21984. client.set_read_timeout(2, 0);
  21985. client.set_write_timeout(2, 0);
  21986. ASSERT_TRUE(client.connect());
  21987. ASSERT_TRUE(client.is_open());
  21988. ASSERT_TRUE(client.send("still open"));
  21989. // Intentionally do NOT call client.close(): leaving scope runs
  21990. // shutdown_and_close() with the WebSocket still open, which must send the
  21991. // close frame while the TLS session is still alive.
  21992. }
  21993. }
  21994. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21995. // shutdown_and_close() at the start of connect(), reproducing the same
  21996. // use-after-free within the test body rather than at scope exit. The second
  21997. // connect must succeed and echo, proving the close handshake ran over a live
  21998. // session. See the note above about memory-tool requirements.
  21999. TEST_F(WebSocketSSLIntegrationTest,
  22000. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22001. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22002. "/ws-echo");
  22003. client.enable_server_certificate_verification(false);
  22004. client.set_read_timeout(2, 0);
  22005. client.set_write_timeout(2, 0);
  22006. ASSERT_TRUE(client.connect());
  22007. ASSERT_TRUE(client.is_open());
  22008. ASSERT_TRUE(client.send("still open"));
  22009. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22010. // the still-open connection, which must not touch a freed TLS session.
  22011. ASSERT_TRUE(client.connect());
  22012. ASSERT_TRUE(client.is_open());
  22013. ASSERT_TRUE(client.send("after reconnect"));
  22014. std::string msg;
  22015. EXPECT_EQ(ws::Text, client.read(msg));
  22016. EXPECT_EQ("after reconnect", msg);
  22017. client.close();
  22018. }
  22019. #endif
  22020. #ifdef CPPHTTPLIB_SSL_ENABLED
  22021. class WebSocketSSLCATest : public ::testing::Test {
  22022. protected:
  22023. void SetUp() override {
  22024. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22025. SERVER_PRIVATE_KEY_FILE);
  22026. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22027. std::string msg;
  22028. while (ws.read(msg)) {
  22029. ws.send(msg);
  22030. }
  22031. });
  22032. port_ = server_->bind_to_any_port("127.0.0.1");
  22033. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22034. server_->wait_until_ready();
  22035. }
  22036. void TearDown() override {
  22037. server_->stop();
  22038. if (server_thread_.joinable()) { server_thread_.join(); }
  22039. }
  22040. std::string url() const {
  22041. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22042. }
  22043. std::unique_ptr<SSLServer> server_;
  22044. std::thread server_thread_;
  22045. int port_ = 0;
  22046. };
  22047. // A custom CA loaded as PEM verifies the server with full certificate
  22048. // verification enabled
  22049. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22050. ws::WebSocketClient client(url());
  22051. std::string cert;
  22052. read_file(SERVER_CERT2_FILE, cert);
  22053. client.load_ca_cert_store(cert.c_str(), cert.size());
  22054. ASSERT_TRUE(client.connect());
  22055. ASSERT_TRUE(client.send("hello"));
  22056. std::string msg;
  22057. EXPECT_EQ(ws::Text, client.read(msg));
  22058. EXPECT_EQ("hello", msg);
  22059. client.close();
  22060. }
  22061. // A custom CA that does not cover the server must fail verification (the
  22062. // custom CA is exclusive; system certs are not loaded alongside it)
  22063. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22064. ws::WebSocketClient client(url());
  22065. std::string cert;
  22066. read_file(CLIENT_CA_CERT_FILE, cert);
  22067. client.load_ca_cert_store(cert.c_str(), cert.size());
  22068. auto res = client.connect();
  22069. ASSERT_FALSE(res);
  22070. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22071. EXPECT_EQ(-1, res.status());
  22072. EXPECT_NE(0u, res.ssl_backend_error());
  22073. }
  22074. // The same CA as a file path rather than PEM in memory
  22075. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22076. ws::WebSocketClient client(url());
  22077. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22078. ASSERT_TRUE(client.connect());
  22079. ASSERT_TRUE(client.send("hello"));
  22080. std::string msg;
  22081. EXPECT_EQ(ws::Text, client.read(msg));
  22082. EXPECT_EQ("hello", msg);
  22083. client.close();
  22084. }
  22085. // ...and a CA file that does not cover the server still fails, so it is the
  22086. // path above that decides the outcome
  22087. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22088. ws::WebSocketClient client(url());
  22089. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22090. ASSERT_FALSE(client.connect());
  22091. }
  22092. // Regression test: reconnecting with a native custom CA store used to reuse
  22093. // a store handle the previous TLS context had already freed (use-after-free
  22094. // under the OpenSSL backend). The context now lives as long as the client.
  22095. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22096. ws::WebSocketClient client(url());
  22097. std::string cert;
  22098. read_file(SERVER_CERT2_FILE, cert);
  22099. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22100. ASSERT_TRUE(client.connect());
  22101. client.close();
  22102. ASSERT_TRUE(client.connect());
  22103. ASSERT_TRUE(client.send("again"));
  22104. std::string msg;
  22105. EXPECT_EQ(ws::Text, client.read(msg));
  22106. EXPECT_EQ("again", msg);
  22107. client.close();
  22108. }
  22109. // Regression test: a certificate with a trusted chain but no identity match
  22110. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22111. // verification entirely for IP hosts, so this connection succeeded there.
  22112. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22113. // chain verification while the identity check must still fail.
  22114. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22115. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22116. ASSERT_TRUE(svr.is_valid());
  22117. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22118. std::string msg;
  22119. while (ws.read(msg)) {
  22120. ws.send(msg);
  22121. }
  22122. });
  22123. auto port = svr.bind_to_any_port("127.0.0.1");
  22124. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22125. auto se = detail::scope_exit([&] {
  22126. svr.stop();
  22127. t.join();
  22128. });
  22129. svr.wait_until_ready();
  22130. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22131. "/echo");
  22132. std::string cert;
  22133. read_file(SERVER_CERT_FILE, cert);
  22134. client.load_ca_cert_store(cert.c_str(), cert.size());
  22135. ASSERT_FALSE(client.connect());
  22136. }
  22137. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22138. // SNI, so nothing binds the host name to the TLS session. These bind the
  22139. // server to "localhost" instead, the only shape that exercises the SNI and
  22140. // hostname-verification path with certificate verification left enabled.
  22141. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22142. protected:
  22143. void Start(const char *cert_file) {
  22144. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22145. SERVER_PRIVATE_KEY_FILE);
  22146. ASSERT_TRUE(server_->is_valid());
  22147. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22148. std::string msg;
  22149. while (ws.read(msg)) {
  22150. ws.send(msg);
  22151. }
  22152. });
  22153. port_ = server_->bind_to_any_port("localhost");
  22154. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22155. server_->wait_until_ready();
  22156. }
  22157. void TearDown() override {
  22158. if (server_) { server_->stop(); }
  22159. if (server_thread_.joinable()) { server_thread_.join(); }
  22160. }
  22161. std::string url() const {
  22162. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22163. }
  22164. std::unique_ptr<SSLServer> server_;
  22165. std::thread server_thread_;
  22166. int port_ = 0;
  22167. };
  22168. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22169. // out and the connection is usable
  22170. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22171. Start(SERVER_CERT2_FILE);
  22172. ws::WebSocketClient client(url());
  22173. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22174. ASSERT_TRUE(client.connect());
  22175. ASSERT_TRUE(client.send("hello"));
  22176. std::string msg;
  22177. EXPECT_EQ(ws::Text, client.read(msg));
  22178. EXPECT_EQ("hello", msg);
  22179. client.close();
  22180. }
  22181. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22182. // while the identity check must still reject "localhost"
  22183. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22184. Start(SERVER_CERT_FILE);
  22185. ws::WebSocketClient client(url());
  22186. client.set_ca_cert_path(SERVER_CERT_FILE);
  22187. auto res = client.connect();
  22188. ASSERT_FALSE(res);
  22189. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22190. EXPECT_EQ(-1, res.status());
  22191. }
  22192. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22193. // disabled: the chain is still checked, only the identity check is skipped
  22194. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22195. Start(SERVER_CERT_FILE);
  22196. ws::WebSocketClient client(url());
  22197. client.set_ca_cert_path(SERVER_CERT_FILE);
  22198. client.enable_server_hostname_verification(false);
  22199. ASSERT_TRUE(client.connect());
  22200. ASSERT_TRUE(client.send("hello"));
  22201. std::string msg;
  22202. EXPECT_EQ(ws::Text, client.read(msg));
  22203. EXPECT_EQ("hello", msg);
  22204. client.close();
  22205. }
  22206. // A CA that did not sign the server certificate fails the chain, even though
  22207. // the name would match
  22208. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22209. Start(SERVER_CERT2_FILE);
  22210. ws::WebSocketClient client(url());
  22211. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22212. ASSERT_FALSE(client.connect());
  22213. }
  22214. // With verification disabled, neither the chain nor the name is checked
  22215. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22216. Start(SERVER_CERT_FILE);
  22217. ws::WebSocketClient client(url());
  22218. client.enable_server_certificate_verification(false);
  22219. ASSERT_TRUE(client.connect());
  22220. ASSERT_TRUE(client.send("hello"));
  22221. std::string msg;
  22222. EXPECT_EQ(ws::Text, client.read(msg));
  22223. EXPECT_EQ("hello", msg);
  22224. client.close();
  22225. }
  22226. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22227. protected:
  22228. void SetUp() override {
  22229. server_ = httplib::detail::make_unique<SSLServer>(
  22230. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22231. ASSERT_TRUE(server_->is_valid());
  22232. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22233. std::string msg;
  22234. while (ws.read(msg)) {
  22235. ws.send(msg);
  22236. }
  22237. });
  22238. port_ = server_->bind_to_any_port("localhost");
  22239. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22240. server_->wait_until_ready();
  22241. }
  22242. void TearDown() override {
  22243. server_->stop();
  22244. if (server_thread_.joinable()) { server_thread_.join(); }
  22245. }
  22246. std::string url() const {
  22247. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22248. }
  22249. void ConnectWithClientCert(const std::string &client_cert_file,
  22250. const std::string &client_private_key_file,
  22251. const char *private_key_password) {
  22252. std::string cert_pem, key_pem;
  22253. read_file(client_cert_file, cert_pem);
  22254. read_file(client_private_key_file, key_pem);
  22255. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22256. key_pem.c_str(), key_pem.size(),
  22257. private_key_password};
  22258. ws::WebSocketClient client(url(), pem);
  22259. ASSERT_TRUE(client.is_valid());
  22260. client.enable_server_certificate_verification(false);
  22261. ASSERT_TRUE(client.connect());
  22262. ASSERT_TRUE(client.send("hello"));
  22263. std::string msg;
  22264. EXPECT_EQ(ws::Text, client.read(msg));
  22265. EXPECT_EQ("hello", msg);
  22266. client.close();
  22267. }
  22268. std::unique_ptr<SSLServer> server_;
  22269. std::thread server_thread_;
  22270. int port_ = 0;
  22271. };
  22272. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22273. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22274. }
  22275. // Control for the tests above: the fixture's server really does require a
  22276. // client certificate, so it is the PEM the constructor installed that decides
  22277. // the outcome.
  22278. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22279. ws::WebSocketClient client(url());
  22280. ASSERT_TRUE(client.is_valid());
  22281. client.enable_server_certificate_verification(false);
  22282. EXPECT_FALSE(client.connect());
  22283. }
  22284. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22285. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22286. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22287. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22288. }
  22289. #endif
  22290. #if !defined(_WIN32)
  22291. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22292. auto secret_dir = std::string("./symlink_test_secret");
  22293. auto served_dir = std::string("./symlink_test_served");
  22294. auto secret_file = secret_dir + "/secret.txt";
  22295. auto symlink_path = served_dir + "/escape";
  22296. // Setup: create directories and files
  22297. mkdir(secret_dir.c_str(), 0755);
  22298. mkdir(served_dir.c_str(), 0755);
  22299. {
  22300. std::ofstream ofs(secret_file);
  22301. ofs << "SECRET_DATA";
  22302. }
  22303. // Create symlink using absolute path so it resolves correctly
  22304. #ifdef PATH_MAX
  22305. char abs_secret[PATH_MAX];
  22306. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22307. #else
  22308. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22309. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22310. ASSERT_NE(nullptr, abs_secret);
  22311. #endif
  22312. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22313. auto se = detail::scope_exit([&] {
  22314. unlink(symlink_path.c_str());
  22315. unlink(secret_file.c_str());
  22316. rmdir(served_dir.c_str());
  22317. rmdir(secret_dir.c_str());
  22318. });
  22319. Server svr;
  22320. svr.set_mount_point("/", served_dir);
  22321. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22322. auto se2 = detail::scope_exit([&] {
  22323. svr.stop();
  22324. listen_thread.join();
  22325. });
  22326. svr.wait_until_ready();
  22327. Client cli("localhost", PORT);
  22328. // Symlink pointing outside base dir should be blocked
  22329. auto res = cli.Get("/escape/secret.txt");
  22330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22331. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22332. }
  22333. #endif
  22334. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22335. // "GET /smuggled" request), reads the first response, and only then sends the
  22336. // embedded request as the body. Returns how many times /smuggled ran.
  22337. //
  22338. // The body is sent AFTER receiving the first response (as in the original
  22339. // PoC) so that the stream_line_reader cannot buffer it together with the
  22340. // headers of the first request.
  22341. static int count_smuggled_requests(const std::string &outer_head,
  22342. std::string &first_response) {
  22343. Server svr;
  22344. svr.set_mount_point("/", "./www");
  22345. std::atomic<int> smuggled_count(0);
  22346. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22347. smuggled_count++;
  22348. res.set_content("oops", "text/plain");
  22349. });
  22350. svr.Post("/post", [&](const Request &req, Response &res) {
  22351. res.set_content(req.body, "text/plain");
  22352. });
  22353. auto port = svr.bind_to_any_port("localhost");
  22354. thread t = thread([&] { svr.listen_after_bind(); });
  22355. auto se = detail::scope_exit([&] {
  22356. svr.stop();
  22357. t.join();
  22358. });
  22359. svr.wait_until_ready();
  22360. auto error = Error::Success;
  22361. auto sock = detail::create_client_socket(
  22362. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22363. /*connection_timeout_sec=*/2, 0,
  22364. /*read_timeout_sec=*/2, 0,
  22365. /*write_timeout_sec=*/2, 0, std::string(), error);
  22366. EXPECT_NE(INVALID_SOCKET, sock);
  22367. if (sock == INVALID_SOCKET) { return -1; }
  22368. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22369. // The "smuggled" request will be sent as the body of the outer request
  22370. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22371. "Host: localhost\r\n"
  22372. "Connection: close\r\n"
  22373. "\r\n";
  22374. auto head = outer_head;
  22375. auto len = std::to_string(smuggled.size());
  22376. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22377. pos = head.find("{len}", pos + len.size())) {
  22378. head.replace(pos, 5, len);
  22379. }
  22380. // Step 1: Send only the outer request headers (no body yet)
  22381. auto sent = send(sock, head.data(), head.size(), 0);
  22382. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22383. // Step 2: Read the first response
  22384. char buf[4096];
  22385. for (;;) {
  22386. auto n = recv(sock, buf, sizeof(buf), 0);
  22387. if (n <= 0) break;
  22388. first_response.append(buf, static_cast<size_t>(n));
  22389. // Stop once we have a complete response (headers + body)
  22390. auto hdr_end = first_response.find("\r\n\r\n");
  22391. if (hdr_end != std::string::npos) {
  22392. // Check for Content-Length to know when the body is complete
  22393. auto cl_pos = first_response.find("Content-Length:");
  22394. if (cl_pos != std::string::npos) {
  22395. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22396. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22397. auto cl = std::stoul(
  22398. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22399. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22400. } else {
  22401. break; // No Content-Length, assume headers-only response
  22402. }
  22403. }
  22404. }
  22405. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22406. // vulnerable server the keep-alive loop reads this as a second request. The
  22407. // server may already have closed the connection, so the result is ignored.
  22408. send(sock, smuggled.data(), smuggled.size(), 0);
  22409. // Half-close so that a server which drained the body sees EOF and closes,
  22410. // instead of the read below waiting for the read timeout.
  22411. #ifdef _WIN32
  22412. ::shutdown(sock, SD_SEND);
  22413. #else
  22414. ::shutdown(sock, SHUT_WR);
  22415. #endif
  22416. // Step 4: Read until the server closes the connection
  22417. for (;;) {
  22418. auto n = recv(sock, buf, sizeof(buf), 0);
  22419. if (n <= 0) break;
  22420. }
  22421. return smuggled_count.load();
  22422. }
  22423. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22424. // A GET request with Content-Length to a static file handler must have its
  22425. // body drained before the keep-alive connection is reused. Otherwise the
  22426. // unread body bytes are interpreted as the next HTTP request.
  22427. std::string first_response;
  22428. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22429. "Host: localhost\r\n"
  22430. "Content-Length: {len}\r\n"
  22431. "\r\n",
  22432. first_response));
  22433. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22434. }
  22435. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22436. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22437. // be answered with 400 and the connection closed. Treating it as "no body"
  22438. // leaves the body to be parsed as the next request.
  22439. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22440. const char *targets[] = {
  22441. "GET /file", // handler that never reads the body
  22442. "GET /not-found", // no handler matches (404)
  22443. "POST /post", // handler that reads the body
  22444. };
  22445. for (auto target : targets) {
  22446. for (auto value : values) {
  22447. std::string first_response;
  22448. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22449. " HTTP/1.1\r\n"
  22450. "Host: localhost\r\n"
  22451. "Content-Length: " +
  22452. value + "\r\n\r\n",
  22453. first_response))
  22454. << target << " with Content-Length: " << value;
  22455. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22456. << target << " with Content-Length: " << value;
  22457. }
  22458. }
  22459. }
  22460. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22461. // A 400 for an unparseable request line leaves the rest of the message
  22462. // unread, so the connection must be closed rather than reused.
  22463. std::string first_response;
  22464. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22465. "Host: localhost\r\n"
  22466. "Content-Length: {len}\r\n"
  22467. "\r\n",
  22468. first_response));
  22469. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22470. }
  22471. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22472. // Same as above for a header block that fails to parse.
  22473. std::string first_response;
  22474. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22475. "Host: localhost\r\n"
  22476. "Bad Header\r\n"
  22477. "Content-Length: {len}\r\n"
  22478. "\r\n",
  22479. first_response));
  22480. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22481. }
  22482. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22483. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22484. // server must not read another request on that connection, even when the
  22485. // request had no body to drain.
  22486. std::string first_response;
  22487. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22488. "Host: localhost\r\n"
  22489. "\r\n",
  22490. first_response));
  22491. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22492. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22493. }
  22494. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22495. // A content reader that stops early leaves the stream inside the body.
  22496. // Draining the whole Content-Length from there, or reading the body again,
  22497. // reads into the next request, and whatever follows is parsed as a request
  22498. // of its own.
  22499. Server svr;
  22500. std::atomic<int> smuggled_count(0);
  22501. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22502. svr.Post("/upload", [](const Request &req, Response &res,
  22503. const ContentReader &content_reader) {
  22504. // Stop at the last chunk, so the whole body has been read however it
  22505. // arrives.
  22506. auto length = req.get_header_value_u64("Content-Length");
  22507. size_t total = 0;
  22508. auto consumed = content_reader([&](const char *, size_t n) {
  22509. total += n;
  22510. return total < length;
  22511. });
  22512. EXPECT_FALSE(consumed);
  22513. if (req.has_param("retry")) {
  22514. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22515. }
  22516. // Replace the 400 the aborted read set, which would close the connection.
  22517. res.set_redirect("/done");
  22518. });
  22519. auto port = svr.bind_to_any_port(HOST);
  22520. thread t = thread([&] { svr.listen_after_bind(); });
  22521. auto se = detail::scope_exit([&] {
  22522. svr.stop();
  22523. t.join();
  22524. });
  22525. svr.wait_until_ready();
  22526. // A front end sees the second request as a POST whose body is the GET. The
  22527. // first body is as long as the POST's headers, so draining it again reads
  22528. // exactly those and leaves the GET to be parsed next.
  22529. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22530. "Host: localhost\r\n"
  22531. "\r\n";
  22532. std::string second_head = "POST /post HTTP/1.1\r\n"
  22533. "Host: localhost\r\n"
  22534. "Content-Length: " +
  22535. std::to_string(inner.size()) +
  22536. "\r\n"
  22537. "\r\n";
  22538. for (auto target : {"/upload", "/upload?retry"}) {
  22539. smuggled_count = 0;
  22540. std::string request = "POST " + std::string(target) +
  22541. " HTTP/1.1\r\n"
  22542. "Host: localhost\r\n"
  22543. "Content-Length: " +
  22544. std::to_string(second_head.size()) +
  22545. "\r\n"
  22546. "\r\n" +
  22547. std::string(second_head.size(), 'A') + second_head +
  22548. inner;
  22549. std::string response;
  22550. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22551. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22552. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22553. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22554. EXPECT_EQ(0, smuggled_count.load()) << target;
  22555. }
  22556. }
  22557. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22558. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22559. // must be rejected with 400 Bad Request.
  22560. Server svr;
  22561. svr.Post("/test", [&](const Request &, Response &res) {
  22562. res.set_content("ok", "text/plain");
  22563. });
  22564. thread t = thread([&] { svr.listen(HOST, PORT); });
  22565. auto se = detail::scope_exit([&] {
  22566. svr.stop();
  22567. t.join();
  22568. ASSERT_FALSE(svr.is_running());
  22569. });
  22570. svr.wait_until_ready();
  22571. // Exact "chunked"
  22572. {
  22573. auto req = "POST /test HTTP/1.1\r\n"
  22574. "Host: localhost\r\n"
  22575. "Content-Length: 5\r\n"
  22576. "Transfer-Encoding: chunked\r\n"
  22577. "Connection: close\r\n"
  22578. "\r\n"
  22579. "hello";
  22580. std::string response;
  22581. ASSERT_TRUE(send_request(1, req, &response));
  22582. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22583. response.substr(0, response.find("\r\n")));
  22584. }
  22585. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22586. {
  22587. auto req = "POST /test HTTP/1.1\r\n"
  22588. "Host: localhost\r\n"
  22589. "Content-Length: 5\r\n"
  22590. "Transfer-Encoding: gzip, chunked\r\n"
  22591. "Connection: close\r\n"
  22592. "\r\n"
  22593. "hello";
  22594. std::string response;
  22595. ASSERT_TRUE(send_request(1, req, &response));
  22596. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22597. response.substr(0, response.find("\r\n")));
  22598. }
  22599. }
  22600. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22601. Server svr;
  22602. svr.Post("/test", [&](const Request &, Response &res) {
  22603. res.set_content("ok", "text/plain");
  22604. });
  22605. thread t = thread([&] { svr.listen(HOST, PORT); });
  22606. auto se = detail::scope_exit([&] {
  22607. svr.stop();
  22608. t.join();
  22609. ASSERT_FALSE(svr.is_running());
  22610. });
  22611. svr.wait_until_ready();
  22612. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22613. // length cannot be determined, so the server must answer 400 and close
  22614. // rather than treat the request as bodyless and leave the body in the
  22615. // socket for the next request to pick up.
  22616. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22617. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22618. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22619. std::string response;
  22620. ASSERT_TRUE(send_request(1, req, &response));
  22621. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22622. response.substr(0, response.find("\r\n")))
  22623. << transfer_encoding;
  22624. }
  22625. // RFC 9110 5.3: the codings may also be split across several
  22626. // Transfer-Encoding lines, which combine in the order they were received.
  22627. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22628. // just like the single-line "chunked, gzip" above.
  22629. {
  22630. auto req = "POST /test HTTP/1.1\r\n"
  22631. "Host: localhost\r\n"
  22632. "Transfer-Encoding: chunked\r\n"
  22633. "Transfer-Encoding: gzip\r\n"
  22634. "\r\n"
  22635. "0\r\n\r\n";
  22636. std::string response;
  22637. ASSERT_TRUE(send_request(1, req, &response));
  22638. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22639. response.substr(0, response.find("\r\n")));
  22640. }
  22641. // A sequence ending in chunked stays valid.
  22642. auto req = "POST /test HTTP/1.1\r\n"
  22643. "Host: localhost\r\n"
  22644. "Transfer-Encoding: gzip, chunked\r\n"
  22645. "Connection: close\r\n"
  22646. "\r\n"
  22647. "0\r\n\r\n";
  22648. std::string response;
  22649. ASSERT_TRUE(send_request(1, req, &response));
  22650. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22651. // ...including when it is spread over several lines.
  22652. auto split_req = "POST /test HTTP/1.1\r\n"
  22653. "Host: localhost\r\n"
  22654. "Transfer-Encoding: gzip\r\n"
  22655. "Transfer-Encoding: chunked\r\n"
  22656. "Connection: close\r\n"
  22657. "\r\n"
  22658. "0\r\n\r\n";
  22659. std::string split_response;
  22660. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22661. EXPECT_EQ("HTTP/1.1 200 OK",
  22662. split_response.substr(0, split_response.find("\r\n")));
  22663. }
  22664. // Regression for issue #2450: a DELETE without Content-Length on a
  22665. // keep-alive connection must not let the post-response drain consume the
  22666. // next request's bytes.
  22667. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22668. Server svr;
  22669. std::atomic<int> delete_count(0);
  22670. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22671. delete_count++;
  22672. res.status = StatusCode::NoContent_204;
  22673. });
  22674. auto port = svr.bind_to_any_port(HOST);
  22675. thread t = thread([&] { svr.listen_after_bind(); });
  22676. auto se = detail::scope_exit([&] {
  22677. svr.stop();
  22678. t.join();
  22679. });
  22680. svr.wait_until_ready();
  22681. auto error = Error::Success;
  22682. auto sock = detail::create_client_socket(
  22683. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22684. /*connection_timeout_sec=*/2, 0,
  22685. /*read_timeout_sec=*/2, 0,
  22686. /*write_timeout_sec=*/2, 0, std::string(), error);
  22687. ASSERT_NE(INVALID_SOCKET, sock);
  22688. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22689. auto send_request_and_read_response = [&](const std::string &req,
  22690. std::string &out) -> bool {
  22691. auto sent = send(sock, req.data(), req.size(), 0);
  22692. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22693. char buf[4096];
  22694. for (;;) {
  22695. auto n = recv(sock, buf, sizeof(buf), 0);
  22696. if (n <= 0) { return !out.empty(); }
  22697. out.append(buf, static_cast<size_t>(n));
  22698. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22699. }
  22700. };
  22701. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22702. "Host: localhost\r\n"
  22703. "\r\n";
  22704. std::string resp1;
  22705. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22706. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22707. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22708. "Host: localhost\r\n"
  22709. "Connection: close\r\n"
  22710. "\r\n";
  22711. std::string resp2;
  22712. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22713. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22714. EXPECT_EQ(2, delete_count.load());
  22715. }
  22716. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22717. Server svr;
  22718. svr.Post("/ingest", [&](const Request &, Response &res,
  22719. const ContentReader &content_reader) {
  22720. auto consumed = content_reader([](const char *, size_t) { return false; });
  22721. EXPECT_FALSE(consumed);
  22722. res.status = StatusCode::Conflict_409;
  22723. res.set_header("Connection", "close");
  22724. });
  22725. auto port = svr.bind_to_any_port(HOST);
  22726. thread t = thread([&] { svr.listen_after_bind(); });
  22727. auto se = detail::scope_exit([&] {
  22728. svr.stop();
  22729. t.join();
  22730. });
  22731. svr.wait_until_ready();
  22732. auto error = Error::Success;
  22733. auto sock = detail::create_client_socket(
  22734. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22735. /*connection_timeout_sec=*/2, 0,
  22736. /*read_timeout_sec=*/1, 0,
  22737. /*write_timeout_sec=*/2, 0, std::string(), error);
  22738. ASSERT_NE(INVALID_SOCKET, sock);
  22739. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22740. std::string request = "POST /ingest HTTP/1.1\r\n"
  22741. "Host: localhost\r\n"
  22742. "Transfer-Encoding: chunked\r\n"
  22743. "\r\n"
  22744. "4\r\n"
  22745. "data\r\n";
  22746. auto sent = send(sock, request.data(), request.size(), 0);
  22747. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22748. std::string response;
  22749. ssize_t received = 0;
  22750. do {
  22751. char buf[4096];
  22752. received = recv(sock, buf, sizeof(buf), 0);
  22753. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22754. } while (received > 0);
  22755. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22756. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22757. EXPECT_EQ(0, received);
  22758. }
  22759. namespace no_proxy_test {
  22760. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22761. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22762. // calling listen().
  22763. class ScopedServer {
  22764. public:
  22765. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22766. ~ScopedServer() {
  22767. svr_.stop();
  22768. if (th_.joinable()) { th_.join(); }
  22769. }
  22770. Server &svr() { return svr_; }
  22771. int port() const { return port_; }
  22772. void listen() {
  22773. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22774. svr_.wait_until_ready();
  22775. }
  22776. private:
  22777. Server svr_;
  22778. std::thread th_;
  22779. int port_ = 0;
  22780. };
  22781. class ProxyAndTargetServers {
  22782. public:
  22783. ProxyAndTargetServers() {
  22784. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22785. proxy_hits_++;
  22786. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22787. res.set_content("via-proxy", "text/plain");
  22788. });
  22789. target_.Get(".*", [this](const Request &req, Response &res) {
  22790. target_hits_++;
  22791. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22792. res.set_content("direct", "text/plain");
  22793. });
  22794. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22795. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22796. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22797. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22798. proxy_mock_.wait_until_ready();
  22799. target_.wait_until_ready();
  22800. }
  22801. ~ProxyAndTargetServers() {
  22802. proxy_mock_.stop();
  22803. target_.stop();
  22804. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22805. if (target_thread_.joinable()) { target_thread_.join(); }
  22806. }
  22807. Server &proxy_mock() { return proxy_mock_; }
  22808. Server &target() { return target_; }
  22809. int proxy_port() const { return proxy_port_; }
  22810. int target_port() const { return target_port_; }
  22811. int proxy_hits() const { return proxy_hits_.load(); }
  22812. int target_hits() const { return target_hits_.load(); }
  22813. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22814. void reset_counters() {
  22815. proxy_hits_ = 0;
  22816. target_hits_ = 0;
  22817. last_had_proxy_authz_ = false;
  22818. }
  22819. private:
  22820. Server proxy_mock_;
  22821. Server target_;
  22822. std::thread proxy_thread_;
  22823. std::thread target_thread_;
  22824. int proxy_port_ = 0;
  22825. int target_port_ = 0;
  22826. std::atomic<int> proxy_hits_{0};
  22827. std::atomic<int> target_hits_{0};
  22828. std::atomic<bool> last_had_proxy_authz_{false};
  22829. };
  22830. inline std::unique_ptr<Client> make_client(const std::string &host,
  22831. ProxyAndTargetServers &s) {
  22832. auto cli = detail::make_unique<Client>(host, s.target_port());
  22833. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22834. cli->set_proxy("127.0.0.1", s.proxy_port());
  22835. return cli;
  22836. }
  22837. } // namespace no_proxy_test
  22838. using no_proxy_test::make_client;
  22839. using no_proxy_test::ProxyAndTargetServers;
  22840. TEST(NoProxyTest, ExactHostnameBypasses) {
  22841. ProxyAndTargetServers s;
  22842. auto cli = make_client("example.com", s);
  22843. cli->set_no_proxy({"example.com"});
  22844. auto res = cli->Get("/");
  22845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22846. EXPECT_EQ(0, s.proxy_hits());
  22847. EXPECT_EQ(1, s.target_hits());
  22848. }
  22849. TEST(NoProxyTest, SubdomainBypasses) {
  22850. ProxyAndTargetServers s;
  22851. auto cli = make_client("foo.example.com", s);
  22852. cli->set_no_proxy({"example.com"});
  22853. auto res = cli->Get("/");
  22854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22855. EXPECT_EQ(0, s.proxy_hits());
  22856. EXPECT_EQ(1, s.target_hits());
  22857. }
  22858. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22859. // Regression guard: "evilexample.com" must not be considered a subdomain
  22860. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22861. // check would let traffic bypass the proxy and leak credentials direct
  22862. // to the attacker host.
  22863. ProxyAndTargetServers s;
  22864. auto cli = make_client("evilexample.com", s);
  22865. cli->set_no_proxy({"example.com"});
  22866. auto res = cli->Get("/");
  22867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22868. EXPECT_GE(s.proxy_hits(), 1);
  22869. EXPECT_EQ(0, s.target_hits());
  22870. }
  22871. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22872. ProxyAndTargetServers s;
  22873. auto cli = make_client("example.com.evil.com", s);
  22874. cli->set_no_proxy({"example.com"});
  22875. auto res = cli->Get("/");
  22876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22877. EXPECT_GE(s.proxy_hits(), 1);
  22878. EXPECT_EQ(0, s.target_hits());
  22879. }
  22880. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22881. ProxyAndTargetServers s;
  22882. auto cli = make_client("example.com", s);
  22883. cli->set_no_proxy({".example.com"});
  22884. auto res = cli->Get("/");
  22885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22886. EXPECT_EQ(0, s.proxy_hits());
  22887. EXPECT_EQ(1, s.target_hits());
  22888. }
  22889. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22890. ProxyAndTargetServers s;
  22891. auto cli = make_client("Example.COM", s);
  22892. cli->set_no_proxy({"EXAMPLE.com"});
  22893. auto res = cli->Get("/");
  22894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22895. EXPECT_EQ(0, s.proxy_hits());
  22896. EXPECT_EQ(1, s.target_hits());
  22897. }
  22898. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22899. ProxyAndTargetServers s;
  22900. auto cli = make_client("example.com.", s);
  22901. cli->set_no_proxy({"example.com"});
  22902. auto res = cli->Get("/");
  22903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22904. EXPECT_EQ(0, s.proxy_hits());
  22905. EXPECT_EQ(1, s.target_hits());
  22906. }
  22907. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22908. // Trailing dots must be normalized on BOTH sides — host and entry.
  22909. // An implementation that only strips the host-side trailing dot would
  22910. // fail to match host "example.com" against entry "example.com." because
  22911. // a literal substring search would compare 11 chars against 12.
  22912. ProxyAndTargetServers s;
  22913. auto cli = make_client("example.com", s);
  22914. cli->set_no_proxy({"example.com."});
  22915. auto res = cli->Get("/");
  22916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22917. EXPECT_EQ(0, s.proxy_hits());
  22918. EXPECT_EQ(1, s.target_hits());
  22919. }
  22920. TEST(NoProxyTest, WildcardBypassesEverything) {
  22921. ProxyAndTargetServers s;
  22922. auto cli = make_client("anything.invalid.test", s);
  22923. cli->set_no_proxy({"*"});
  22924. auto res = cli->Get("/");
  22925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22926. EXPECT_EQ(0, s.proxy_hits());
  22927. EXPECT_EQ(1, s.target_hits());
  22928. }
  22929. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22930. ProxyAndTargetServers s;
  22931. Client cli("127.0.0.1", s.target_port());
  22932. cli.set_proxy("127.0.0.1", s.proxy_port());
  22933. cli.set_no_proxy({"127.0.0.1"});
  22934. auto res = cli.Get("/");
  22935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22936. EXPECT_EQ(0, s.proxy_hits());
  22937. EXPECT_EQ(1, s.target_hits());
  22938. }
  22939. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22940. ProxyAndTargetServers s;
  22941. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22942. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22943. cli.set_proxy("127.0.0.1", s.proxy_port());
  22944. cli.set_no_proxy({"::1"});
  22945. auto res = cli.Get("/");
  22946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22947. EXPECT_EQ(0, s.proxy_hits());
  22948. EXPECT_EQ(1, s.target_hits());
  22949. }
  22950. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22951. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22952. // must still be recognized as IPv6 for CIDR matching. Implementations
  22953. // that detect IPv6 only when the host begins with '[' would parse the
  22954. // host as a hostname and miss the match.
  22955. ProxyAndTargetServers s;
  22956. Client cli("fe80::1", s.target_port());
  22957. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22958. cli.set_proxy("127.0.0.1", s.proxy_port());
  22959. cli.set_no_proxy({"fe80::/10"});
  22960. auto res = cli.Get("/");
  22961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22962. EXPECT_EQ(0, s.proxy_hits());
  22963. EXPECT_EQ(1, s.target_hits());
  22964. }
  22965. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22966. ProxyAndTargetServers s;
  22967. Client cli("::1", s.target_port());
  22968. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22969. cli.set_proxy("127.0.0.1", s.proxy_port());
  22970. cli.set_no_proxy({"[::1]"});
  22971. auto res = cli.Get("/");
  22972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22973. EXPECT_EQ(0, s.proxy_hits());
  22974. EXPECT_EQ(1, s.target_hits());
  22975. }
  22976. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22977. ProxyAndTargetServers s;
  22978. Client cli("fe80::1", s.target_port());
  22979. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22980. cli.set_proxy("127.0.0.1", s.proxy_port());
  22981. cli.set_no_proxy({"[fe80::]/10"});
  22982. auto res = cli.Get("/");
  22983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22984. EXPECT_EQ(0, s.proxy_hits());
  22985. EXPECT_EQ(1, s.target_hits());
  22986. }
  22987. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22988. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22989. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22990. // tricks via address-family conversion.
  22991. ProxyAndTargetServers s;
  22992. Client cli("::ffff:127.0.0.1", s.target_port());
  22993. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22994. cli.set_proxy("127.0.0.1", s.proxy_port());
  22995. cli.set_no_proxy({"127.0.0.1"});
  22996. auto res = cli.Get("/");
  22997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22998. EXPECT_GE(s.proxy_hits(), 1);
  22999. EXPECT_EQ(0, s.target_hits());
  23000. }
  23001. TEST(NoProxyTest, IPv4CidrMatch) {
  23002. ProxyAndTargetServers s;
  23003. Client cli("127.0.0.1", s.target_port());
  23004. cli.set_proxy("127.0.0.1", s.proxy_port());
  23005. cli.set_no_proxy({"127.0.0.0/8"});
  23006. auto res = cli.Get("/");
  23007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23008. EXPECT_EQ(0, s.proxy_hits());
  23009. EXPECT_EQ(1, s.target_hits());
  23010. }
  23011. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23012. ProxyAndTargetServers s;
  23013. Client cli("127.0.0.1", s.target_port());
  23014. cli.set_proxy("127.0.0.1", s.proxy_port());
  23015. cli.set_no_proxy({"10.0.0.0/8"});
  23016. auto res = cli.Get("/");
  23017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23018. EXPECT_GE(s.proxy_hits(), 1);
  23019. EXPECT_EQ(0, s.target_hits());
  23020. }
  23021. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23022. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23023. // IPv4 target matches.
  23024. ProxyAndTargetServers s;
  23025. Client cli("127.0.0.1", s.target_port());
  23026. cli.set_proxy("127.0.0.1", s.proxy_port());
  23027. cli.set_no_proxy({"0.0.0.0/0"});
  23028. auto res = cli.Get("/");
  23029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23030. EXPECT_EQ(0, s.proxy_hits());
  23031. EXPECT_EQ(1, s.target_hits());
  23032. }
  23033. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23034. ProxyAndTargetServers s;
  23035. Client cli("127.0.0.1", s.target_port());
  23036. cli.set_proxy("127.0.0.1", s.proxy_port());
  23037. cli.set_no_proxy({"127.0.0.1"});
  23038. auto res = cli.Get("/");
  23039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23040. EXPECT_EQ(0, s.proxy_hits());
  23041. EXPECT_EQ(1, s.target_hits());
  23042. }
  23043. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23044. ProxyAndTargetServers s;
  23045. Client cli("127.0.0.1", s.target_port());
  23046. cli.set_proxy("127.0.0.1", s.proxy_port());
  23047. cli.set_no_proxy({"127.0.0.0/33"});
  23048. auto res = cli.Get("/");
  23049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23050. EXPECT_GE(s.proxy_hits(), 1);
  23051. EXPECT_EQ(0, s.target_hits());
  23052. }
  23053. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23054. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23055. ProxyAndTargetServers s;
  23056. Client cli("127.0.0.1", s.target_port());
  23057. cli.set_proxy("127.0.0.1", s.proxy_port());
  23058. cli.set_no_proxy({"127.0.0.1/"});
  23059. auto res = cli.Get("/");
  23060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23061. EXPECT_GE(s.proxy_hits(), 1);
  23062. EXPECT_EQ(0, s.target_hits());
  23063. }
  23064. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23065. ProxyAndTargetServers s;
  23066. auto cli = make_client("internal.corp", s);
  23067. cli->set_proxy_basic_auth("u", "p");
  23068. cli->set_no_proxy({"internal.corp"});
  23069. auto res = cli->Get("/");
  23070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23071. EXPECT_EQ(1, s.target_hits());
  23072. EXPECT_EQ(0, s.proxy_hits());
  23073. EXPECT_FALSE(s.last_had_proxy_authz())
  23074. << "Proxy-Authorization must not be sent direct to the target";
  23075. }
  23076. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23077. ProxyAndTargetServers s;
  23078. auto cli = make_client("public.example", s);
  23079. cli->set_proxy_basic_auth("u", "p");
  23080. cli->set_no_proxy({"internal.corp"}); // does not match
  23081. auto res = cli->Get("/");
  23082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23083. EXPECT_GE(s.proxy_hits(), 1);
  23084. EXPECT_TRUE(s.last_had_proxy_authz());
  23085. }
  23086. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23087. std::atomic<int> hits{0};
  23088. std::atomic<int> hits_with_authz{0};
  23089. no_proxy_test::ScopedServer proxy_mock;
  23090. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23091. hits++;
  23092. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23093. if (req.target.find("/redir") != std::string::npos) {
  23094. res.set_redirect("http://other.example/landed");
  23095. } else {
  23096. res.set_content("via-proxy", "text/plain");
  23097. }
  23098. });
  23099. proxy_mock.listen();
  23100. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23101. hits = 0;
  23102. hits_with_authz = 0;
  23103. Client cli("public.example", 80);
  23104. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23105. cli.set_proxy_basic_auth(c.first, c.second);
  23106. cli.set_follow_location(true);
  23107. // The redirect to another host goes through the proxy as well
  23108. auto res = cli.Get("/redir");
  23109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23110. EXPECT_EQ(2, hits.load());
  23111. EXPECT_EQ(2, hits_with_authz.load());
  23112. }
  23113. }
  23114. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23115. ProxyAndTargetServers s;
  23116. auto cli = make_client("anything.test", s);
  23117. auto res = cli->Get("/");
  23118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23119. EXPECT_GE(s.proxy_hits(), 1);
  23120. EXPECT_EQ(0, s.target_hits());
  23121. }
  23122. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23123. ProxyAndTargetServers s;
  23124. auto cli = make_client("example.com", s);
  23125. cli->set_no_proxy({"example.com:8080"});
  23126. auto res = cli->Get("/");
  23127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23128. EXPECT_GE(s.proxy_hits(), 1);
  23129. EXPECT_EQ(0, s.target_hits());
  23130. }
  23131. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23132. ProxyAndTargetServers s;
  23133. auto cli = make_client("anything.test", s);
  23134. cli->set_no_proxy({"", " ", "\t"});
  23135. auto res = cli->Get("/");
  23136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23137. EXPECT_GE(s.proxy_hits(), 1);
  23138. EXPECT_EQ(0, s.target_hits());
  23139. }
  23140. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23141. // An entry with leading/trailing whitespace must still match — env-style
  23142. // values are commonly pasted with stray spaces and an implementation
  23143. // that feeds the raw token directly to inet_pton would fail to match
  23144. // valid CIDRs because of the spaces.
  23145. ProxyAndTargetServers s;
  23146. Client cli("127.0.0.1", s.target_port());
  23147. cli.set_proxy("127.0.0.1", s.proxy_port());
  23148. cli.set_no_proxy({" 127.0.0.0/8 "});
  23149. auto res = cli.Get("/");
  23150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23151. EXPECT_EQ(0, s.proxy_hits());
  23152. EXPECT_EQ(1, s.target_hits());
  23153. }
  23154. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23155. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23156. // go direct and must NOT carry Proxy-Authorization.
  23157. std::atomic<int> proxy_hits{0};
  23158. std::atomic<int> target_hits{0};
  23159. std::atomic<bool> target_saw_authz{false};
  23160. no_proxy_test::ScopedServer proxy_mock, target;
  23161. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23162. proxy_hits++;
  23163. res.status = 302;
  23164. res.set_header("Location", "http://127.0.0.1:" +
  23165. std::to_string(target.port()) + "/landed");
  23166. });
  23167. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23168. target_hits++;
  23169. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23170. res.set_content("direct", "text/plain");
  23171. });
  23172. proxy_mock.listen();
  23173. target.listen();
  23174. Client cli("public.example", target.port());
  23175. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23176. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23177. cli.set_proxy_basic_auth("u", "p");
  23178. cli.set_no_proxy({"127.0.0.1"});
  23179. cli.set_follow_location(true);
  23180. auto res = cli.Get("/redir");
  23181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23182. EXPECT_GE(proxy_hits.load(), 1);
  23183. EXPECT_GE(target_hits.load(), 1);
  23184. EXPECT_FALSE(target_saw_authz.load());
  23185. }
  23186. #ifdef CPPHTTPLIB_SSL_ENABLED
  23187. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23188. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23189. // proxy creds would be sent to the (possibly hostile) origin.
  23190. std::atomic<int> target_hits{0};
  23191. std::atomic<bool> target_saw_proxy_authz{false};
  23192. no_proxy_test::ScopedServer target;
  23193. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23194. target_hits++;
  23195. if (req.has_header("Proxy-Authorization")) {
  23196. target_saw_proxy_authz = true;
  23197. }
  23198. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23199. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23200. "nonce=\"abc\", algorithm=MD5");
  23201. });
  23202. target.listen();
  23203. // The proxy address is set to the target's port: the bypass MUST kick in;
  23204. // if it doesn't, the test still routes "via proxy" to the same server and
  23205. // the Proxy-Authorization assertion below catches the leak.
  23206. Client cli("evil.example", target.port());
  23207. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23208. cli.set_proxy("127.0.0.1", target.port());
  23209. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23210. cli.set_no_proxy({"evil.example"});
  23211. auto res = cli.Get("/x");
  23212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23213. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23214. EXPECT_EQ(1, target_hits.load());
  23215. EXPECT_FALSE(target_saw_proxy_authz.load());
  23216. }
  23217. #endif
  23218. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23219. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23220. std::atomic<int> proxy_hits{0};
  23221. std::atomic<int> bypass_hits{0};
  23222. std::atomic<bool> proxy_saw_c_url{false};
  23223. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23224. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23225. proxy_hits++;
  23226. if (req.path.find("/start") != std::string::npos) {
  23227. res.status = 302;
  23228. res.set_header("Location", "http://127.0.0.1:" +
  23229. std::to_string(bypass_server.port()) +
  23230. "/middle");
  23231. return;
  23232. }
  23233. if (req.path.find("/end") != std::string::npos) {
  23234. proxy_saw_c_url = true;
  23235. res.set_content("c-via-proxy", "text/plain");
  23236. return;
  23237. }
  23238. res.set_content("unexpected", "text/plain");
  23239. });
  23240. // public.example's "advertised" port is arbitrary (the request never lands
  23241. // there — it goes through the proxy), but use a dynamic value to stay
  23242. // friendly with sharded parallel runs.
  23243. int public_port = bypass_server.port();
  23244. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23245. bypass_hits++;
  23246. res.status = 302;
  23247. res.set_header("Location", "http://public.example:" +
  23248. std::to_string(public_port) + "/end");
  23249. });
  23250. proxy_mock.listen();
  23251. bypass_server.listen();
  23252. Client cli("public.example", public_port);
  23253. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23254. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23255. cli.set_no_proxy({"127.0.0.1"});
  23256. cli.set_follow_location(true);
  23257. auto res = cli.Get("/start");
  23258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23259. EXPECT_EQ(StatusCode::OK_200, res->status);
  23260. EXPECT_EQ("c-via-proxy", res->body);
  23261. EXPECT_GE(proxy_hits.load(), 2);
  23262. EXPECT_GE(bypass_hits.load(), 1);
  23263. EXPECT_TRUE(proxy_saw_c_url.load());
  23264. }
  23265. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23266. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23267. // request reconnects to the correct endpoint.
  23268. std::atomic<int> proxy_hits{0};
  23269. std::atomic<int> target_hits{0};
  23270. no_proxy_test::ScopedServer proxy_mock, target;
  23271. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23272. proxy_hits++;
  23273. res.set_content("via-proxy", "text/plain");
  23274. });
  23275. target.svr().Get(".*", [&](const Request &, Response &res) {
  23276. target_hits++;
  23277. res.set_content("direct", "text/plain");
  23278. });
  23279. proxy_mock.listen();
  23280. target.listen();
  23281. Client cli("public.example", target.port());
  23282. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23283. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23284. cli.set_keep_alive(true);
  23285. auto res1 = cli.Get("/a");
  23286. ASSERT_TRUE(res1);
  23287. EXPECT_EQ("via-proxy", res1->body);
  23288. EXPECT_EQ(1, proxy_hits.load());
  23289. EXPECT_EQ(0, target_hits.load());
  23290. cli.set_no_proxy({"public.example"});
  23291. auto res2 = cli.Get("/b");
  23292. ASSERT_TRUE(res2);
  23293. EXPECT_EQ("direct", res2->body);
  23294. EXPECT_EQ(1, proxy_hits.load());
  23295. EXPECT_EQ(1, target_hits.load());
  23296. }
  23297. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23298. namespace proxy_tunnel_test {
  23299. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23300. class ScopedSSLServer {
  23301. public:
  23302. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23303. port_ = svr_.bind_to_any_port("127.0.0.1");
  23304. }
  23305. ~ScopedSSLServer() {
  23306. svr_.stop();
  23307. if (th_.joinable()) { th_.join(); }
  23308. }
  23309. SSLServer &svr() { return svr_; }
  23310. int port() const { return port_; }
  23311. void listen() {
  23312. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23313. svr_.wait_until_ready();
  23314. }
  23315. private:
  23316. SSLServer svr_;
  23317. std::thread th_;
  23318. int port_ = 0;
  23319. };
  23320. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23321. class ScopedConnectProxy {
  23322. public:
  23323. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23324. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23325. if (listen_fd_ < 0) { return; }
  23326. int yes = 1;
  23327. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23328. sockaddr_in a{};
  23329. a.sin_family = AF_INET;
  23330. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23331. a.sin_port = 0;
  23332. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23333. return;
  23334. }
  23335. socklen_t alen = sizeof(a);
  23336. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23337. 0) {
  23338. return;
  23339. }
  23340. port_ = ntohs(a.sin_port);
  23341. if (::listen(listen_fd_, 1) != 0) { return; }
  23342. th_ = std::thread([this] { run(); });
  23343. }
  23344. ~ScopedConnectProxy() {
  23345. stop_ = true;
  23346. if (listen_fd_ >= 0) {
  23347. ::shutdown(listen_fd_, SHUT_RDWR);
  23348. ::close(listen_fd_);
  23349. }
  23350. if (th_.joinable()) { th_.join(); }
  23351. }
  23352. int port() const { return port_; }
  23353. int connect_hits() const { return connect_hits_.load(); }
  23354. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23355. std::string connect_request() const {
  23356. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23357. return connect_request_;
  23358. }
  23359. private:
  23360. void run() {
  23361. while (!stop_.load()) {
  23362. fd_set rfds;
  23363. FD_ZERO(&rfds);
  23364. FD_SET(listen_fd_, &rfds);
  23365. timeval tv{0, 100 * 1000};
  23366. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23367. if (sel <= 0) { continue; }
  23368. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23369. if (client_fd < 0) { continue; }
  23370. std::string req;
  23371. char buf[2048];
  23372. while (req.find("\r\n\r\n") == std::string::npos) {
  23373. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23374. if (n <= 0) { break; }
  23375. req.append(buf, static_cast<size_t>(n));
  23376. }
  23377. if (req.compare(0, 7, "CONNECT") != 0) {
  23378. ::close(client_fd);
  23379. continue;
  23380. }
  23381. connect_hits_++;
  23382. {
  23383. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23384. connect_request_ = req;
  23385. }
  23386. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23387. ::send(client_fd, ok, std::strlen(ok), 0);
  23388. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23389. sockaddr_in o{};
  23390. o.sin_family = AF_INET;
  23391. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23392. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23393. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23394. 0) {
  23395. ::close(client_fd);
  23396. ::close(origin_fd);
  23397. continue;
  23398. }
  23399. auto forward = [](int from, int to) {
  23400. char b[8192];
  23401. for (;;) {
  23402. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23403. if (n <= 0) { break; }
  23404. ssize_t off = 0;
  23405. while (off < n) {
  23406. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23407. if (s <= 0) {
  23408. off = n;
  23409. break;
  23410. }
  23411. off += s;
  23412. }
  23413. }
  23414. ::shutdown(to, SHUT_WR);
  23415. };
  23416. std::thread t1([&] { forward(client_fd, origin_fd); });
  23417. std::thread t2([&] { forward(origin_fd, client_fd); });
  23418. t1.join();
  23419. t2.join();
  23420. ::close(client_fd);
  23421. ::close(origin_fd);
  23422. }
  23423. }
  23424. int forward_port_ = -1;
  23425. int listen_fd_ = -1;
  23426. int port_ = 0;
  23427. std::thread th_;
  23428. std::atomic<bool> stop_{false};
  23429. std::atomic<int> connect_hits_{0};
  23430. mutable std::mutex connect_request_mutex_;
  23431. std::string connect_request_;
  23432. };
  23433. // Sends one request through the CONNECT proxy to the TLS origin with a
  23434. // credential configured for each hop, and checks that each credential reaches
  23435. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23436. // origin's (every header in origin_headers) on the tunnelled request.
  23437. void CredentialsStayWithTheirHop(
  23438. const std::function<void(SSLClient &)> &set_credentials,
  23439. const std::string &scheme,
  23440. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23441. std::atomic<int> origin_hits{0};
  23442. std::atomic<bool> origin_saw_proxy_authz{false};
  23443. std::atomic<bool> origin_saw_headers{false};
  23444. ScopedSSLServer origin;
  23445. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23446. origin_hits++;
  23447. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23448. origin_saw_headers =
  23449. std::all_of(origin_headers.begin(), origin_headers.end(),
  23450. [&](const std::string &h) { return req.has_header(h); });
  23451. res.set_content("ok", "text/plain");
  23452. });
  23453. origin.listen();
  23454. ScopedConnectProxy proxy(origin.port());
  23455. ASSERT_NE(0, proxy.port());
  23456. // Pinned to 127.0.0.1 for the same reason as the test below.
  23457. SSLClient cli("127.0.0.1", origin.port());
  23458. cli.enable_server_certificate_verification(false);
  23459. cli.set_proxy("127.0.0.1", proxy.port());
  23460. set_credentials(cli);
  23461. auto res = cli.Get("/x");
  23462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23463. EXPECT_EQ(StatusCode::OK_200, res->status);
  23464. EXPECT_EQ(1, origin_hits.load());
  23465. EXPECT_EQ(1, proxy.connect_hits());
  23466. EXPECT_TRUE(origin_saw_headers.load());
  23467. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23468. << "Proxy-Authorization must not be sent inside the tunnel";
  23469. auto connect_req = proxy.connect_request();
  23470. EXPECT_NE(std::string::npos,
  23471. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23472. for (const auto &h : origin_headers) {
  23473. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23474. << h << " must not be sent to the proxy on CONNECT";
  23475. }
  23476. }
  23477. } // namespace proxy_tunnel_test
  23478. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23479. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23480. [](SSLClient &cli) {
  23481. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23482. cli.set_basic_auth("origin-user", "origin-pass");
  23483. },
  23484. "Basic");
  23485. }
  23486. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23487. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23488. [](SSLClient &cli) {
  23489. cli.set_proxy_bearer_token_auth("proxy-token");
  23490. cli.set_bearer_token_auth("origin-token");
  23491. },
  23492. "Bearer");
  23493. }
  23494. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23495. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23496. [](SSLClient &cli) {
  23497. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23498. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23499. {"Cookie", "sid=origin-session"},
  23500. {"X-Api-Key", "origin-key"}});
  23501. },
  23502. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23503. }
  23504. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23505. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23506. // retry; otherwise proxy creds would be sent to the origin.
  23507. std::atomic<int> origin_hits{0};
  23508. std::atomic<bool> origin_saw_proxy_authz{false};
  23509. proxy_tunnel_test::ScopedSSLServer origin;
  23510. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23511. origin_hits++;
  23512. if (req.has_header("Proxy-Authorization")) {
  23513. origin_saw_proxy_authz = true;
  23514. }
  23515. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23516. res.set_header("Proxy-Authenticate",
  23517. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23518. "algorithm=MD5");
  23519. });
  23520. origin.listen();
  23521. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23522. ASSERT_NE(0, proxy.port());
  23523. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23524. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23525. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23526. // and answer with its own status, making this test flaky.
  23527. SSLClient cli("127.0.0.1", origin.port());
  23528. cli.enable_server_certificate_verification(false);
  23529. cli.set_proxy("127.0.0.1", proxy.port());
  23530. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23531. auto res = cli.Get("/x");
  23532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23533. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23534. EXPECT_EQ(1, origin_hits.load());
  23535. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23536. EXPECT_EQ(1, proxy.connect_hits());
  23537. }
  23538. #endif