test.cc 955 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  1058. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*");
  1061. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1470. Server svr;
  1471. std::string file_names;
  1472. svr.Post("/upload", [&](const Request &req, Response &res) {
  1473. for (const auto &file : req.form.files) {
  1474. file_names += file.first + "|" + file.second.filename + " ";
  1475. }
  1476. res.set_content("ok", "text/plain");
  1477. });
  1478. auto port = svr.bind_to_any_port(HOST);
  1479. thread t = thread([&] { svr.listen_after_bind(); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. t.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. // A trailing backslash would otherwise escape the closing quote.
  1487. UploadFormDataItems items = {
  1488. {"dir\\", "x", "a.txt", "text/plain"},
  1489. {"b", "y", "a\\\\b.txt", "text/plain"},
  1490. };
  1491. Client cli(HOST, port);
  1492. auto res = cli.Post("/upload", items);
  1493. ASSERT_TRUE(res);
  1494. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1495. }
  1496. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1497. // Server::read_content() keeps a FormFields::iterator alive across the
  1498. // content callbacks that fill the part it points at. The container is
  1499. // vector-backed, so a later emplace can reallocate and invalidate an older
  1500. // iterator; 64 parts grow the vector through seven reallocations, which
  1501. // checks that every part's content still lands in its own entry.
  1502. const size_t part_count = 64;
  1503. // One formula for both the parts sent and the values expected back, so the
  1504. // two cannot drift apart.
  1505. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1506. auto content_of = [](size_t i) {
  1507. return std::string(64, static_cast<char>('a' + (i % 26)));
  1508. };
  1509. Server svr;
  1510. std::vector<std::pair<std::string, std::string>> received;
  1511. svr.Post("/many", [&](const Request &req, Response &res) {
  1512. for (const auto &field : req.form.fields) {
  1513. received.emplace_back(field.first, field.second.content);
  1514. }
  1515. res.set_content("ok", "text/plain");
  1516. });
  1517. auto port = svr.bind_to_any_port(HOST);
  1518. thread t = thread([&] { svr.listen_after_bind(); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. t.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. UploadFormDataItems items;
  1526. for (size_t i = 0; i < part_count; i++) {
  1527. items.push_back({name_of(i), content_of(i), "", ""});
  1528. }
  1529. Client cli(HOST, port);
  1530. auto res = cli.Post("/many", items);
  1531. ASSERT_TRUE(res);
  1532. ASSERT_EQ(part_count, received.size());
  1533. for (size_t i = 0; i < part_count; i++) {
  1534. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1535. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1536. }
  1537. }
  1538. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1539. string content_type = "multipart/form-data; boundary=something";
  1540. string boundary;
  1541. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(boundary, "something");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1546. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1547. string boundary;
  1548. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1553. string content_type =
  1554. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1555. string boundary;
  1556. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1557. EXPECT_TRUE(ret);
  1558. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1559. }
  1560. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1561. string content_type =
  1562. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1563. string boundary;
  1564. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1565. EXPECT_TRUE(ret);
  1566. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1569. const string boundary(70, 'a');
  1570. string content_type = "multipart/form-data; boundary=" + boundary;
  1571. string parsed;
  1572. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1573. EXPECT_TRUE(ret);
  1574. EXPECT_EQ(parsed, boundary);
  1575. }
  1576. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1577. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1578. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1579. string parsed;
  1580. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1581. EXPECT_FALSE(ret);
  1582. }
  1583. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1584. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1585. // is 72 characters on the wire and still valid.
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1588. string parsed;
  1589. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1590. EXPECT_EQ(parsed, boundary);
  1591. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1592. parsed.clear();
  1593. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1594. }
  1595. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1596. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1597. // The parameter parser must not treat that '=' as the key/value separator.
  1598. string content_type =
  1599. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1600. "charset=UTF-8";
  1601. string parsed;
  1602. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1603. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1606. // A ';' inside the quoted-string is part of the value, not a parameter
  1607. // separator, so it must not truncate the boundary.
  1608. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1609. string parsed;
  1610. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1611. EXPECT_EQ(parsed, "a;b");
  1612. }
  1613. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1614. string parsed;
  1615. EXPECT_TRUE(detail::parse_multipart_boundary(
  1616. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1617. EXPECT_EQ("a\\b", parsed);
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1620. EXPECT_EQ("a\"b", parsed);
  1621. }
  1622. TEST(ParseDispositionParamsTest, QuotedValues) {
  1623. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1624. // ';' and '=' are ordinary characters inside one.
  1625. struct {
  1626. const char *value;
  1627. std::vector<std::pair<const char *, const char *>> expected;
  1628. } cases[] = {
  1629. {"name=\"file1\"; filename=\"a.txt\"",
  1630. {{"name", "file1"}, {"filename", "a.txt"}}},
  1631. // Whitespace around '=' and ';' is still trimmed
  1632. {"name=\"file2\" ;filename = \"a.html\"",
  1633. {{"name", "file2"}, {"filename", "a.html"}}},
  1634. // '=' inside the value used to leave only the text after the last one
  1635. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1636. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1637. {"name=\"x=y\"", {{"name", "x=y"}}},
  1638. // ';' inside the value used to truncate the pair and leave a bogus one
  1639. {"name=\"file3\"; filename=\"a;b.txt\"",
  1640. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1641. // An unquoted value keeps working, and so does filename*
  1642. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1643. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1644. // A parameter with no key is dropped rather than turned into one whose
  1645. // key is the value
  1646. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1647. // An escaped quote does not end the value
  1648. {"name=\"a\\\"; filename=evil.php\"",
  1649. {{"name", "a\"; filename=evil.php"}}},
  1650. // Other backslashes, as in a Windows path, are kept
  1651. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1652. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1653. };
  1654. for (const auto &c : cases) {
  1655. Params params;
  1656. detail::parse_disposition_params(c.value, params);
  1657. for (const auto &kv : c.expected) {
  1658. auto it = params.find(kv.first);
  1659. ASSERT_NE(it, params.end())
  1660. << "value: " << c.value << ", key: " << kv.first;
  1661. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1662. }
  1663. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1664. }
  1665. }
  1666. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1667. Server svr;
  1668. std::string filename;
  1669. std::string content;
  1670. svr.Post("/upload", [&](const Request &req, Response &) {
  1671. const auto &file = req.form.get_file("file");
  1672. filename = file.filename;
  1673. content = file.content;
  1674. });
  1675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1676. auto se = detail::scope_exit([&] {
  1677. svr.stop();
  1678. thread.join();
  1679. ASSERT_FALSE(svr.is_running());
  1680. });
  1681. svr.wait_until_ready();
  1682. std::string body = "--B\r\n"
  1683. "Content-Disposition: form-data; name=\"file\"; "
  1684. "filename=\"a.txt\"\r\n"
  1685. "Content-Type: text/plain\r\n"
  1686. "\r\n"
  1687. "hello\r\n"
  1688. "--B--\r\n";
  1689. Client cli(HOST, PORT);
  1690. auto res = cli.Post(
  1691. "/upload",
  1692. [&](size_t offset, DataSink &sink) {
  1693. if (offset < body.size()) {
  1694. sink.write(&body[offset], 1);
  1695. } else {
  1696. sink.done();
  1697. }
  1698. return true;
  1699. },
  1700. "multipart/form-data; boundary=B");
  1701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ("a.txt", filename);
  1704. EXPECT_EQ("hello", content);
  1705. }
  1706. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1707. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1708. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1709. Server svr;
  1710. std::string field_value, file_name, file_filename;
  1711. bool has_field = false, has_file = false;
  1712. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1713. has_field = req.form.has_field("x=y");
  1714. field_value = req.form.get_field("x=y");
  1715. has_file = req.form.has_file("file1");
  1716. const auto &file = req.form.get_file("file1");
  1717. file_name = file.name;
  1718. file_filename = file.filename;
  1719. res.set_content("ok", "text/plain");
  1720. });
  1721. auto port = svr.bind_to_any_port(HOST);
  1722. thread t = thread([&] { svr.listen_after_bind(); });
  1723. auto se = detail::scope_exit([&] {
  1724. svr.stop();
  1725. t.join();
  1726. ASSERT_FALSE(svr.is_running());
  1727. });
  1728. svr.wait_until_ready();
  1729. UploadFormDataItems items = {
  1730. {"x=y", "field-value", "", ""},
  1731. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1732. };
  1733. Client cli(HOST, port);
  1734. auto res = cli.Post("/quoted", items);
  1735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1736. ASSERT_EQ(StatusCode::OK_200, res->status);
  1737. EXPECT_TRUE(has_field);
  1738. EXPECT_EQ("field-value", field_value);
  1739. EXPECT_TRUE(has_file);
  1740. EXPECT_EQ("file1", file_name);
  1741. EXPECT_EQ("a;b=report.pdf", file_filename);
  1742. }
  1743. TEST(GetHeaderValueTest, DefaultValue) {
  1744. Headers headers = {{"Dummy", "Dummy"}};
  1745. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1746. EXPECT_STREQ("text/plain", val);
  1747. }
  1748. TEST(GetHeaderValueTest, DefaultValueInt) {
  1749. Headers headers = {{"Dummy", "Dummy"}};
  1750. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1751. EXPECT_EQ(100ull, val);
  1752. }
  1753. TEST(GetHeaderValueTest, RegularValue) {
  1754. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/html", val);
  1757. }
  1758. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1759. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1761. EXPECT_STREQ("text/html", val);
  1762. }
  1763. TEST(GetHeaderValueTest, SetContent) {
  1764. Response res;
  1765. res.set_content("html", "text/html");
  1766. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1767. res.set_content("text", "text/plain");
  1768. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1769. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1770. }
  1771. TEST(GetHeaderValueTest, RegularValueInt) {
  1772. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1773. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1774. EXPECT_EQ(100ull, val);
  1775. }
  1776. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1777. Headers headers = {{"Content-Length", "x"}};
  1778. auto is_invalid_value = false;
  1779. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1780. is_invalid_value);
  1781. EXPECT_EQ(0ull, val);
  1782. EXPECT_TRUE(is_invalid_value);
  1783. }
  1784. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1785. // An all-digit value that overflows size_t must be reported as invalid, not
  1786. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1787. // a large length to a small one on 32-bit builds, leaving the framing length
  1788. // wrong while is_invalid_value stayed false.
  1789. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1790. auto is_invalid_value = false;
  1791. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1792. is_invalid_value);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. // A well-formed length is unaffected.
  1795. Headers ok = {{"Content-Length", "1234"}};
  1796. is_invalid_value = false;
  1797. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1798. is_invalid_value);
  1799. EXPECT_EQ(1234ull, val);
  1800. EXPECT_FALSE(is_invalid_value);
  1801. }
  1802. TEST(GetHeaderValueTest, Range) {
  1803. {
  1804. Headers headers = {make_range_header({{1, -1}})};
  1805. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1806. EXPECT_STREQ("bytes=1-", val);
  1807. }
  1808. {
  1809. Headers headers = {make_range_header({{-1, 1}})};
  1810. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1811. EXPECT_STREQ("bytes=-1", val);
  1812. }
  1813. {
  1814. Headers headers = {make_range_header({{1, 10}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-10", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=1-10, 100-", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=0-0, -1", val);
  1832. }
  1833. }
  1834. TEST(BearerTokenAuthTest, SchemeValidation) {
  1835. // A value shorter than "Bearer " must not throw from the fixed-length
  1836. // substr, and a non-Bearer scheme must not be reported as a token.
  1837. struct {
  1838. const char *value;
  1839. const char *expected;
  1840. } cases[] = {
  1841. {"x", ""},
  1842. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1843. {"Bearer abc123", "abc123"},
  1844. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1845. };
  1846. for (const auto &c : cases) {
  1847. Request req;
  1848. req.set_header("Authorization", c.value);
  1849. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1850. }
  1851. }
  1852. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1853. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1854. // to depend on the standard library (libstdc++ handed back duplicates in
  1855. // reverse insertion order, libc++ in insertion order).
  1856. Request req;
  1857. req.set_header("Accept-Encoding", "gzip");
  1858. req.set_header("Accept-Encoding", "deflate");
  1859. req.set_header("Accept-Encoding", "br");
  1860. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1861. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1863. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1864. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1865. }
  1866. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1867. Request req;
  1868. req.set_header("X-Test", "only");
  1869. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1870. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1872. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1873. }
  1874. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1875. Request req;
  1876. req.set_header("X-First", "1");
  1877. req.set_header("X-Test", "2");
  1878. req.params.emplace("first", "1");
  1879. req.params.emplace("test", "2");
  1880. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1881. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1882. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1883. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1884. // The second one is negative when read as a signed value
  1885. const auto max_id = (std::numeric_limits<size_t>::max)();
  1886. for (auto id : {max_id / 2, max_id}) {
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1888. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1889. EXPECT_EQ("", req.get_param_value("test", id));
  1890. EXPECT_EQ("", req.form.get_field("test", id));
  1891. EXPECT_EQ("", req.form.get_file("test", id).content);
  1892. }
  1893. }
  1894. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1895. Headers headers;
  1896. headers.emplace("Host", "example.com");
  1897. headers.emplace("Accept-Encoding", "gzip");
  1898. headers.emplace("User-Agent", "test");
  1899. headers.emplace("Accept-Encoding", "deflate");
  1900. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1901. "Accept-Encoding=deflate ",
  1902. entries_to_string(headers));
  1903. }
  1904. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1905. Headers headers = {{"Content-Type", "text/html"},
  1906. {"CONTENT-TYPE", "text/xml"}};
  1907. EXPECT_EQ(2U, headers.count("content-type"));
  1908. auto it = headers.find("content-type");
  1909. ASSERT_TRUE(it != headers.end());
  1910. EXPECT_EQ("text/html", it->second);
  1911. }
  1912. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1913. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1914. // drop only those fields and leave everything positioned between them.
  1915. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1916. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1917. auto rng = headers.equal_range("a");
  1918. headers.erase(rng.first, rng.second);
  1919. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1922. Headers headers = {
  1923. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1924. EXPECT_EQ(3U, headers.erase("A"));
  1925. EXPECT_EQ(0U, headers.count("A"));
  1926. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1927. }
  1928. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1929. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1930. headers.emplace_front("Host", "example.com");
  1931. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1932. entries_to_string(headers));
  1933. }
  1934. TEST(ParseHeaderValueTest, Range) {
  1935. {
  1936. Ranges ranges;
  1937. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(1u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(-1, ranges[0].second);
  1942. }
  1943. {
  1944. Ranges ranges;
  1945. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1946. EXPECT_TRUE(ret);
  1947. EXPECT_EQ(1u, ranges.size());
  1948. EXPECT_EQ(-1, ranges[0].first);
  1949. EXPECT_EQ(1u, ranges[0].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ(1u, ranges.size());
  1956. EXPECT_EQ(1u, ranges[0].first);
  1957. EXPECT_EQ(10u, ranges[0].second);
  1958. }
  1959. {
  1960. Ranges ranges;
  1961. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1962. EXPECT_FALSE(ret);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ(2u, ranges.size());
  1969. EXPECT_EQ(1u, ranges[0].first);
  1970. EXPECT_EQ(10u, ranges[0].second);
  1971. EXPECT_EQ(100u, ranges[1].first);
  1972. EXPECT_EQ(-1, ranges[1].second);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ(3u, ranges.size());
  1980. EXPECT_EQ(1u, ranges[0].first);
  1981. EXPECT_EQ(10u, ranges[0].second);
  1982. EXPECT_EQ(100u, ranges[1].first);
  1983. EXPECT_EQ(200u, ranges[1].second);
  1984. EXPECT_EQ(300u, ranges[2].first);
  1985. EXPECT_EQ(400u, ranges[2].second);
  1986. }
  1987. {
  1988. Ranges ranges;
  1989. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2002. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2003. EXPECT_FALSE(
  2004. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2005. EXPECT_TRUE(ranges.empty());
  2006. }
  2007. {
  2008. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2009. // remainder of the representation, so it stays accepted.
  2010. Ranges ranges;
  2011. auto ret =
  2012. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2013. EXPECT_TRUE(ret);
  2014. ASSERT_EQ(1u, ranges.size());
  2015. EXPECT_EQ(0, ranges[0].first);
  2016. EXPECT_EQ(-1, ranges[0].second);
  2017. }
  2018. // RFC 9110 14.1: range unit names are case-insensitive.
  2019. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2020. Ranges ranges;
  2021. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2022. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2023. }
  2024. }
  2025. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2033. #else
  2034. EXPECT_TRUE(ret == detail::EncodingType::None);
  2035. #endif
  2036. }
  2037. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2038. Request req;
  2039. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2040. Response res;
  2041. res.set_header("Content-Type", "text/plain");
  2042. auto ret = detail::encoding_type(req, res);
  2043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2049. #else
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. #endif
  2052. }
  2053. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2054. Request req;
  2055. req.set_header("Accept-Encoding",
  2056. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2057. Response res;
  2058. res.set_header("Content-Type", "text/plain");
  2059. auto ret = detail::encoding_type(req, res);
  2060. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2062. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2064. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2066. #else
  2067. EXPECT_TRUE(ret == detail::EncodingType::None);
  2068. #endif
  2069. }
  2070. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2071. // All supported encodings rejected with q=0 should return None
  2072. Request req;
  2073. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2074. Response res;
  2075. res.set_header("Content-Type", "text/plain");
  2076. auto ret = detail::encoding_type(req, res);
  2077. EXPECT_TRUE(ret == detail::EncodingType::None);
  2078. }
  2079. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2080. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2081. Request req;
  2082. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2083. Response res;
  2084. res.set_header("Content-Type", "text/plain");
  2085. auto ret = detail::encoding_type(req, res);
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. }
  2088. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2089. Request req;
  2090. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2091. Response res;
  2092. res.set_header("Content-Type", "text/plain");
  2093. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2094. }
  2095. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2096. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2097. Request req;
  2098. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2099. Response res;
  2100. res.set_header("Content-Type", "text/plain");
  2101. auto ret = detail::encoding_type(req, res);
  2102. EXPECT_TRUE(ret == detail::EncodingType::None);
  2103. }
  2104. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2105. // RFC 7231: Accept-Encoding values are case-insensitive
  2106. Request req;
  2107. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2108. Response res;
  2109. res.set_header("Content-Type", "text/plain");
  2110. auto ret = detail::encoding_type(req, res);
  2111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2112. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2113. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2114. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2115. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2116. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2117. #else
  2118. EXPECT_TRUE(ret == detail::EncodingType::None);
  2119. #endif
  2120. }
  2121. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2122. // q value should determine priority, not hardcoded order
  2123. Request req;
  2124. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2125. Response res;
  2126. res.set_header("Content-Type", "text/plain");
  2127. auto ret = detail::encoding_type(req, res);
  2128. // gzip has highest q=1.0, so it should be selected even though
  2129. // br and zstd are also supported
  2130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2132. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2133. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2134. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2135. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2136. #else
  2137. EXPECT_TRUE(ret == detail::EncodingType::None);
  2138. #endif
  2139. }
  2140. TEST(BufferStreamTest, read) {
  2141. detail::BufferStream strm1;
  2142. Stream &strm = strm1;
  2143. EXPECT_EQ(5, strm.write("hello"));
  2144. char buf[512];
  2145. EXPECT_EQ(2, strm.read(buf, 2));
  2146. EXPECT_EQ('h', buf[0]);
  2147. EXPECT_EQ('e', buf[1]);
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('l', buf[0]);
  2150. EXPECT_EQ('l', buf[1]);
  2151. EXPECT_EQ(1, strm.read(buf, 1));
  2152. EXPECT_EQ('o', buf[0]);
  2153. EXPECT_EQ(0, strm.read(buf, 1));
  2154. }
  2155. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2156. auto host = "www.httpwatch.com";
  2157. auto ip = hosted_at(host);
  2158. EXPECT_EQ("23.96.13.243", ip);
  2159. std::vector<std::string> addrs;
  2160. hosted_at(host, addrs);
  2161. EXPECT_EQ(1u, addrs.size());
  2162. }
  2163. #if 0 // It depends on each test environment...
  2164. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2165. auto host = "www.youtube.com";
  2166. std::vector<std::string> addrs;
  2167. hosted_at(host, addrs);
  2168. EXPECT_EQ(20u, addrs.size());
  2169. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2170. EXPECT_TRUE(it != addrs.end());
  2171. }
  2172. #endif
  2173. class ChunkedEncodingTest : public ::testing::Test {
  2174. protected:
  2175. ChunkedEncodingTest()
  2176. : cli_(HOST, PORT)
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. ,
  2179. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2180. #endif
  2181. {
  2182. cli_.set_connection_timeout(2);
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. cli_.enable_server_certificate_verification(false);
  2185. #endif
  2186. }
  2187. virtual void SetUp() {
  2188. read_file("./image.jpg", image_data_);
  2189. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2190. res.set_content("Hello World!", "text/plain");
  2191. });
  2192. svr_.Get(
  2193. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2194. res.set_chunked_content_provider(
  2195. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2196. size_t remaining = image_data_.size() - offset;
  2197. if (remaining == 0) {
  2198. sink.done();
  2199. } else {
  2200. constexpr size_t CHUNK_SIZE = 1024;
  2201. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2202. sink.write(&image_data_[offset], send_size);
  2203. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2204. }
  2205. return true;
  2206. });
  2207. });
  2208. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2209. svr_.wait_until_ready();
  2210. }
  2211. virtual void TearDown() {
  2212. svr_.stop();
  2213. if (!request_threads_.empty()) {
  2214. std::this_thread::sleep_for(std::chrono::seconds(1));
  2215. for (auto &t : request_threads_) {
  2216. t.join();
  2217. }
  2218. }
  2219. t_.join();
  2220. }
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. SSLClient cli_;
  2223. SSLServer svr_;
  2224. #else
  2225. Client cli_;
  2226. Server svr_;
  2227. #endif
  2228. thread t_;
  2229. std::vector<thread> request_threads_;
  2230. std::string image_data_;
  2231. };
  2232. TEST_F(ChunkedEncodingTest, NormalGet) {
  2233. auto res = cli_.Get("/chunked");
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, res->body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2243. body.append(data, data_length);
  2244. return true;
  2245. });
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. std::string out;
  2248. read_file("./image.jpg", out);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. EXPECT_EQ(out, body);
  2251. }
  2252. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2253. std::string body;
  2254. auto res = cli_.Get(
  2255. "/chunked",
  2256. [&](const Response &response) {
  2257. EXPECT_EQ(StatusCode::OK_200, response.status);
  2258. return true;
  2259. },
  2260. [&](const char *data, size_t data_length) {
  2261. body.append(data, data_length);
  2262. return true;
  2263. });
  2264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2265. std::string out;
  2266. read_file("./image.jpg", out);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ(out, body);
  2269. }
  2270. TEST(RangeTest, FromHTTPBin_Online) {
  2271. auto host = "httpbingo.org";
  2272. auto path = std::string{"/range/32"};
  2273. #ifdef CPPHTTPLIB_SSL_ENABLED
  2274. auto port = 443;
  2275. SSLClient cli(host, port);
  2276. #else
  2277. auto port = 80;
  2278. Client cli(host, port);
  2279. #endif
  2280. cli.set_connection_timeout(5);
  2281. {
  2282. auto res = cli.Get(path);
  2283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2284. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. {
  2288. Headers headers = {make_range_header({{1, -1}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2293. }
  2294. {
  2295. Headers headers = {make_range_header({{1, 10}})};
  2296. auto res = cli.Get(path, headers);
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. EXPECT_EQ("bcdefghijk", res->body);
  2299. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2300. }
  2301. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2302. // entire resource, while the original httpbin returned 200. Both are
  2303. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2304. {
  2305. Headers headers = {make_range_header({{0, 31}})};
  2306. auto res = cli.Get(path, headers);
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2309. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2310. res->status == StatusCode::PartialContent_206);
  2311. }
  2312. {
  2313. Headers headers = {make_range_header({{0, -1}})};
  2314. auto res = cli.Get(path, headers);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2317. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2318. res->status == StatusCode::PartialContent_206);
  2319. }
  2320. // go-httpbin returns 206 with clamped range for over-range requests,
  2321. // while the original httpbin returned 416. Both behaviors are observed
  2322. // in real servers, so we only verify the request succeeds.
  2323. {
  2324. Headers headers = {make_range_header({{0, 32}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. }
  2328. }
  2329. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2330. auto host = "unresolvableaddress.local";
  2331. auto path = std::string{"/"};
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. auto port = 443;
  2334. SSLClient cli(host, port);
  2335. #else
  2336. auto port = 80;
  2337. Client cli(host, port);
  2338. #endif
  2339. cli.set_connection_timeout(1);
  2340. {
  2341. auto res = cli.Get(path);
  2342. ASSERT_FALSE(res);
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(8));
  2345. }
  2346. #if defined(__linux__) && defined(__GLIBC__) && \
  2347. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2348. // Forward declaration: in split builds split.py strips `inline` and moves the
  2349. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2350. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2351. // against the symbol in both header-only and split builds.
  2352. namespace httplib {
  2353. namespace detail {
  2354. int getaddrinfo_with_timeout(const char *node, const char *service,
  2355. const struct addrinfo *hints,
  2356. struct addrinfo **res, time_t timeout_sec);
  2357. } // namespace detail
  2358. } // namespace httplib
  2359. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2360. //
  2361. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2362. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2363. // gai_suspend() call hits the connection timeout the function calls
  2364. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2365. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2366. // still alive and still references the now-destroyed stack frame.
  2367. //
  2368. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2369. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2370. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2371. // and runs them in a container.
  2372. namespace {
  2373. bool should_run_issue_2431_tests() {
  2374. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2375. return v && *v && std::string(v) != "0";
  2376. }
  2377. std::string unique_unresolvable_host(int n) {
  2378. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2379. // glibc still asks the configured nameserver — which is exactly the path
  2380. // we want to exercise. A unique label per call avoids the resolver cache.
  2381. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2382. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2383. std::to_string(n) + ".invalid";
  2384. }
  2385. } // namespace
  2386. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2387. if (!should_run_issue_2431_tests()) {
  2388. GTEST_SKIP()
  2389. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2390. }
  2391. for (int i = 0; i < 8; ++i) {
  2392. struct addrinfo hints;
  2393. memset(&hints, 0, sizeof(hints));
  2394. hints.ai_family = AF_UNSPEC;
  2395. hints.ai_socktype = SOCK_STREAM;
  2396. auto host = unique_unresolvable_host(i);
  2397. struct addrinfo *result = nullptr;
  2398. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2399. &result, /*timeout_sec=*/1);
  2400. if (rc == 0 && result) { freeaddrinfo(result); }
  2401. }
  2402. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2403. // stack region they still believe holds their gaicb.
  2404. std::this_thread::sleep_for(std::chrono::seconds(3));
  2405. }
  2406. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2407. if (!should_run_issue_2431_tests()) {
  2408. GTEST_SKIP()
  2409. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2410. }
  2411. std::atomic<bool> stop{false};
  2412. std::vector<std::thread> threads;
  2413. for (int t = 0; t < 8; ++t) {
  2414. threads.emplace_back([t, &stop] {
  2415. int i = 0;
  2416. while (!stop.load(std::memory_order_relaxed)) {
  2417. struct addrinfo hints;
  2418. memset(&hints, 0, sizeof(hints));
  2419. hints.ai_family = AF_UNSPEC;
  2420. hints.ai_socktype = SOCK_STREAM;
  2421. auto host = unique_unresolvable_host(t * 100000 + i++);
  2422. struct addrinfo *result = nullptr;
  2423. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2424. &result, /*timeout_sec=*/1);
  2425. if (rc == 0 && result) { freeaddrinfo(result); }
  2426. }
  2427. });
  2428. }
  2429. std::this_thread::sleep_for(std::chrono::seconds(8));
  2430. stop.store(true, std::memory_order_relaxed);
  2431. for (auto &th : threads) {
  2432. th.join();
  2433. }
  2434. std::this_thread::sleep_for(std::chrono::seconds(3));
  2435. }
  2436. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2437. if (!should_run_issue_2431_tests()) {
  2438. GTEST_SKIP()
  2439. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2440. }
  2441. std::atomic<bool> stop{false};
  2442. std::vector<std::thread> threads;
  2443. for (int t = 0; t < 8; ++t) {
  2444. threads.emplace_back([t, &stop] {
  2445. int i = 0;
  2446. while (!stop.load(std::memory_order_relaxed)) {
  2447. auto host = unique_unresolvable_host(t * 100000 + i++);
  2448. Client cli(host, 80);
  2449. cli.set_connection_timeout(1, 0);
  2450. cli.set_read_timeout(1, 0);
  2451. cli.set_write_timeout(1, 0);
  2452. (void)cli.Get("/");
  2453. }
  2454. });
  2455. }
  2456. std::this_thread::sleep_for(std::chrono::seconds(8));
  2457. stop.store(true, std::memory_order_relaxed);
  2458. for (auto &th : threads) {
  2459. th.join();
  2460. }
  2461. std::this_thread::sleep_for(std::chrono::seconds(3));
  2462. }
  2463. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2464. TEST(ConnectionErrorTest, InvalidHost) {
  2465. auto host = "-abcde.com";
  2466. #ifdef CPPHTTPLIB_SSL_ENABLED
  2467. auto port = 443;
  2468. SSLClient cli(host, port);
  2469. #else
  2470. auto port = 80;
  2471. Client cli(host, port);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHost2) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. EXPECT_EQ(Error::Connection, res.error());
  2489. }
  2490. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2491. auto host = "httpcan.org/";
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(host);
  2494. #else
  2495. Client cli(host);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(2));
  2498. auto res = cli.Get("/");
  2499. ASSERT_TRUE(!res);
  2500. stringstream s;
  2501. s << "error code: " << res.error();
  2502. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2503. }
  2504. TEST(ConnectionErrorTest, InvalidPort) {
  2505. auto host = "localhost";
  2506. auto port = 44380;
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. SSLClient cli(host, port);
  2509. #else
  2510. Client cli(host, port);
  2511. #endif
  2512. cli.set_connection_timeout(std::chrono::seconds(2));
  2513. auto res = cli.Get("/");
  2514. ASSERT_TRUE(!res);
  2515. EXPECT_TRUE(Error::Connection == res.error() ||
  2516. Error::ConnectionTimeout == res.error());
  2517. }
  2518. TEST(ConnectionErrorTest, Timeout_Online) {
  2519. auto host = "google.com";
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 44380;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 8080;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(std::chrono::seconds(2));
  2528. // only probe one address type so that the error reason
  2529. // correlates to the timed-out IPv4, not the unsupported
  2530. // IPv6 connection attempt
  2531. cli.set_address_family(AF_INET);
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2535. }
  2536. TEST(CancelTest, NoCancel_Online) {
  2537. auto host = "httpbingo.org";
  2538. auto path = std::string{"/range/32"};
  2539. #ifdef CPPHTTPLIB_SSL_ENABLED
  2540. auto port = 443;
  2541. SSLClient cli(host, port);
  2542. #else
  2543. auto port = 80;
  2544. Client cli(host, port);
  2545. #endif
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2553. // Use /bytes with a large payload so that the DownloadProgress callback
  2554. // (which only fires for Content-Length responses) is invoked before the
  2555. // entire body is received, giving cancellation a chance to fire.
  2556. auto host = "httpbingo.org";
  2557. auto path = std::string{"/bytes/524288"};
  2558. #ifdef CPPHTTPLIB_SSL_ENABLED
  2559. auto port = 443;
  2560. SSLClient cli(host, port);
  2561. #else
  2562. auto port = 80;
  2563. Client cli(host, port);
  2564. #endif
  2565. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Canceled, res.error());
  2569. }
  2570. TEST(CancelTest, WithCancelLargePayload_Online) {
  2571. auto host = "httpbingo.org";
  2572. auto path = std::string{"/bytes/524288"};
  2573. #ifdef CPPHTTPLIB_SSL_ENABLED
  2574. auto port = 443;
  2575. SSLClient cli(host, port);
  2576. #else
  2577. auto port = 80;
  2578. Client cli(host, port);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(5));
  2581. uint32_t count = 0;
  2582. auto res =
  2583. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, NoCancelPost) {
  2588. Server svr;
  2589. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2590. res.set_content("Hello World!", "text/plain");
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. Client cli(HOST, PORT);
  2600. cli.set_connection_timeout(std::chrono::seconds(5));
  2601. auto res =
  2602. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2603. "application/json", [](uint64_t, uint64_t) { return true; });
  2604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2605. EXPECT_EQ("Hello World!", res->body);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. }
  2608. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2609. Server svr;
  2610. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!", "text/plain");
  2612. });
  2613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2614. auto se = detail::scope_exit([&] {
  2615. svr.stop();
  2616. thread.join();
  2617. ASSERT_FALSE(svr.is_running());
  2618. });
  2619. svr.wait_until_ready();
  2620. Client cli(HOST, PORT);
  2621. cli.set_connection_timeout(std::chrono::seconds(5));
  2622. auto res =
  2623. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2624. "application/json", [](uint64_t, uint64_t) { return false; });
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayloadPost) {
  2629. Server svr;
  2630. svr.set_payload_max_length(200 * 1024 * 1024);
  2631. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2632. res.set_content(LARGE_DATA, "text/plain");
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. Client cli(HOST, PORT);
  2642. cli.set_payload_max_length(200 * 1024 * 1024);
  2643. cli.set_connection_timeout(std::chrono::seconds(5));
  2644. auto res =
  2645. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2646. "application/json", [](uint64_t, uint64_t) { return false; });
  2647. ASSERT_TRUE(!res);
  2648. EXPECT_EQ(Error::Canceled, res.error());
  2649. }
  2650. TEST(CancelTest, NoCancelPut) {
  2651. Server svr;
  2652. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2653. res.set_content("Hello World!", "text/plain");
  2654. });
  2655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2656. auto se = detail::scope_exit([&] {
  2657. svr.stop();
  2658. thread.join();
  2659. ASSERT_FALSE(svr.is_running());
  2660. });
  2661. svr.wait_until_ready();
  2662. Client cli(HOST, PORT);
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. auto res =
  2665. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2666. "application/json", [](uint64_t, uint64_t) { return true; });
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ("Hello World!", res->body);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2672. Server svr;
  2673. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2674. res.set_content("Hello World!", "text/plain");
  2675. });
  2676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2677. auto se = detail::scope_exit([&] {
  2678. svr.stop();
  2679. thread.join();
  2680. ASSERT_FALSE(svr.is_running());
  2681. });
  2682. svr.wait_until_ready();
  2683. Client cli(HOST, PORT);
  2684. cli.set_connection_timeout(std::chrono::seconds(5));
  2685. auto res =
  2686. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2687. "application/json", [](uint64_t, uint64_t) { return false; });
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Canceled, res.error());
  2690. }
  2691. TEST(CancelTest, WithCancelLargePayloadPut) {
  2692. Server svr;
  2693. svr.set_payload_max_length(200 * 1024 * 1024);
  2694. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2695. res.set_content(LARGE_DATA, "text/plain");
  2696. });
  2697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2698. auto se = detail::scope_exit([&] {
  2699. svr.stop();
  2700. thread.join();
  2701. ASSERT_FALSE(svr.is_running());
  2702. });
  2703. svr.wait_until_ready();
  2704. Client cli(HOST, PORT);
  2705. cli.set_payload_max_length(200 * 1024 * 1024);
  2706. cli.set_connection_timeout(std::chrono::seconds(5));
  2707. auto res =
  2708. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2709. "application/json", [](uint64_t, uint64_t) { return false; });
  2710. ASSERT_TRUE(!res);
  2711. EXPECT_EQ(Error::Canceled, res.error());
  2712. }
  2713. TEST(CancelTest, NoCancelPatch) {
  2714. Server svr;
  2715. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2716. res.set_content("Hello World!", "text/plain");
  2717. });
  2718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2719. auto se = detail::scope_exit([&] {
  2720. svr.stop();
  2721. thread.join();
  2722. ASSERT_FALSE(svr.is_running());
  2723. });
  2724. svr.wait_until_ready();
  2725. Client cli(HOST, PORT);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return true; });
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ("Hello World!", res->body);
  2732. EXPECT_EQ(StatusCode::OK_200, res->status);
  2733. }
  2734. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2735. Server svr;
  2736. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2737. res.set_content("Hello World!", "text/plain");
  2738. });
  2739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. thread.join();
  2743. ASSERT_FALSE(svr.is_running());
  2744. });
  2745. svr.wait_until_ready();
  2746. Client cli(HOST, PORT);
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res =
  2749. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2750. "application/json", [](uint64_t, uint64_t) { return false; });
  2751. ASSERT_TRUE(!res);
  2752. EXPECT_EQ(Error::Canceled, res.error());
  2753. }
  2754. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2755. Server svr;
  2756. svr.set_payload_max_length(200 * 1024 * 1024);
  2757. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2758. res.set_content(LARGE_DATA, "text/plain");
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. Client cli(HOST, PORT);
  2768. cli.set_payload_max_length(200 * 1024 * 1024);
  2769. cli.set_connection_timeout(std::chrono::seconds(5));
  2770. auto res =
  2771. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2772. "application/json", [](uint64_t, uint64_t) { return false; });
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, NoCancelDelete) {
  2777. Server svr;
  2778. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2779. res.set_content("Hello World!", "text/plain");
  2780. });
  2781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2782. auto se = detail::scope_exit([&] {
  2783. svr.stop();
  2784. thread.join();
  2785. ASSERT_FALSE(svr.is_running());
  2786. });
  2787. svr.wait_until_ready();
  2788. Client cli(HOST, PORT);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return true; });
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. EXPECT_EQ("Hello World!", res->body);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. }
  2797. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2798. Server svr;
  2799. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2803. auto se = detail::scope_exit([&] {
  2804. svr.stop();
  2805. thread.join();
  2806. ASSERT_FALSE(svr.is_running());
  2807. });
  2808. svr.wait_until_ready();
  2809. Client cli(HOST, PORT);
  2810. cli.set_connection_timeout(std::chrono::seconds(5));
  2811. auto res =
  2812. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2813. "application/json", [](uint64_t, uint64_t) { return false; });
  2814. ASSERT_TRUE(!res);
  2815. EXPECT_EQ(Error::Canceled, res.error());
  2816. }
  2817. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2818. Server svr;
  2819. svr.set_payload_max_length(200 * 1024 * 1024);
  2820. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2821. res.set_content(LARGE_DATA, "text/plain");
  2822. });
  2823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2824. auto se = detail::scope_exit([&] {
  2825. svr.stop();
  2826. thread.join();
  2827. ASSERT_FALSE(svr.is_running());
  2828. });
  2829. svr.wait_until_ready();
  2830. Client cli(HOST, PORT);
  2831. cli.set_payload_max_length(200 * 1024 * 1024);
  2832. cli.set_connection_timeout(std::chrono::seconds(5));
  2833. auto res =
  2834. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2835. "application/json", [](uint64_t, uint64_t) { return false; });
  2836. ASSERT_TRUE(!res);
  2837. EXPECT_EQ(Error::Canceled, res.error());
  2838. }
  2839. static std::string remove_whitespace(const std::string &input) {
  2840. std::string output;
  2841. output.reserve(input.size());
  2842. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2843. [](unsigned char c) { return !std::isspace(c); });
  2844. return output;
  2845. }
  2846. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2847. auto host = "httpbingo.org";
  2848. auto path = std::string{"/basic-auth/hello/world"};
  2849. #ifdef CPPHTTPLIB_SSL_ENABLED
  2850. auto port = 443;
  2851. SSLClient cli(host, port);
  2852. #else
  2853. auto port = 80;
  2854. Client cli(host, port);
  2855. #endif
  2856. {
  2857. auto res = cli.Get(path);
  2858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2860. }
  2861. {
  2862. auto res = cli.Get(
  2863. path, Headers{make_basic_authentication_header("hello", "world")});
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. auto body = remove_whitespace(res->body);
  2866. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2867. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2868. EXPECT_EQ(StatusCode::OK_200, res->status);
  2869. }
  2870. {
  2871. cli.set_basic_auth("hello", "world");
  2872. auto res = cli.Get(path);
  2873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2874. auto body = remove_whitespace(res->body);
  2875. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2876. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. {
  2880. cli.set_basic_auth("hello", "bad");
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2884. }
  2885. {
  2886. cli.set_basic_auth("bad", "world");
  2887. auto res = cli.Get(path);
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2890. }
  2891. }
  2892. #ifdef CPPHTTPLIB_SSL_ENABLED
  2893. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2894. auto host = "httpbingo.org";
  2895. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2896. auto paths = std::vector<std::string>{
  2897. "/digest-auth/auth/hello/world/MD5",
  2898. "/digest-auth/auth/hello/world/SHA-256",
  2899. };
  2900. auto port = 443;
  2901. SSLClient cli(host, port);
  2902. {
  2903. auto res = cli.Get(unauth_path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. {
  2908. cli.set_digest_auth("hello", "world");
  2909. for (const auto &path : paths) {
  2910. auto res = cli.Get(path.c_str());
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. auto body = remove_whitespace(res->body);
  2913. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2914. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. }
  2917. cli.set_digest_auth("hello", "bad");
  2918. for (const auto &path : paths) {
  2919. auto res = cli.Get(path.c_str());
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. }
  2924. }
  2925. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2926. // comma-separated list of challenges, and each challenge may itself carry a
  2927. // comma-separated auth-param list, so a server can legally offer Basic
  2928. // before Digest, either as two field lines or packed into one. Runs one 401
  2929. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2930. // value() joins them in receipt order) and checks that the retry carries a
  2931. // well-formed Digest Authorization header naming expected_realm.
  2932. static void
  2933. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2934. const std::string &expected_realm) {
  2935. std::atomic<int> hits{0};
  2936. Server svr;
  2937. svr.Get("/x", [&](const Request &req, Response &res) {
  2938. if (++hits == 1) {
  2939. res.status = StatusCode::Unauthorized_401;
  2940. for (const auto &challenge : challenges) {
  2941. res.set_header("WWW-Authenticate", challenge);
  2942. }
  2943. } else {
  2944. auto authorization = req.get_header_value("Authorization");
  2945. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2946. EXPECT_NE(std::string::npos,
  2947. authorization.find("realm=\"" + expected_realm + "\""));
  2948. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2949. res.set_content("ok", "text/plain");
  2950. }
  2951. });
  2952. auto port = svr.bind_to_any_port(HOST);
  2953. std::thread t([&]() { svr.listen_after_bind(); });
  2954. auto se = detail::scope_exit([&] {
  2955. svr.stop();
  2956. t.join();
  2957. });
  2958. svr.wait_until_ready();
  2959. Client cli(HOST, port);
  2960. cli.set_digest_auth("hello", "world");
  2961. auto res = cli.Get("/x");
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(2, hits.load());
  2964. }
  2965. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2966. static const char *kDigestChallenge =
  2967. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2968. "algorithm=MD5";
  2969. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2970. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2971. "testrealm");
  2972. }
  2973. // Same challenge list with the schemes in the opposite order, to make sure
  2974. // the fix above didn't just special-case "Basic first".
  2975. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2976. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2977. "testrealm");
  2978. }
  2979. // A comma inside a quoted auth-param value must not be mistaken for the
  2980. // separator between two challenges (or two auth-params).
  2981. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2982. run_digest_challenge_list_test(
  2983. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5"},
  2985. "test,realm");
  2986. }
  2987. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2988. // the params and leaves out the fragment.
  2989. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2990. Server svr;
  2991. std::string uri, target;
  2992. svr.Get("/a b", [&](const Request &req, Response &res) {
  2993. auto auth = req.get_header_value("Authorization");
  2994. if (auth.empty()) {
  2995. res.status = StatusCode::Unauthorized_401;
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2998. return;
  2999. }
  3000. auto b = auth.find("uri=\"") + 5;
  3001. uri = auth.substr(b, auth.find('"', b) - b);
  3002. target = req.target;
  3003. });
  3004. auto port = svr.bind_to_any_port(HOST);
  3005. std::thread t([&]() { svr.listen_after_bind(); });
  3006. auto se = detail::scope_exit([&] {
  3007. svr.stop();
  3008. t.join();
  3009. });
  3010. svr.wait_until_ready();
  3011. Client cli(HOST, port);
  3012. cli.set_digest_auth("hello", "world");
  3013. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3015. EXPECT_EQ("/a%20b?x=1", target);
  3016. EXPECT_EQ(target, uri);
  3017. }
  3018. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3019. // make_digest_authentication_header() dereferences both unconditionally, so
  3020. // a server sending a challenge missing either one must not be treated as
  3021. // usable -- doing so used to crash the client with std::out_of_range.
  3022. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3023. Server svr;
  3024. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3025. res.status = StatusCode::Unauthorized_401;
  3026. res.set_header("WWW-Authenticate", challenge);
  3027. });
  3028. auto port = svr.bind_to_any_port(HOST);
  3029. std::thread t([&]() { svr.listen_after_bind(); });
  3030. auto se = detail::scope_exit([&] {
  3031. svr.stop();
  3032. t.join();
  3033. });
  3034. svr.wait_until_ready();
  3035. Client cli(HOST, port);
  3036. cli.set_digest_auth("hello", "world");
  3037. auto res = cli.Get("/x");
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3040. }
  3041. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3042. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3049. }
  3050. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3051. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3052. // when storing the values, so the header builder has to re-escape them (and
  3053. // keep algorithm a bare token); otherwise the value breaks out of its
  3054. // quoted-string and injects extra auth-params into the client's Authorization.
  3055. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3056. std::atomic<int> hits{0};
  3057. std::string authorization;
  3058. Server svr;
  3059. svr.Get("/x", [&](const Request &req, Response &res) {
  3060. if (++hits == 1) {
  3061. res.status = StatusCode::Unauthorized_401;
  3062. // On the wire the quotes embedded in the values are backslash-escaped.
  3063. res.set_header("WWW-Authenticate",
  3064. "Digest realm=\"testrealm\", "
  3065. "nonce=\"n\\\"; injected=\\\"x\", "
  3066. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3067. } else {
  3068. authorization = req.get_header_value("Authorization");
  3069. res.set_content("ok", "text/plain");
  3070. }
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. std::thread t([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. t.join();
  3077. });
  3078. svr.wait_until_ready();
  3079. Client cli(HOST, port);
  3080. cli.set_digest_auth("hello", "world");
  3081. auto res = cli.Get("/x");
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(2, hits.load());
  3084. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3085. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3086. // inside its quoted-string rather than starting an "injected" auth-param.
  3087. EXPECT_NE(std::string::npos,
  3088. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3089. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3090. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3091. }
  3092. #endif
  3093. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3094. auto host = "google.com";
  3095. auto another_host = "example.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3108. auto host = "google.com";
  3109. auto wrong_ip = "0.0.0.0";
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(host);
  3112. #else
  3113. Client cli(host);
  3114. #endif
  3115. cli.set_hostname_addr_map({{host, wrong_ip}});
  3116. auto res = cli.Get("/");
  3117. ASSERT_TRUE(!res);
  3118. EXPECT_EQ(Error::Connection, res.error());
  3119. }
  3120. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3121. // A mapped value that is not an IP literal must be resolved. "localhost"
  3122. // resolves from the hosts file, so this test needs no external DNS.
  3123. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3124. auto host = "target.invalid";
  3125. Server svr;
  3126. std::string received_host;
  3127. svr.Get("/hi", [&](const Request &req, Response &res) {
  3128. received_host = req.get_header_value("Host");
  3129. res.set_content("Hello World!", "text/plain");
  3130. });
  3131. auto port = svr.bind_to_any_port(HOST);
  3132. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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. Client cli(host, port);
  3140. cli.set_hostname_addr_map({{host, HOST}});
  3141. auto res = cli.Get("/hi");
  3142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3143. EXPECT_EQ(StatusCode::OK_200, res->status);
  3144. // The mapping only redirects the connection; the identity stays host_.
  3145. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3146. }
  3147. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3148. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3149. auto host = "target.invalid";
  3150. Server svr;
  3151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port("127.0.0.1");
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. }
  3168. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3169. // An empty mapped value must leave host_ as the connection target. Without
  3170. // that guard the empty value would become the host argument, getaddrinfo
  3171. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3172. // loopback - silently connecting somewhere the caller never asked for.
  3173. // The server listens on loopback, so such a fallback would succeed and is
  3174. // therefore observable as a failure of this test.
  3175. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3176. Server svr;
  3177. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3178. res.set_content("Hello World!", "text/plain");
  3179. });
  3180. auto port = svr.bind_to_any_port(HOST);
  3181. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3182. auto se = detail::scope_exit([&] {
  3183. svr.stop();
  3184. thread.join();
  3185. ASSERT_FALSE(svr.is_running());
  3186. });
  3187. svr.wait_until_ready();
  3188. Client cli(blackhole, port);
  3189. cli.set_hostname_addr_map({{blackhole, ""}});
  3190. cli.set_connection_timeout(1);
  3191. auto res = cli.Get("/hi");
  3192. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3193. }
  3194. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/absolute-redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(RelativeRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/relative-redirect/3"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::OK_200, res->status);
  3232. }
  3233. TEST(TooManyRedirectTest, Redirect_Online) {
  3234. auto host = "httpbingo.org";
  3235. auto path = std::string{"/redirect/21"};
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. SSLClient cli(host);
  3238. #else
  3239. Client cli(host);
  3240. #endif
  3241. cli.set_follow_location(true);
  3242. auto res = cli.Get(path);
  3243. ASSERT_TRUE(!res);
  3244. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3245. }
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. TEST(YahooRedirectTest, Redirect_Online) {
  3248. Client cli("yahoo.com");
  3249. auto res = cli.Get("/");
  3250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3252. cli.set_follow_location(true);
  3253. res = cli.Get("/");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3257. }
  3258. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3259. #define REDIR_HOST "httpbingo.org"
  3260. #define REDIR_PATH "/redirect-to"
  3261. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3262. SSLClient cli(REDIR_HOST);
  3263. cli.set_follow_location(true);
  3264. auto res =
  3265. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. }
  3269. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3270. SSLClient cli(REDIR_HOST);
  3271. cli.set_follow_location(true);
  3272. Params params;
  3273. params.emplace("url", "http://example.com");
  3274. params.emplace("status_code", "302");
  3275. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. }
  3288. TEST(UrlWithSpace, Redirect_Online) {
  3289. SSLClient cli("edge.forgecdn.net");
  3290. cli.set_follow_location(true);
  3291. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3295. }
  3296. #endif
  3297. #if !defined(_WIN32) && !defined(_WIN64)
  3298. TEST(ReceiveSignals, Signal) {
  3299. auto setupSignalHandlers = []() {
  3300. struct sigaction act;
  3301. sigemptyset(&act.sa_mask);
  3302. act.sa_flags = SA_SIGINFO;
  3303. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3304. switch (sig) {
  3305. case SIGINT:
  3306. default: break;
  3307. }
  3308. };
  3309. ::sigaction(SIGINT, &act, nullptr);
  3310. };
  3311. Server svr;
  3312. int port = 0;
  3313. auto thread = std::thread([&]() {
  3314. setupSignalHandlers();
  3315. port = svr.bind_to_any_port(HOST);
  3316. svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. svr.stop();
  3320. thread.join();
  3321. ASSERT_FALSE(svr.is_running());
  3322. });
  3323. svr.wait_until_ready();
  3324. ASSERT_TRUE(svr.is_running());
  3325. pthread_kill(thread.native_handle(), SIGINT);
  3326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3327. ASSERT_TRUE(svr.is_running());
  3328. }
  3329. #endif
  3330. TEST(RedirectToDifferentPort, Redirect) {
  3331. Server svr1;
  3332. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3333. res.set_content("Hello World!", "text/plain");
  3334. });
  3335. int svr1_port = 0;
  3336. auto thread1 = std::thread([&]() {
  3337. svr1_port = svr1.bind_to_any_port(HOST);
  3338. svr1.listen_after_bind();
  3339. });
  3340. Server svr2;
  3341. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3342. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3343. });
  3344. int svr2_port = 0;
  3345. auto thread2 = std::thread([&]() {
  3346. svr2_port = svr2.bind_to_any_port(HOST);
  3347. svr2.listen_after_bind();
  3348. });
  3349. auto se = detail::scope_exit([&] {
  3350. svr2.stop();
  3351. thread2.join();
  3352. svr1.stop();
  3353. thread1.join();
  3354. ASSERT_FALSE(svr2.is_running());
  3355. ASSERT_FALSE(svr1.is_running());
  3356. });
  3357. svr1.wait_until_ready();
  3358. svr2.wait_until_ready();
  3359. Client cli("localhost", svr2_port);
  3360. cli.set_follow_location(true);
  3361. auto res = cli.Get("/2");
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("Hello World!", res->body);
  3365. }
  3366. // GET /redir on one server redirects to /target on another port, so the
  3367. // client follows it with a new client.
  3368. static Result
  3369. GetThroughRedirectToDifferentPort(Server::Handler target,
  3370. const std::function<void(Client &)> &setup,
  3371. const Headers &headers = Headers()) {
  3372. Server target_svr;
  3373. target_svr.Get("/target", target);
  3374. int target_port = 0;
  3375. auto target_thread = std::thread([&]() {
  3376. target_port = target_svr.bind_to_any_port(HOST);
  3377. target_svr.listen_after_bind();
  3378. });
  3379. Server origin_svr;
  3380. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3381. res.set_redirect(
  3382. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3383. });
  3384. int origin_port = 0;
  3385. auto origin_thread = std::thread([&]() {
  3386. origin_port = origin_svr.bind_to_any_port(HOST);
  3387. origin_svr.listen_after_bind();
  3388. });
  3389. auto se = detail::scope_exit([&] {
  3390. origin_svr.stop();
  3391. origin_thread.join();
  3392. target_svr.stop();
  3393. target_thread.join();
  3394. });
  3395. target_svr.wait_until_ready();
  3396. origin_svr.wait_until_ready();
  3397. Client cli("localhost", origin_port);
  3398. cli.set_follow_location(true);
  3399. setup(cli);
  3400. return cli.Get("/redir", headers);
  3401. }
  3402. static void
  3403. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3404. std::string captured_authorization;
  3405. auto result = GetThroughRedirectToDifferentPort(
  3406. [&](const Request &req, Response &res) {
  3407. captured_authorization = req.get_header_value("Authorization");
  3408. res.set_content("OK", "text/plain");
  3409. },
  3410. set_auth);
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3414. EXPECT_TRUE(captured_authorization.empty());
  3415. }
  3416. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3417. TestDoNotForwardCredentialsOnRedirect(
  3418. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3419. }
  3420. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3421. TestDoNotForwardCredentialsOnRedirect(
  3422. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3423. }
  3424. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3425. std::string captured_cookie;
  3426. auto result = GetThroughRedirectToDifferentPort(
  3427. [&](const Request &req, Response &res) {
  3428. captured_cookie = req.get_header_value("Cookie");
  3429. res.set_content("OK", "text/plain");
  3430. },
  3431. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3432. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3433. EXPECT_EQ(StatusCode::OK_200, result->status);
  3434. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3435. EXPECT_TRUE(captured_cookie.empty());
  3436. }
  3437. TEST(RedirectToSamePort, ForwardCookie) {
  3438. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3439. // header so that ordinary session flows keep working.
  3440. Server svr;
  3441. std::string captured_cookie;
  3442. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3443. res.set_redirect("/target", 302);
  3444. });
  3445. svr.Get("/target", [&](const Request &req, Response &res) {
  3446. captured_cookie = req.get_header_value("Cookie");
  3447. res.set_content("OK", "text/plain");
  3448. });
  3449. auto port = svr.bind_to_any_port(HOST);
  3450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. Client cli(HOST, port);
  3458. cli.set_follow_location(true);
  3459. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3460. auto res = cli.Get("/redir", headers);
  3461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3462. EXPECT_EQ(StatusCode::OK_200, res->status);
  3463. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3464. }
  3465. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3466. std::string authorization;
  3467. std::string trace_id;
  3468. auto result = GetThroughRedirectToDifferentPort(
  3469. [&](const Request &req, Response &res) {
  3470. authorization = req.get_header_value("Authorization");
  3471. trace_id = req.get_header_value("X-Trace-Id");
  3472. res.set_content("OK", "text/plain");
  3473. },
  3474. [](Client &cli) {
  3475. cli.set_default_headers(
  3476. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3477. });
  3478. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3479. EXPECT_EQ(StatusCode::OK_200, result->status);
  3480. // Like a header given with the request, a default one goes along unless it
  3481. // carries credentials (RFC 9110 15.4).
  3482. EXPECT_TRUE(authorization.empty());
  3483. EXPECT_EQ("42", trace_id);
  3484. }
  3485. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3486. auto result = GetThroughRedirectToDifferentPort(
  3487. [](const Request &, Response &res) {
  3488. res.set_content(std::string(2048, 'x'), "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_payload_max_length(1024); });
  3491. EXPECT_FALSE(result);
  3492. }
  3493. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3494. auto result = GetThroughRedirectToDifferentPort(
  3495. [](const Request &req, Response &res) {
  3496. // Answer after a second, or once the client gives up.
  3497. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3498. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3499. }
  3500. res.set_content("late", "text/plain");
  3501. },
  3502. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3503. ASSERT_FALSE(result);
  3504. EXPECT_EQ(Error::Read, result.error());
  3505. }
  3506. #ifdef CPPHTTPLIB_SSL_ENABLED
  3507. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3508. auto result = GetThroughRedirectToDifferentPort(
  3509. [](const Request &, Response &res) {
  3510. res.status = StatusCode::Unauthorized_401;
  3511. res.set_header("WWW-Authenticate",
  3512. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3513. },
  3514. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3515. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3516. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3517. }
  3518. #endif
  3519. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3520. Server svr;
  3521. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3522. // Port number that overflows int — should not crash
  3523. res.set_redirect("http://localhost:99999999999999999999/target");
  3524. });
  3525. auto port = svr.bind_to_any_port(HOST);
  3526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3527. auto se = detail::scope_exit([&] {
  3528. svr.stop();
  3529. thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. });
  3532. svr.wait_until_ready();
  3533. Client cli(HOST, port);
  3534. cli.set_follow_location(true);
  3535. auto res = cli.Get("/redir");
  3536. // Should fail gracefully, not crash (no valid response due to bad port)
  3537. EXPECT_FALSE(res);
  3538. }
  3539. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3540. Server svr;
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3543. // The server's own port followed by junk must not be followed
  3544. res.set_redirect("http://" + std::string(HOST) + ":" +
  3545. std::to_string(port) + "junk/target");
  3546. });
  3547. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3548. res.set_content("target", "text/plain");
  3549. });
  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. Client cli(HOST, port);
  3558. cli.set_follow_location(true);
  3559. auto res = cli.Get("/redir");
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectFromPageWithContent, Redirect) {
  3563. Server svr;
  3564. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("___", "text/plain");
  3566. res.set_redirect("/2");
  3567. });
  3568. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!", "text/plain");
  3570. });
  3571. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3572. auto se = detail::scope_exit([&] {
  3573. svr.stop();
  3574. th.join();
  3575. ASSERT_FALSE(svr.is_running());
  3576. });
  3577. svr.wait_until_ready();
  3578. {
  3579. Client cli("localhost", PORT);
  3580. cli.set_follow_location(true);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. EXPECT_EQ("Hello World!", body);
  3589. }
  3590. {
  3591. Client cli("localhost", PORT);
  3592. std::string body;
  3593. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3594. body.append(data, data_length);
  3595. return true;
  3596. });
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(StatusCode::Found_302, res->status);
  3599. EXPECT_EQ("___", body);
  3600. }
  3601. }
  3602. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3603. Server svr;
  3604. auto port_str = std::to_string(PORT);
  3605. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3606. auto expected_host = "[::1]:" + port_str;
  3607. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3608. res.set_content("___", "text/plain");
  3609. // res.set_redirect("/2");
  3610. res.set_redirect(redirect_url);
  3611. });
  3612. svr.Get("/2", [&](const Request &req, Response &res) {
  3613. auto host_header = req.headers.find("Host");
  3614. ASSERT_TRUE(host_header != req.headers.end());
  3615. EXPECT_EQ(expected_host, host_header->second);
  3616. res.set_content("Hello World!", "text/plain");
  3617. });
  3618. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. th.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3625. // actually starts anything, so the condition !svr.is_running() will
  3626. // always remain true, and the loop never stops.
  3627. // This basically counts how many milliseconds have passed since the
  3628. // call to svr.listen(), and if after 5 seconds nothing started yet
  3629. // aborts the test.
  3630. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3631. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3632. ASSERT_LT(milliseconds, 5000U);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. cli.set_follow_location(true);
  3637. std::string body;
  3638. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3639. body.append(data, data_length);
  3640. return true;
  3641. });
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. EXPECT_EQ("Hello World!", body);
  3645. }
  3646. {
  3647. Client cli("::1", PORT);
  3648. std::string body;
  3649. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3650. body.append(data, data_length);
  3651. return true;
  3652. });
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::Found_302, res->status);
  3655. EXPECT_EQ("___", body);
  3656. }
  3657. }
  3658. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3659. Server svr;
  3660. svr.Get("/foo", [](const Request &req, Response &res) {
  3661. auto a = req.params.find("a");
  3662. if (a != req.params.end()) {
  3663. res.set_content((*a).second, "text/plain");
  3664. res.status = StatusCode::OK_200;
  3665. } else {
  3666. res.status = StatusCode::BadRequest_400;
  3667. }
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. {
  3677. Client cli(HOST, PORT);
  3678. cli.set_path_encode(false);
  3679. auto res = cli.Get("/foo?a=explicitly+encoded");
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. // This expects it back with a space, as the `+` won't have been
  3683. // url-encoded, and server-side the params get decoded turning `+`
  3684. // into spaces.
  3685. EXPECT_EQ("explicitly encoded", res->body);
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3689. // When path encoding is disabled the client must transmit the supplied
  3690. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3691. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3692. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3693. // than a space (0x20). Assert on the raw wire target to catch this.
  3694. Server svr;
  3695. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3696. svr.Get("/foo", [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(expected_target, req.target);
  3698. res.status = StatusCode::OK_200;
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. cli.set_path_encode(false);
  3710. auto res = cli.Get(expected_target.c_str());
  3711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3712. EXPECT_EQ(StatusCode::OK_200, res->status);
  3713. }
  3714. }
  3715. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3716. // `open_stream()` used to skip the path encoding that the buffered send
  3717. // path applies, so the same `path` produced different bytes in the request
  3718. // line depending on which API was used. Assert the two agree.
  3719. Server svr;
  3720. std::string target;
  3721. svr.Get(".*", [&](const Request &req, Response &res) {
  3722. target = req.target;
  3723. res.status = StatusCode::OK_200;
  3724. });
  3725. auto port = svr.bind_to_any_port(HOST);
  3726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3727. auto se = detail::scope_exit([&] {
  3728. svr.stop();
  3729. thread.join();
  3730. ASSERT_FALSE(svr.is_running());
  3731. });
  3732. svr.wait_until_ready();
  3733. struct {
  3734. const char *path;
  3735. const char *expected;
  3736. } cases[] = {
  3737. {"/a b?x=1", "/a%20b?x=1"},
  3738. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3739. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3740. };
  3741. for (const auto &c : cases) {
  3742. Client cli(HOST, port);
  3743. target.clear();
  3744. auto res = cli.Get(c.path);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3747. auto buffered_target = target;
  3748. target.clear();
  3749. auto handle = cli.open_stream("GET", c.path);
  3750. EXPECT_TRUE(handle.is_valid())
  3751. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3752. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3753. }
  3754. }
  3755. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3756. // The `set_path_encode(false)` contract — transmit the supplied target
  3757. // verbatim — must hold for the streaming API too.
  3758. Server svr;
  3759. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3760. std::string target;
  3761. svr.Get("/foo", [&](const Request &req, Response &res) {
  3762. target = req.target;
  3763. res.status = StatusCode::OK_200;
  3764. });
  3765. auto port = svr.bind_to_any_port(HOST);
  3766. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3767. auto se = detail::scope_exit([&] {
  3768. svr.stop();
  3769. thread.join();
  3770. ASSERT_FALSE(svr.is_running());
  3771. });
  3772. svr.wait_until_ready();
  3773. {
  3774. Client cli(HOST, port);
  3775. cli.set_path_encode(false);
  3776. auto handle = cli.open_stream("GET", expected_target);
  3777. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3778. EXPECT_EQ(expected_target, target);
  3779. }
  3780. }
  3781. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3782. // With path encoding enabled a CR/LF in the target is percent-encoded
  3783. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3784. // write_request_line still backstops `set_path_encode(false)`, which is
  3785. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3786. Server svr;
  3787. // Captured before routing: the decoded path contains a newline, which a
  3788. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3789. std::string target;
  3790. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3791. target = req.target;
  3792. res.status = StatusCode::OK_200;
  3793. return Server::HandlerResponse::Handled;
  3794. });
  3795. auto port = svr.bind_to_any_port(HOST);
  3796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3797. auto se = detail::scope_exit([&] {
  3798. svr.stop();
  3799. thread.join();
  3800. ASSERT_FALSE(svr.is_running());
  3801. });
  3802. svr.wait_until_ready();
  3803. {
  3804. Client cli(HOST, port);
  3805. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3806. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3807. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3808. }
  3809. }
  3810. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3811. // Every control character is percent-encoded, not just CR/LF, so the target
  3812. // passes the request-target check in write_request_line.
  3813. Server svr;
  3814. std::string target;
  3815. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3816. target = req.target;
  3817. res.status = StatusCode::OK_200;
  3818. return Server::HandlerResponse::Handled;
  3819. });
  3820. auto port = svr.bind_to_any_port(HOST);
  3821. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3822. auto se = detail::scope_exit([&] {
  3823. svr.stop();
  3824. thread.join();
  3825. ASSERT_FALSE(svr.is_running());
  3826. });
  3827. svr.wait_until_ready();
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/a\tb\x1b\x7f");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ("/a%09b%1B%7F", target);
  3833. }
  3834. }
  3835. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3836. // Nothing may reach the wire: a raw CR/LF target would split the request
  3837. // line and inject headers.
  3838. Server svr;
  3839. // Pre-routing so that "not called" means nothing reached the server at all,
  3840. // rather than merely failing to match a handler pattern.
  3841. auto handler_called = false;
  3842. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3843. handler_called = true;
  3844. res.status = StatusCode::OK_200;
  3845. return Server::HandlerResponse::Handled;
  3846. });
  3847. auto port = svr.bind_to_any_port(HOST);
  3848. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3849. auto se = detail::scope_exit([&] {
  3850. svr.stop();
  3851. thread.join();
  3852. ASSERT_FALSE(svr.is_running());
  3853. });
  3854. svr.wait_until_ready();
  3855. {
  3856. Client cli(HOST, port);
  3857. cli.set_path_encode(false);
  3858. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3859. EXPECT_FALSE(handle.is_valid());
  3860. EXPECT_EQ(Error::Write, handle.error);
  3861. EXPECT_FALSE(handler_called);
  3862. }
  3863. }
  3864. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3865. // Which of the two branches runs is decided by whether the query component
  3866. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3867. // an empty query and must still fall back to building one from
  3868. // `req.params`, while a non-empty query must win over `req.params`.
  3869. Server svr;
  3870. std::string target;
  3871. svr.Get("/foo", [&](const Request &req, Response &res) {
  3872. target = req.target;
  3873. res.status = StatusCode::OK_200;
  3874. });
  3875. auto port = svr.bind_to_any_port(HOST);
  3876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3877. auto se = detail::scope_exit([&] {
  3878. svr.stop();
  3879. thread.join();
  3880. ASSERT_FALSE(svr.is_running());
  3881. });
  3882. svr.wait_until_ready();
  3883. {
  3884. // Trailing `?` -> empty query component -> `req.params` is used.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?a=1", target);
  3894. }
  3895. {
  3896. // Non-empty query in `req.path` -> `req.params` is not appended.
  3897. Client cli(HOST, port);
  3898. Request req;
  3899. req.method = "GET";
  3900. req.path = "/foo?b=2";
  3901. req.params.emplace("a", "1");
  3902. target.clear();
  3903. auto res = cli.send(req);
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ("/foo?b=2", target);
  3906. }
  3907. }
  3908. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3909. Server svr;
  3910. svr.Get("/", [](const Request &req, Response &) {
  3911. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3912. });
  3913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3914. auto se = detail::scope_exit([&] {
  3915. svr.stop();
  3916. thread.join();
  3917. ASSERT_FALSE(svr.is_running());
  3918. });
  3919. svr.wait_until_ready();
  3920. {
  3921. Client cli(HOST, PORT);
  3922. cli.set_path_encode(false);
  3923. auto res = cli.Get("/?something=%0A");
  3924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3925. EXPECT_EQ(StatusCode::OK_200, res->status);
  3926. }
  3927. }
  3928. TEST(BindServerTest, BindDualStack) {
  3929. Server svr;
  3930. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3931. res.set_content("Hello World!", "text/plain");
  3932. });
  3933. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3934. auto se = detail::scope_exit([&] {
  3935. svr.stop();
  3936. thread.join();
  3937. ASSERT_FALSE(svr.is_running());
  3938. });
  3939. svr.wait_until_ready();
  3940. {
  3941. Client cli("127.0.0.1", PORT);
  3942. auto res = cli.Get("/1");
  3943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3944. EXPECT_EQ(StatusCode::OK_200, res->status);
  3945. EXPECT_EQ("Hello World!", res->body);
  3946. }
  3947. {
  3948. Client cli("::1", PORT);
  3949. auto res = cli.Get("/1");
  3950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ("Hello World!", res->body);
  3953. }
  3954. }
  3955. TEST(BindServerTest, BindAndListenSeparately) {
  3956. Server svr;
  3957. int port = svr.bind_to_any_port("0.0.0.0");
  3958. ASSERT_TRUE(svr.is_valid());
  3959. ASSERT_TRUE(port > 0);
  3960. svr.stop();
  3961. }
  3962. // Reports whether anything is still listening on a loopback port. A plain
  3963. // connect() is used instead of a Client request because a socket left bound by
  3964. // mistake accepts the connection into its backlog and never answers, which
  3965. // would hang the test instead of failing it.
  3966. static bool is_loopback_port_accepting(int port) {
  3967. sockaddr_in addr{};
  3968. addr.sin_family = AF_INET;
  3969. addr.sin_port = htons(static_cast<uint16_t>(port));
  3970. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3971. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3972. EXPECT_NE(sock, INVALID_SOCKET);
  3973. if (sock == INVALID_SOCKET) { return false; }
  3974. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3975. static_cast<socklen_t>(sizeof(addr)));
  3976. detail::close_socket(sock);
  3977. return ret == 0;
  3978. }
  3979. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3980. Server svr;
  3981. auto port = svr.bind_to_any_port("127.0.0.1");
  3982. ASSERT_TRUE(port > 0);
  3983. svr.stop();
  3984. // bind_to_any_port() already called listen(2), so until stop() closed the
  3985. // descriptor the port kept accepting connections into the backlog. ASSERT
  3986. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3987. // below blocks forever in the accept loop.
  3988. ASSERT_FALSE(is_loopback_port_accepting(port));
  3989. // Nothing is left to accept on, so listen_after_bind() must report failure
  3990. // instead of returning success without ever serving.
  3991. EXPECT_FALSE(svr.listen_after_bind());
  3992. // The failed listen marks the server decommissioned, so a waiter returns
  3993. // instead of spinning forever.
  3994. svr.wait_until_ready();
  3995. }
  3996. #ifdef CPPHTTPLIB_SSL_ENABLED
  3997. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3999. CLIENT_CA_CERT_DIR);
  4000. int port = svr.bind_to_any_port("0.0.0.0");
  4001. ASSERT_TRUE(svr.is_valid());
  4002. ASSERT_TRUE(port > 0);
  4003. svr.stop();
  4004. }
  4005. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4006. // or a rejected CustomRoute() registration would not stop the server binding.
  4007. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. ASSERT_TRUE(svr.is_valid());
  4011. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4012. EXPECT_FALSE(svr.is_valid());
  4013. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4014. }
  4015. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4016. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4017. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4018. int port = svr.bind_to_any_port("0.0.0.0");
  4019. ASSERT_TRUE(svr.is_valid());
  4020. ASSERT_TRUE(port > 0);
  4021. svr.stop();
  4022. }
  4023. TEST(BindServerTest, UpdateCertsPem) {
  4024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4025. int port = svr.bind_to_any_port("0.0.0.0");
  4026. ASSERT_TRUE(svr.is_valid());
  4027. ASSERT_TRUE(port > 0);
  4028. // Read PEM files
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4033. // Update server certificates using PEM API
  4034. ASSERT_TRUE(
  4035. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4036. ASSERT_TRUE(svr.is_valid());
  4037. svr.stop();
  4038. }
  4039. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4040. // Start server with client CA (enables client auth)
  4041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4042. ASSERT_TRUE(svr.is_valid());
  4043. bool handler_called = false;
  4044. svr.Get("/test", [&](const Request &req, Response &res) {
  4045. handler_called = true;
  4046. // Verify client certificate is present
  4047. auto cert = req.peer_cert();
  4048. EXPECT_TRUE(static_cast<bool>(cert));
  4049. res.set_content("ok", "text/plain");
  4050. });
  4051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. t.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. // Read PEM files
  4059. std::string cert_pem, key_pem, ca_pem;
  4060. read_file(SERVER_CERT_FILE, cert_pem);
  4061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4063. // Update server certificates and client CA using PEM API while server running
  4064. ASSERT_TRUE(
  4065. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4066. // Connect with client certificate
  4067. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4068. cli.enable_server_certificate_verification(false);
  4069. cli.set_connection_timeout(30);
  4070. auto res = cli.Get("/test");
  4071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_TRUE(handler_called);
  4074. EXPECT_EQ("ok", res->body);
  4075. }
  4076. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4078. ASSERT_TRUE(svr.is_valid());
  4079. svr.Get("/test", [](const Request &, Response &res) {
  4080. res.set_content("ok", "text/plain");
  4081. });
  4082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4083. auto se = detail::scope_exit([&] {
  4084. svr.stop();
  4085. t.join();
  4086. ASSERT_FALSE(svr.is_running());
  4087. });
  4088. svr.wait_until_ready();
  4089. auto get = [] {
  4090. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4091. cli.enable_server_certificate_verification(false);
  4092. return cli.Get("/test");
  4093. };
  4094. ASSERT_TRUE(get());
  4095. // A CA that did not sign the client's certificate takes the old one's place.
  4096. std::string cert_pem, key_pem, ca_pem;
  4097. read_file(SERVER_CERT_FILE, cert_pem);
  4098. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4099. read_file(SERVER_CERT2_FILE, ca_pem);
  4100. ASSERT_TRUE(
  4101. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4102. EXPECT_FALSE(get());
  4103. }
  4104. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4106. ASSERT_TRUE(svr.is_valid());
  4107. svr.Get("/test", [](const Request &, Response &res) {
  4108. res.set_content("ok", "text/plain");
  4109. });
  4110. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. t.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. // A connection that sends no ClientHello keeps its handshake in progress,
  4118. // once the server has had a moment to start it.
  4119. auto error = Error::Success;
  4120. auto sock = detail::create_client_socket(
  4121. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4122. /*connection_timeout_sec=*/5, 0,
  4123. /*read_timeout_sec=*/5, 0,
  4124. /*write_timeout_sec=*/5, 0, std::string(), error);
  4125. ASSERT_NE(INVALID_SOCKET, sock);
  4126. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4127. std::string cert_pem, key_pem;
  4128. read_file(SERVER_CERT_FILE, cert_pem);
  4129. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4130. auto update = std::async(std::launch::async, [&]() {
  4131. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4132. });
  4133. EXPECT_EQ(std::future_status::timeout,
  4134. update.wait_for(std::chrono::milliseconds(200)));
  4135. detail::close_socket(sock);
  4136. EXPECT_TRUE(update.get());
  4137. SSLClient cli(HOST, PORT);
  4138. cli.enable_server_certificate_verification(false);
  4139. auto res = cli.Get("/test");
  4140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. }
  4143. #endif
  4144. TEST(ErrorHandlerTest, ContentLength) {
  4145. Server svr;
  4146. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4147. res.status = StatusCode::OK_200;
  4148. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4149. "text/html"); // <= Content-Length still 13
  4150. });
  4151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4152. res.set_content("Hello World!\n", "text/plain");
  4153. res.status = 524;
  4154. });
  4155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4156. auto se = detail::scope_exit([&] {
  4157. svr.stop();
  4158. thread.join();
  4159. ASSERT_FALSE(svr.is_running());
  4160. });
  4161. svr.wait_until_ready();
  4162. {
  4163. Client cli(HOST, PORT);
  4164. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::OK_200, res->status);
  4167. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4168. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4169. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4170. }
  4171. }
  4172. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4173. TEST(ExceptionTest, WithoutExceptionHandler) {
  4174. Server svr;
  4175. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4176. throw std::runtime_error("exception...");
  4177. });
  4178. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4179. throw std::runtime_error("exception\r\n...");
  4180. });
  4181. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4182. auto se = detail::scope_exit([&] {
  4183. svr.stop();
  4184. listen_thread.join();
  4185. ASSERT_FALSE(svr.is_running());
  4186. });
  4187. svr.wait_until_ready();
  4188. Client cli("localhost", PORT);
  4189. {
  4190. auto res = cli.Get("/exception");
  4191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4192. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4193. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4194. }
  4195. {
  4196. auto res = cli.Get("/unknown");
  4197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4198. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4199. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4200. }
  4201. }
  4202. TEST(ExceptionTest, WithExceptionHandler) {
  4203. Server svr;
  4204. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4205. std::exception_ptr ep) {
  4206. EXPECT_FALSE(ep == nullptr);
  4207. try {
  4208. std::rethrow_exception(ep);
  4209. } catch (std::exception &e) {
  4210. EXPECT_EQ("abc", std::string(e.what()));
  4211. } catch (...) {}
  4212. res.status = StatusCode::InternalServerError_500;
  4213. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4214. "text/html"); // <= Content-Length still 13 at this point
  4215. });
  4216. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4217. res.set_content("Hello World!\n", "text/plain");
  4218. throw std::runtime_error("abc");
  4219. });
  4220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4221. auto se = detail::scope_exit([&] {
  4222. svr.stop();
  4223. thread.join();
  4224. ASSERT_FALSE(svr.is_running());
  4225. });
  4226. svr.wait_until_ready();
  4227. for (size_t i = 0; i < 10; i++) {
  4228. Client cli(HOST, PORT);
  4229. for (size_t j = 0; j < 100; j++) {
  4230. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4232. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4233. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4234. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4236. }
  4237. cli.set_keep_alive(true);
  4238. for (size_t j = 0; j < 100; j++) {
  4239. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4241. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4242. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4243. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4245. }
  4246. }
  4247. }
  4248. TEST(ExceptionTest, AndErrorHandler) {
  4249. Server svr;
  4250. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4251. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4252. });
  4253. svr.set_exception_handler(
  4254. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4255. EXPECT_FALSE(ep == nullptr);
  4256. try {
  4257. std::rethrow_exception(ep);
  4258. } catch (std::exception &e) {
  4259. res.set_content(e.what(), "text/html");
  4260. } catch (...) {}
  4261. res.status = StatusCode::InternalServerError_500;
  4262. });
  4263. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4264. throw std::runtime_error("EXCEPTION");
  4265. });
  4266. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4267. res.set_content("ERROR", "text/html");
  4268. res.status = StatusCode::InternalServerError_500;
  4269. });
  4270. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4271. auto se = detail::scope_exit([&] {
  4272. svr.stop();
  4273. thread.join();
  4274. ASSERT_FALSE(svr.is_running());
  4275. });
  4276. svr.wait_until_ready();
  4277. Client cli(HOST, PORT);
  4278. {
  4279. auto res = cli.Get("/exception");
  4280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4281. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4282. EXPECT_EQ("EXCEPTION", res->body);
  4283. }
  4284. {
  4285. auto res = cli.Get("/error");
  4286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4287. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4288. EXPECT_EQ("ERROR", res->body);
  4289. }
  4290. {
  4291. auto res = cli.Get("/invalid");
  4292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4294. EXPECT_EQ("NOT_FOUND", res->body);
  4295. }
  4296. }
  4297. #endif
  4298. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4299. // process_request() wraps only routing() in a try/catch, so an exception from
  4300. // any other user callback used to unwind into the task queue - which does not
  4301. // catch - and terminate the process. Each test below runs the server on a
  4302. // single worker thread: a guard that catches the exception but still loses the
  4303. // thread would otherwise be hidden by a spare worker serving the follow-up
  4304. // request. Note that a regression here aborts the whole test binary rather
  4305. // than failing one test.
  4306. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4307. Server svr;
  4308. svr.new_task_queue = [] { return new ThreadPool(1); };
  4309. std::atomic<int> reported{0};
  4310. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4311. if (err == Error::UserCallbackException) { reported++; }
  4312. });
  4313. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4314. res.set_content_provider(
  4315. 1024, "text/plain",
  4316. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4317. sink.write("hello", 5);
  4318. throw std::runtime_error("from the content provider");
  4319. });
  4320. });
  4321. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4322. res.set_content("ok", "text/plain");
  4323. });
  4324. auto port = svr.bind_to_any_port(HOST);
  4325. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4326. auto se = detail::scope_exit([&] {
  4327. svr.stop();
  4328. listen_thread.join();
  4329. ASSERT_FALSE(svr.is_running());
  4330. });
  4331. svr.wait_until_ready();
  4332. {
  4333. Client cli(HOST, port);
  4334. cli.set_read_timeout(5, 0);
  4335. EXPECT_FALSE(cli.Get("/throw"));
  4336. }
  4337. EXPECT_TRUE(svr.is_running());
  4338. EXPECT_EQ(1, reported.load());
  4339. // A request on a fresh connection is still served.
  4340. {
  4341. Client cli(HOST, port);
  4342. auto res = cli.Get("/ok");
  4343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. EXPECT_EQ("ok", res->body);
  4346. }
  4347. }
  4348. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4349. Server svr;
  4350. svr.new_task_queue = [] { return new ThreadPool(1); };
  4351. std::atomic<bool> should_throw{true};
  4352. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4353. res.set_content("hi", "text/plain");
  4354. });
  4355. svr.set_post_routing_handler(
  4356. [&](const Request & /*req*/, Response & /*res*/) {
  4357. if (should_throw) {
  4358. throw std::runtime_error("from the post-routing handler");
  4359. }
  4360. });
  4361. auto port = svr.bind_to_any_port(HOST);
  4362. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4363. auto se = detail::scope_exit([&] {
  4364. svr.stop();
  4365. listen_thread.join();
  4366. ASSERT_FALSE(svr.is_running());
  4367. });
  4368. svr.wait_until_ready();
  4369. {
  4370. Client cli(HOST, port);
  4371. cli.set_read_timeout(5, 0);
  4372. EXPECT_FALSE(cli.Get("/hi"));
  4373. }
  4374. EXPECT_TRUE(svr.is_running());
  4375. should_throw = false;
  4376. {
  4377. Client cli(HOST, port);
  4378. auto res = cli.Get("/hi");
  4379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. EXPECT_EQ("hi", res->body);
  4382. }
  4383. }
  4384. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4385. // The guard reports the caught exception through the error logger, which is
  4386. // a user callback too. A logger that throws has to be contained as well, or
  4387. // the process would terminate from inside the catch.
  4388. Server svr;
  4389. svr.new_task_queue = [] { return new ThreadPool(1); };
  4390. std::atomic<int> reported{0};
  4391. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4392. if (err == Error::UserCallbackException) {
  4393. reported++;
  4394. throw std::runtime_error("from the error logger");
  4395. }
  4396. });
  4397. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4398. res.set_content_provider(
  4399. 1024, "text/plain",
  4400. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4401. sink.write("hello", 5);
  4402. throw std::runtime_error("from the content provider");
  4403. });
  4404. });
  4405. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4406. res.set_content("ok", "text/plain");
  4407. });
  4408. auto port = svr.bind_to_any_port(HOST);
  4409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4410. auto se = detail::scope_exit([&] {
  4411. svr.stop();
  4412. listen_thread.join();
  4413. ASSERT_FALSE(svr.is_running());
  4414. });
  4415. svr.wait_until_ready();
  4416. {
  4417. Client cli(HOST, port);
  4418. cli.set_read_timeout(5, 0);
  4419. EXPECT_FALSE(cli.Get("/throw"));
  4420. }
  4421. EXPECT_TRUE(svr.is_running());
  4422. EXPECT_EQ(1, reported.load());
  4423. {
  4424. Client cli(HOST, port);
  4425. auto res = cli.Get("/ok");
  4426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4427. EXPECT_EQ(StatusCode::OK_200, res->status);
  4428. EXPECT_EQ("ok", res->body);
  4429. }
  4430. }
  4431. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4432. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4433. // so the exception unwinds through the ws::WebSocket object on its way to
  4434. // the guard. None of the HTTP cases above cross that.
  4435. Server svr;
  4436. svr.new_task_queue = [] { return new ThreadPool(1); };
  4437. std::atomic<int> reported{0};
  4438. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4439. if (err == Error::UserCallbackException) { reported++; }
  4440. });
  4441. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4442. throw std::runtime_error("from the WebSocket handler");
  4443. });
  4444. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4445. res.set_content("ok", "text/plain");
  4446. });
  4447. auto port = svr.bind_to_any_port(HOST);
  4448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4449. auto se = detail::scope_exit([&] {
  4450. svr.stop();
  4451. listen_thread.join();
  4452. ASSERT_FALSE(svr.is_running());
  4453. });
  4454. svr.wait_until_ready();
  4455. {
  4456. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4457. "/ws");
  4458. auto res = client.connect();
  4459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4460. // The server dropped the connection instead of dying.
  4461. std::string msg;
  4462. EXPECT_FALSE(client.read(msg));
  4463. client.close();
  4464. }
  4465. EXPECT_TRUE(svr.is_running());
  4466. EXPECT_EQ(1, reported.load());
  4467. {
  4468. Client cli(HOST, port);
  4469. auto res = cli.Get("/ok");
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. EXPECT_EQ(StatusCode::OK_200, res->status);
  4472. EXPECT_EQ("ok", res->body);
  4473. }
  4474. }
  4475. #ifdef CPPHTTPLIB_SSL_ENABLED
  4476. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4477. // SSLServer::process_and_close_socket() is a separate overload with its own
  4478. // guard, so it is exercised on its own.
  4479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4480. ASSERT_TRUE(svr.is_valid());
  4481. svr.new_task_queue = [] { return new ThreadPool(1); };
  4482. std::atomic<int> reported{0};
  4483. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4484. if (err == Error::UserCallbackException) { reported++; }
  4485. });
  4486. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4487. res.set_content_provider(
  4488. 1024, "text/plain",
  4489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4490. sink.write("hello", 5);
  4491. throw std::runtime_error("from the content provider");
  4492. });
  4493. });
  4494. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4495. res.set_content("ok", "text/plain");
  4496. });
  4497. auto port = svr.bind_to_any_port(HOST);
  4498. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. listen_thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. {
  4506. SSLClient cli(HOST, port);
  4507. cli.enable_server_certificate_verification(false);
  4508. cli.set_read_timeout(5, 0);
  4509. EXPECT_FALSE(cli.Get("/throw"));
  4510. }
  4511. EXPECT_TRUE(svr.is_running());
  4512. EXPECT_EQ(1, reported.load());
  4513. {
  4514. SSLClient cli(HOST, port);
  4515. cli.enable_server_certificate_verification(false);
  4516. auto res = cli.Get("/ok");
  4517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4518. EXPECT_EQ(StatusCode::OK_200, res->status);
  4519. EXPECT_EQ("ok", res->body);
  4520. }
  4521. }
  4522. #endif
  4523. #endif
  4524. TEST(NoContentTest, ContentLength) {
  4525. Server svr;
  4526. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4527. res.status = StatusCode::NoContent_204;
  4528. });
  4529. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4530. auto se = detail::scope_exit([&] {
  4531. svr.stop();
  4532. thread.join();
  4533. ASSERT_FALSE(svr.is_running());
  4534. });
  4535. svr.wait_until_ready();
  4536. {
  4537. Client cli(HOST, PORT);
  4538. auto res = cli.Get("/hi");
  4539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4540. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4541. // RFC 9110 8.6: none in a 204 response
  4542. EXPECT_FALSE(res->has_header("Content-Length"));
  4543. }
  4544. }
  4545. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4546. Server svr;
  4547. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4548. res.set_header("Content-Length", "5");
  4549. res.set_content("hello world", "text/plain");
  4550. });
  4551. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4552. // A body that reads as the last chunk, were it taken as chunked
  4553. res.set_header("Transfer-Encoding", "chunked");
  4554. res.set_content("0\r\n\r\n", "text/plain");
  4555. });
  4556. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4557. res.set_header("Content-Length", "2");
  4558. res.set_content_provider(5, "text/plain",
  4559. [](size_t offset, size_t length, DataSink &sink) {
  4560. sink.write(&"hello"[offset], length);
  4561. return true;
  4562. });
  4563. });
  4564. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4565. res.set_header("Content-Length", "1234");
  4566. });
  4567. thread t = thread([&] { svr.listen(HOST, PORT); });
  4568. auto se = detail::scope_exit([&] {
  4569. svr.stop();
  4570. t.join();
  4571. ASSERT_FALSE(svr.is_running());
  4572. });
  4573. svr.wait_until_ready();
  4574. Client cli(HOST, PORT);
  4575. cli.set_read_timeout(1, 0);
  4576. auto expect_body = [&](const Result &res, const std::string &body) {
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. EXPECT_EQ(body, res->body);
  4579. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4580. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4581. };
  4582. Headers identity{{"Accept-Encoding", ""}};
  4583. expect_body(cli.Get("/body", identity), "hello world");
  4584. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4585. expect_body(cli.Get("/body",
  4586. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4587. "he");
  4588. expect_body(cli.Get("/provider", identity), "hello");
  4589. expect_body(cli.Get("/empty", identity), "");
  4590. // A HEAD response may give the length of the body a GET would get.
  4591. auto res = cli.Head("/empty");
  4592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4593. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4594. }
  4595. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4596. Server svr;
  4597. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4598. res.set_content("short", "text/plain");
  4599. });
  4600. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4601. res.body += " with a footer";
  4602. res.set_header("Transfer-Encoding", "chunked");
  4603. });
  4604. thread t = thread([&] { svr.listen(HOST, PORT); });
  4605. auto se = detail::scope_exit([&] {
  4606. svr.stop();
  4607. t.join();
  4608. ASSERT_FALSE(svr.is_running());
  4609. });
  4610. svr.wait_until_ready();
  4611. Client cli(HOST, PORT);
  4612. cli.set_read_timeout(1, 0);
  4613. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4615. EXPECT_EQ("short with a footer", res->body);
  4616. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4617. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4618. }
  4619. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4620. #ifdef CPPHTTPLIB_SSL_ENABLED
  4621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4622. ASSERT_TRUE(svr.is_valid());
  4623. #else
  4624. Server svr;
  4625. #endif
  4626. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4627. if (req.path == "/routing_handler") {
  4628. res.set_header("PRE_ROUTING", "on");
  4629. res.set_content("Routing Handler", "text/plain");
  4630. return httplib::Server::HandlerResponse::Handled;
  4631. }
  4632. return httplib::Server::HandlerResponse::Unhandled;
  4633. });
  4634. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4635. res.set_content("Error", "text/html");
  4636. });
  4637. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4638. if (req.path == "/routing_handler") {
  4639. res.set_header("POST_ROUTING", "on");
  4640. }
  4641. });
  4642. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4643. res.set_content("Hello World!\n", "text/plain");
  4644. });
  4645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4646. auto se = detail::scope_exit([&] {
  4647. svr.stop();
  4648. thread.join();
  4649. ASSERT_FALSE(svr.is_running());
  4650. });
  4651. svr.wait_until_ready();
  4652. {
  4653. #ifdef CPPHTTPLIB_SSL_ENABLED
  4654. SSLClient cli(HOST, PORT);
  4655. cli.enable_server_certificate_verification(false);
  4656. #else
  4657. Client cli(HOST, PORT);
  4658. #endif
  4659. auto res = cli.Get("/routing_handler");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("Routing Handler", res->body);
  4663. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4664. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4665. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4666. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4667. }
  4668. {
  4669. #ifdef CPPHTTPLIB_SSL_ENABLED
  4670. SSLClient cli(HOST, PORT);
  4671. cli.enable_server_certificate_verification(false);
  4672. #else
  4673. Client cli(HOST, PORT);
  4674. #endif
  4675. auto res = cli.Get("/hi");
  4676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4677. EXPECT_EQ(StatusCode::OK_200, res->status);
  4678. EXPECT_EQ("Hello World!\n", res->body);
  4679. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4680. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4681. }
  4682. {
  4683. #ifdef CPPHTTPLIB_SSL_ENABLED
  4684. SSLClient cli(HOST, PORT);
  4685. cli.enable_server_certificate_verification(false);
  4686. #else
  4687. Client cli(HOST, PORT);
  4688. #endif
  4689. auto res = cli.Get("/aaa");
  4690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4692. EXPECT_EQ("Error", res->body);
  4693. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4694. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4695. }
  4696. }
  4697. TEST(RequestHandlerTest, PreRequestHandler) {
  4698. auto route_path = "/user/:user";
  4699. Server svr;
  4700. svr.Get("/hi", [](const Request &, Response &res) {
  4701. res.set_content("hi", "text/plain");
  4702. });
  4703. svr.Get(route_path, [](const Request &req, Response &res) {
  4704. res.set_content(req.path_params.at("user"), "text/plain");
  4705. });
  4706. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4707. if (req.matched_route == route_path) {
  4708. auto user = req.path_params.at("user");
  4709. if (user != "john") {
  4710. res.status = StatusCode::Forbidden_403;
  4711. res.set_content("error", "text/html");
  4712. return Server::HandlerResponse::Handled;
  4713. }
  4714. }
  4715. return Server::HandlerResponse::Unhandled;
  4716. });
  4717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4718. auto se = detail::scope_exit([&] {
  4719. svr.stop();
  4720. thread.join();
  4721. ASSERT_FALSE(svr.is_running());
  4722. });
  4723. svr.wait_until_ready();
  4724. Client cli(HOST, PORT);
  4725. {
  4726. auto res = cli.Get("/hi");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ("hi", res->body);
  4730. }
  4731. {
  4732. auto res = cli.Get("/user/john");
  4733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4734. EXPECT_EQ(StatusCode::OK_200, res->status);
  4735. EXPECT_EQ("john", res->body);
  4736. }
  4737. {
  4738. auto res = cli.Get("/user/invalid-user");
  4739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4740. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4741. EXPECT_EQ("error", res->body);
  4742. }
  4743. }
  4744. // The pre-request handler must run before the request body is read, so a
  4745. // rejected request never forces the server to buffer a (potentially large)
  4746. // body. Here the posted body is larger than the payload limit: if the body
  4747. // were read first the server would answer 413, but because the pre-request
  4748. // handler runs first it answers 403 and the body is never read.
  4749. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4750. Server svr;
  4751. svr.set_payload_max_length(8);
  4752. auto handler_ran = false;
  4753. svr.Post("/reject", [&](const Request &req, Response &res) {
  4754. handler_ran = true;
  4755. res.set_content(req.body, "text/plain");
  4756. });
  4757. svr.Post("/accept", [](const Request &req, Response &res) {
  4758. res.set_content(req.body, "text/plain");
  4759. });
  4760. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4761. if (req.matched_route == "/reject") {
  4762. res.status = StatusCode::Forbidden_403;
  4763. res.set_content("denied", "text/plain");
  4764. return Server::HandlerResponse::Handled;
  4765. }
  4766. return Server::HandlerResponse::Unhandled;
  4767. });
  4768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. Client cli(HOST, PORT);
  4776. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4777. // rejects with 403 before the body is read, so 413 is never reached.
  4778. {
  4779. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4782. EXPECT_EQ("denied", res->body);
  4783. EXPECT_FALSE(handler_ran);
  4784. }
  4785. // An approved route still reads the body and enforces the payload limit.
  4786. {
  4787. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4789. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4790. }
  4791. }
  4792. TEST(UserDataTest, BasicOperations) {
  4793. httplib::UserData ud;
  4794. // Initially empty
  4795. EXPECT_FALSE(ud.has("key"));
  4796. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4797. // set and get
  4798. ud.set("key", 42);
  4799. EXPECT_TRUE(ud.has("key"));
  4800. auto *p = ud.get<int>("key");
  4801. ASSERT_NE(nullptr, p);
  4802. EXPECT_EQ(42, *p);
  4803. // Type mismatch → nullptr
  4804. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4805. // Overwrite with different type
  4806. ud.set("key", std::string("hello"));
  4807. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4808. auto *s = ud.get<std::string>("key");
  4809. ASSERT_NE(nullptr, s);
  4810. EXPECT_EQ("hello", *s);
  4811. // erase
  4812. ud.erase("key");
  4813. EXPECT_FALSE(ud.has("key"));
  4814. // clear
  4815. ud.set("a", 1);
  4816. ud.set("b", 2);
  4817. ud.clear();
  4818. EXPECT_FALSE(ud.has("a"));
  4819. EXPECT_FALSE(ud.has("b"));
  4820. }
  4821. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4822. struct AuthCtx {
  4823. std::string user_id;
  4824. };
  4825. Server svr;
  4826. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4827. res.user_data.set("auth", AuthCtx{"alice"});
  4828. return Server::HandlerResponse::Unhandled;
  4829. });
  4830. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4831. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4832. ASSERT_NE(nullptr, ctx);
  4833. res.set_content("Hello " + ctx->user_id, "text/plain");
  4834. });
  4835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4836. auto se = detail::scope_exit([&] {
  4837. svr.stop();
  4838. thread.join();
  4839. ASSERT_FALSE(svr.is_running());
  4840. });
  4841. svr.wait_until_ready();
  4842. Client cli(HOST, PORT);
  4843. auto res = cli.Get("/me");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("Hello alice", res->body);
  4847. }
  4848. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4849. struct RoleCtx {
  4850. std::string role;
  4851. };
  4852. Server svr;
  4853. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4854. res.user_data.set("role", RoleCtx{"admin"});
  4855. return Server::HandlerResponse::Unhandled;
  4856. });
  4857. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4858. auto *ctx = res.user_data.get<RoleCtx>("role");
  4859. ASSERT_NE(nullptr, ctx);
  4860. res.set_content(ctx->role, "text/plain");
  4861. });
  4862. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4863. auto se = detail::scope_exit([&] {
  4864. svr.stop();
  4865. thread.join();
  4866. ASSERT_FALSE(svr.is_running());
  4867. });
  4868. svr.wait_until_ready();
  4869. Client cli(HOST, PORT);
  4870. auto res = cli.Get("/role");
  4871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4872. EXPECT_EQ(StatusCode::OK_200, res->status);
  4873. EXPECT_EQ("admin", res->body);
  4874. }
  4875. TEST(InvalidFormatTest, StatusCode) {
  4876. Server svr;
  4877. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4878. res.set_content("Hello World!\n", "text/plain");
  4879. res.status = 9999; // Status should be a three-digit code...
  4880. });
  4881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4882. auto se = detail::scope_exit([&] {
  4883. svr.stop();
  4884. thread.join();
  4885. ASSERT_FALSE(svr.is_running());
  4886. });
  4887. svr.wait_until_ready();
  4888. {
  4889. Client cli(HOST, PORT);
  4890. auto res = cli.Get("/hi");
  4891. ASSERT_FALSE(res);
  4892. }
  4893. }
  4894. TEST(URLFragmentTest, WithFragment) {
  4895. Server svr;
  4896. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4897. EXPECT_TRUE(req.target == "/hi");
  4898. });
  4899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4900. auto se = detail::scope_exit([&] {
  4901. svr.stop();
  4902. thread.join();
  4903. ASSERT_FALSE(svr.is_running());
  4904. });
  4905. svr.wait_until_ready();
  4906. {
  4907. Client cli(HOST, PORT);
  4908. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4909. EXPECT_TRUE(res);
  4910. EXPECT_EQ(StatusCode::OK_200, res->status);
  4911. res = cli.Get("/hi%23key1=val1=key2=val2");
  4912. EXPECT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4914. }
  4915. }
  4916. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  4917. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  4918. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  4919. Server svr;
  4920. std::vector<std::string> targets;
  4921. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  4922. targets.push_back(req.target);
  4923. });
  4924. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4925. auto se = detail::scope_exit([&] {
  4926. svr.stop();
  4927. thread.join();
  4928. ASSERT_FALSE(svr.is_running());
  4929. });
  4930. svr.wait_until_ready();
  4931. Client cli(HOST, PORT);
  4932. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  4933. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  4934. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  4935. // A '?' after the '#' belongs to the fragment, not to the query.
  4936. Request req;
  4937. req.method = "GET";
  4938. req.path = "/hi#f?x=1";
  4939. req.params.emplace("a", "1");
  4940. Response res;
  4941. auto error = Error::Success;
  4942. EXPECT_TRUE(cli.send(req, res, error));
  4943. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  4944. "/hi?a=1"}),
  4945. targets);
  4946. }
  4947. TEST(HeaderWriter, SetHeaderWriter) {
  4948. Server svr;
  4949. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4950. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4951. return detail::write_headers(strm, hdrs);
  4952. });
  4953. svr.Get("/hi", [](const Request &req, Response &res) {
  4954. auto it = req.headers.find("CustomClientHeader");
  4955. EXPECT_TRUE(it != req.headers.end());
  4956. EXPECT_EQ(it->second, "CustomClientValue");
  4957. res.set_content("Hello World!\n", "text/plain");
  4958. });
  4959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4960. auto se = detail::scope_exit([&] {
  4961. svr.stop();
  4962. thread.join();
  4963. ASSERT_FALSE(svr.is_running());
  4964. });
  4965. svr.wait_until_ready();
  4966. {
  4967. Client cli(HOST, PORT);
  4968. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4969. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4970. return detail::write_headers(strm, hdrs);
  4971. });
  4972. auto res = cli.Get("/hi");
  4973. EXPECT_TRUE(res);
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. auto it = res->headers.find("CustomServerHeader");
  4976. EXPECT_TRUE(it != res->headers.end());
  4977. EXPECT_EQ(it->second, "CustomServerValue");
  4978. }
  4979. }
  4980. class ServerTest : public ::testing::Test {
  4981. protected:
  4982. ServerTest()
  4983. : cli_(HOST, PORT)
  4984. #ifdef CPPHTTPLIB_SSL_ENABLED
  4985. ,
  4986. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4987. #endif
  4988. {
  4989. #ifdef CPPHTTPLIB_SSL_ENABLED
  4990. cli_.enable_server_certificate_verification(false);
  4991. #endif
  4992. // Allow LARGE_DATA (100MB) responses
  4993. cli_.set_payload_max_length(200 * 1024 * 1024);
  4994. }
  4995. virtual void SetUp() {
  4996. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4997. svr_.set_payload_max_length(200 * 1024 * 1024);
  4998. svr_.set_mount_point("/", "./www");
  4999. svr_.set_mount_point("/mount", "./www2");
  5000. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5001. svr_.Get("/hi",
  5002. [&](const Request & /*req*/, Response &res) {
  5003. res.set_content("Hello World!", "text/plain");
  5004. })
  5005. .Get("/file_content",
  5006. [&](const Request & /*req*/, Response &res) {
  5007. res.set_file_content("./www/dir/test.html");
  5008. })
  5009. .Get("/file_content_with_content_type",
  5010. [&](const Request & /*req*/, Response &res) {
  5011. res.set_file_content("./www/file", "text/plain");
  5012. })
  5013. .Get("/invalid_file_content",
  5014. [&](const Request & /*req*/, Response &res) {
  5015. res.set_file_content("./www/dir/invalid_file_path");
  5016. })
  5017. .Get("/http_response_splitting",
  5018. [&](const Request & /*req*/, Response &res) {
  5019. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5020. EXPECT_EQ(0U, res.headers.size());
  5021. EXPECT_FALSE(res.has_header("a"));
  5022. res.set_header("a", "1\nSet-Cookie: a=1");
  5023. EXPECT_EQ(0U, res.headers.size());
  5024. EXPECT_FALSE(res.has_header("a"));
  5025. res.set_header("a", "1\rSet-Cookie: a=1");
  5026. EXPECT_EQ(0U, res.headers.size());
  5027. EXPECT_FALSE(res.has_header("a"));
  5028. res.set_header("a\r\nb", "0");
  5029. EXPECT_EQ(0U, res.headers.size());
  5030. EXPECT_FALSE(res.has_header("a"));
  5031. res.set_header("a\rb", "0");
  5032. EXPECT_EQ(0U, res.headers.size());
  5033. EXPECT_FALSE(res.has_header("a"));
  5034. res.set_header("a\nb", "0");
  5035. EXPECT_EQ(0U, res.headers.size());
  5036. EXPECT_FALSE(res.has_header("a"));
  5037. res.set_redirect("1\r\nSet-Cookie: a=1");
  5038. EXPECT_EQ(0U, res.headers.size());
  5039. EXPECT_FALSE(res.has_header("Location"));
  5040. })
  5041. .Get("/slow",
  5042. [&](const Request & /*req*/, Response &res) {
  5043. std::this_thread::sleep_for(std::chrono::seconds(4));
  5044. res.set_content("slow", "text/plain");
  5045. })
  5046. #if 0
  5047. .Post("/slowpost",
  5048. [&](const Request & /*req*/, Response &res) {
  5049. std::this_thread::sleep_for(std::chrono::seconds(2));
  5050. res.set_content("slow", "text/plain");
  5051. })
  5052. #endif
  5053. .Get("/remote_addr",
  5054. [&](const Request &req, Response &res) {
  5055. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5056. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5057. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5058. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5059. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5060. #endif
  5061. res.set_content(req.remote_addr, "text/plain");
  5062. })
  5063. .Get("/local_addr",
  5064. [&](const Request &req, Response &res) {
  5065. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5066. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5067. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5068. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5069. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5070. #endif
  5071. auto local_addr = req.local_addr;
  5072. auto local_port = std::to_string(req.local_port);
  5073. res.set_content(local_addr.append(":").append(local_port),
  5074. "text/plain");
  5075. })
  5076. .Get("/endwith%",
  5077. [&](const Request & /*req*/, Response &res) {
  5078. res.set_content("Hello World!", "text/plain");
  5079. })
  5080. .Get("/a\\+\\+b",
  5081. [&](const Request &req, Response &res) {
  5082. ASSERT_TRUE(req.has_param("a +b"));
  5083. auto val = req.get_param_value("a +b");
  5084. res.set_content(val, "text/plain");
  5085. })
  5086. .Get("/", [&](const Request & /*req*/,
  5087. Response &res) { res.set_redirect("/hi"); })
  5088. .Post("/1",
  5089. [](const Request & /*req*/, Response &res) {
  5090. res.set_redirect("/2", StatusCode::SeeOther_303);
  5091. })
  5092. .Get("/2",
  5093. [](const Request & /*req*/, Response &res) {
  5094. res.set_content("redirected.", "text/plain");
  5095. res.status = StatusCode::OK_200;
  5096. })
  5097. .Post("/person",
  5098. [&](const Request &req, Response &res) {
  5099. if (req.has_param("name") && req.has_param("note")) {
  5100. persons_[req.get_param_value("name")] =
  5101. req.get_param_value("note");
  5102. } else {
  5103. res.status = StatusCode::BadRequest_400;
  5104. }
  5105. })
  5106. .Put("/person",
  5107. [&](const Request &req, Response &res) {
  5108. if (req.has_param("name") && req.has_param("note")) {
  5109. persons_[req.get_param_value("name")] =
  5110. req.get_param_value("note");
  5111. } else {
  5112. res.status = StatusCode::BadRequest_400;
  5113. }
  5114. })
  5115. .Get("/person/(.*)",
  5116. [&](const Request &req, Response &res) {
  5117. string name = req.matches[1];
  5118. if (persons_.find(name) != persons_.end()) {
  5119. auto note = persons_[name];
  5120. res.set_content(note, "text/plain");
  5121. } else {
  5122. res.status = StatusCode::NotFound_404;
  5123. }
  5124. })
  5125. .Delete("/person",
  5126. [&](const Request &req, Response &res) {
  5127. if (req.has_param("name")) {
  5128. string name = req.get_param_value("name");
  5129. if (persons_.find(name) != persons_.end()) {
  5130. persons_.erase(name);
  5131. res.set_content("DELETED", "text/plain");
  5132. } else {
  5133. res.status = StatusCode::NotFound_404;
  5134. }
  5135. } else {
  5136. res.status = StatusCode::BadRequest_400;
  5137. }
  5138. })
  5139. .Post("/x-www-form-urlencoded-json",
  5140. [&](const Request &req, Response &res) {
  5141. auto json = req.get_param_value("json");
  5142. ASSERT_EQ(JSON_DATA, json);
  5143. res.set_content(json, "appliation/json");
  5144. res.status = StatusCode::OK_200;
  5145. })
  5146. .Get("/streamed-chunked",
  5147. [&](const Request & /*req*/, Response &res) {
  5148. res.set_chunked_content_provider(
  5149. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5150. sink.os << "123";
  5151. sink.os << "456";
  5152. sink.os << "789";
  5153. sink.done();
  5154. return true;
  5155. });
  5156. })
  5157. .Get("/streamed-chunked-with-prohibited-trailer",
  5158. [&](const Request & /*req*/, Response &res) {
  5159. auto i = new int(0);
  5160. // Declare both a prohibited trailer (Content-Length) and an
  5161. // allowed one
  5162. res.set_header("Trailer", "Content-Length, X-Allowed");
  5163. res.set_chunked_content_provider(
  5164. "text/plain",
  5165. [i](size_t /*offset*/, DataSink &sink) {
  5166. switch (*i) {
  5167. case 0: sink.os << "123"; break;
  5168. case 1: sink.os << "456"; break;
  5169. case 2: sink.os << "789"; break;
  5170. case 3: {
  5171. sink.done_with_trailer(
  5172. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5173. } break;
  5174. }
  5175. (*i)++;
  5176. return true;
  5177. },
  5178. [i](bool success) {
  5179. EXPECT_TRUE(success);
  5180. delete i;
  5181. });
  5182. })
  5183. .Get("/streamed-chunked2",
  5184. [&](const Request & /*req*/, Response &res) {
  5185. auto i = new int(0);
  5186. res.set_chunked_content_provider(
  5187. "text/plain",
  5188. [i](size_t /*offset*/, DataSink &sink) {
  5189. switch (*i) {
  5190. case 0: sink.os << "123"; break;
  5191. case 1: sink.os << "456"; break;
  5192. case 2: sink.os << "789"; break;
  5193. case 3: sink.done(); break;
  5194. }
  5195. (*i)++;
  5196. return true;
  5197. },
  5198. [i](bool success) {
  5199. EXPECT_TRUE(success);
  5200. delete i;
  5201. });
  5202. })
  5203. .Get("/streamed-chunked-with-trailer",
  5204. [&](const Request & /*req*/, Response &res) {
  5205. auto i = new int(0);
  5206. res.set_header("Trailer", "Dummy1, Dummy2");
  5207. res.set_chunked_content_provider(
  5208. "text/plain",
  5209. [i](size_t /*offset*/, DataSink &sink) {
  5210. switch (*i) {
  5211. case 0: sink.os << "123"; break;
  5212. case 1: sink.os << "456"; break;
  5213. case 2: sink.os << "789"; break;
  5214. case 3: {
  5215. sink.done_with_trailer(
  5216. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5217. } break;
  5218. }
  5219. (*i)++;
  5220. return true;
  5221. },
  5222. [i](bool success) {
  5223. EXPECT_TRUE(success);
  5224. delete i;
  5225. });
  5226. })
  5227. .Get("/streamed",
  5228. [&](const Request & /*req*/, Response &res) {
  5229. res.set_content_provider(
  5230. 6, "text/plain",
  5231. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5232. sink.os << (offset < 3 ? "a" : "b");
  5233. return true;
  5234. });
  5235. })
  5236. .Get("/streamed-without-length",
  5237. [&](const Request & /*req*/, Response &res) {
  5238. auto data = new std::string("abcdefg");
  5239. res.set_content_provider(
  5240. "text/plain",
  5241. [data](size_t offset, DataSink &sink) {
  5242. if (offset < data->size()) {
  5243. sink.os << data->substr(offset);
  5244. }
  5245. sink.done();
  5246. return true;
  5247. },
  5248. [data](bool success) {
  5249. EXPECT_TRUE(success);
  5250. delete data;
  5251. });
  5252. })
  5253. .Get("/streamed-with-range",
  5254. [&](const Request &req, Response &res) {
  5255. auto data = new std::string("abcdefg");
  5256. // An explicit status keeps the server from picking the 206 it
  5257. // would otherwise choose for a ranged request, so the response
  5258. // is not a partial representation.
  5259. auto status = req.get_param_value("status");
  5260. if (status == "200") {
  5261. res.status = StatusCode::OK_200;
  5262. } else if (status == "403") {
  5263. res.status = StatusCode::Forbidden_403;
  5264. }
  5265. res.set_content_provider(
  5266. data->size(), "text/plain",
  5267. [data](size_t offset, size_t length, DataSink &sink) {
  5268. size_t DATA_CHUNK_SIZE = 4;
  5269. const auto &d = *data;
  5270. auto out_len =
  5271. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5272. auto ret =
  5273. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5274. EXPECT_TRUE(ret);
  5275. return true;
  5276. },
  5277. [data, &req](bool success) {
  5278. EXPECT_EQ(success, !req.has_param("error"));
  5279. delete data;
  5280. });
  5281. })
  5282. .Get("/streamed-cancel",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. res.set_content_provider(
  5285. size_t(-1), "text/plain",
  5286. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5287. sink.os << "data_chunk";
  5288. return true;
  5289. });
  5290. })
  5291. .Get("/regex-with-delimiter",
  5292. [&](const Request &req, Response & /*res*/) {
  5293. ASSERT_TRUE(req.has_param("key"));
  5294. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5295. })
  5296. .Get("/with-range",
  5297. [&](const Request & /*req*/, Response &res) {
  5298. res.set_content("abcdefg", "text/plain");
  5299. })
  5300. .Get("/test-start-time",
  5301. [&](const Request &req, Response & /*res*/) {
  5302. EXPECT_NE(req.start_time_,
  5303. std::chrono::steady_clock::time_point::min());
  5304. })
  5305. .Get("/with-range-customized-response",
  5306. [&](const Request & /*req*/, Response &res) {
  5307. res.status = StatusCode::BadRequest_400;
  5308. res.set_content(JSON_DATA, "application/json");
  5309. })
  5310. .Post("/chunked",
  5311. [&](const Request &req, Response & /*res*/) {
  5312. EXPECT_EQ(req.body, "dechunked post body");
  5313. })
  5314. .Post("/large-chunked",
  5315. [&](const Request &req, Response & /*res*/) {
  5316. std::string expected(6 * 30 * 1024u, 'a');
  5317. EXPECT_EQ(req.body, expected);
  5318. })
  5319. .Post("/multipart",
  5320. [&](const Request &req, Response & /*res*/) {
  5321. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5322. req.form.get_field_count("text2") +
  5323. req.form.get_field_count("file3") +
  5324. req.form.get_field_count("file4"));
  5325. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5326. req.form.get_file_count("file2"));
  5327. ASSERT_TRUE(!req.form.has_file("???"));
  5328. ASSERT_TRUE(!req.form.has_field("???"));
  5329. ASSERT_TRUE(req.body.empty());
  5330. {
  5331. const auto &text = req.form.get_field("text1");
  5332. EXPECT_EQ("text default", text);
  5333. }
  5334. {
  5335. const auto &text = req.form.get_field("text2");
  5336. EXPECT_EQ("aωb", text);
  5337. }
  5338. {
  5339. const auto &file = req.form.get_file("file1");
  5340. EXPECT_EQ("hello.txt", file.filename);
  5341. EXPECT_EQ("text/plain", file.content_type);
  5342. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5343. }
  5344. {
  5345. const auto &file = req.form.get_file("file2");
  5346. EXPECT_EQ("world.json", file.filename);
  5347. EXPECT_EQ("application/json", file.content_type);
  5348. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5349. }
  5350. {
  5351. const auto &text = req.form.get_field("file3");
  5352. EXPECT_EQ(0u, text.size());
  5353. }
  5354. {
  5355. const auto &text = req.form.get_field("file4");
  5356. EXPECT_EQ(0u, text.size());
  5357. }
  5358. })
  5359. .Post("/multipart/multi_file_values",
  5360. [&](const Request &req, Response & /*res*/) {
  5361. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5362. req.form.get_field_count("multi_text1"));
  5363. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5364. ASSERT_TRUE(!req.form.has_file("???"));
  5365. ASSERT_TRUE(!req.form.has_field("???"));
  5366. ASSERT_TRUE(req.body.empty());
  5367. {
  5368. const auto &text = req.form.get_field("text");
  5369. EXPECT_EQ("default text", text);
  5370. }
  5371. {
  5372. const auto &text1_values = req.form.get_fields("multi_text1");
  5373. EXPECT_EQ(2u, text1_values.size());
  5374. EXPECT_EQ("aaaaa", text1_values[0]);
  5375. EXPECT_EQ("bbbbb", text1_values[1]);
  5376. }
  5377. {
  5378. const auto &file1_values = req.form.get_files("multi_file1");
  5379. EXPECT_EQ(2u, file1_values.size());
  5380. auto file1 = file1_values[0];
  5381. EXPECT_EQ(file1.filename, "hello.txt");
  5382. EXPECT_EQ(file1.content_type, "text/plain");
  5383. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5384. auto file2 = file1_values[1];
  5385. EXPECT_EQ(file2.filename, "world.json");
  5386. EXPECT_EQ(file2.content_type, "application/json");
  5387. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5388. }
  5389. })
  5390. .Post("/empty",
  5391. [&](const Request &req, Response &res) {
  5392. EXPECT_EQ(req.body, "");
  5393. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5394. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5395. res.set_content("empty", "text/plain");
  5396. })
  5397. .Post("/empty-no-content-type",
  5398. [&](const Request &req, Response &res) {
  5399. EXPECT_EQ(req.body, "");
  5400. EXPECT_FALSE(req.has_header("Content-Type"));
  5401. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5402. res.set_content("empty-no-content-type", "text/plain");
  5403. })
  5404. .Post("/path-only",
  5405. [&](const Request &req, Response &res) {
  5406. EXPECT_EQ(req.body, "");
  5407. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5408. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5409. res.set_content("path-only", "text/plain");
  5410. })
  5411. .Post("/path-headers-only",
  5412. [&](const Request &req, Response &res) {
  5413. EXPECT_EQ(req.body, "");
  5414. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5415. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5416. EXPECT_EQ("world", req.get_header_value("hello"));
  5417. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5418. res.set_content("path-headers-only", "text/plain");
  5419. })
  5420. .Post("/post-large",
  5421. [&](const Request &req, Response &res) {
  5422. EXPECT_EQ(req.body, LARGE_DATA);
  5423. res.set_content(req.body, "text/plain");
  5424. })
  5425. .Post("/post-loopback",
  5426. [&](const Request &, Response &res,
  5427. ContentReader const &content_reader) {
  5428. std::string body;
  5429. content_reader([&](const char *data, size_t data_length) {
  5430. body.append(data, data_length);
  5431. return true;
  5432. });
  5433. res.set_content(body, "text/plain");
  5434. })
  5435. .Put("/put-loopback",
  5436. [&](const Request &, Response &res,
  5437. ContentReader const &content_reader) {
  5438. std::string body;
  5439. content_reader([&](const char *data, size_t data_length) {
  5440. body.append(data, data_length);
  5441. return true;
  5442. });
  5443. res.set_content(body, "text/plain");
  5444. })
  5445. .Patch("/patch-loopback",
  5446. [&](const Request &, Response &res,
  5447. ContentReader const &content_reader) {
  5448. std::string body;
  5449. content_reader([&](const char *data, size_t data_length) {
  5450. body.append(data, data_length);
  5451. return true;
  5452. });
  5453. res.set_content(body, "text/plain");
  5454. })
  5455. .Put("/empty-no-content-type",
  5456. [&](const Request &req, Response &res) {
  5457. EXPECT_EQ(req.body, "");
  5458. EXPECT_FALSE(req.has_header("Content-Type"));
  5459. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5460. res.set_content("empty-no-content-type", "text/plain");
  5461. })
  5462. .Put("/put",
  5463. [&](const Request &req, Response &res) {
  5464. EXPECT_EQ(req.body, "PUT");
  5465. res.set_content(req.body, "text/plain");
  5466. })
  5467. .Put("/put-large",
  5468. [&](const Request &req, Response &res) {
  5469. EXPECT_EQ(req.body, LARGE_DATA);
  5470. res.set_content(req.body, "text/plain");
  5471. })
  5472. .Patch("/patch",
  5473. [&](const Request &req, Response &res) {
  5474. EXPECT_EQ(req.body, "PATCH");
  5475. res.set_content(req.body, "text/plain");
  5476. })
  5477. .Delete("/delete",
  5478. [&](const Request & /*req*/, Response &res) {
  5479. res.set_content("DELETE", "text/plain");
  5480. })
  5481. .Delete("/delete-body",
  5482. [&](const Request &req, Response &res) {
  5483. EXPECT_EQ(req.body, "content");
  5484. res.set_content(req.body, "text/plain");
  5485. })
  5486. .Options(R"(\*)",
  5487. [&](const Request & /*req*/, Response &res) {
  5488. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5489. })
  5490. .CustomRoute("PROPFIND", "/dav/:id",
  5491. [&](const Request &req, Response &res) {
  5492. res.set_header("x-body-size",
  5493. std::to_string(req.body.size()));
  5494. res.set_header("x-matched-route", req.matched_route);
  5495. res.set_header("x-dav-id", req.path_params.at("id"));
  5496. res.status = StatusCode::MultiStatus_207;
  5497. res.set_content(req.body, "application/xml");
  5498. })
  5499. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5500. [&](const Request &req, Response &res) {
  5501. res.set_header("x-dav-match", req.matches[1]);
  5502. res.status = StatusCode::MultiStatus_207;
  5503. })
  5504. .CustomRoute("MKCOL", "/dav-mkcol",
  5505. [&](const Request &req, Response &res) {
  5506. EXPECT_TRUE(req.body.empty());
  5507. res.status = StatusCode::Created_201;
  5508. })
  5509. .CustomRoute(
  5510. "REPORT", "/dav-report",
  5511. [&](const Request & /*req*/, Response &res,
  5512. const ContentReader &content_reader) {
  5513. std::string body;
  5514. content_reader([&](const char *data, size_t data_length) {
  5515. body.append(data, data_length);
  5516. return true;
  5517. });
  5518. res.set_header("x-body-size", std::to_string(body.size()));
  5519. res.status = StatusCode::MultiStatus_207;
  5520. res.set_content(body, "application/xml");
  5521. })
  5522. .Get("/request-target",
  5523. [&](const Request &req, Response & /*res*/) {
  5524. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5525. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5526. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5527. })
  5528. .Get("/long-query-value",
  5529. [&](const Request &req, Response & /*res*/) {
  5530. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5531. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5532. })
  5533. .Get("/too-long-query-value",
  5534. [&](const Request &req, Response & /*res*/) {
  5535. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5536. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5537. })
  5538. .Get("/array-param",
  5539. [&](const Request &req, Response & /*res*/) {
  5540. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5541. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5542. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5543. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5544. })
  5545. .Get("/array-param-values",
  5546. [&](const Request &req, Response & /*res*/) {
  5547. auto values = req.get_param_values("array");
  5548. EXPECT_EQ(3u, values.size());
  5549. EXPECT_EQ("value1", values[0]);
  5550. EXPECT_EQ("value2", values[1]);
  5551. EXPECT_EQ("value3", values[2]);
  5552. auto empty = req.get_param_values("nonexistent");
  5553. EXPECT_TRUE(empty.empty());
  5554. })
  5555. .Post("/validate-no-multiple-headers",
  5556. [&](const Request &req, Response & /*res*/) {
  5557. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5558. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5559. })
  5560. .Post("/content_receiver",
  5561. [&](const Request &req, Response &res,
  5562. const ContentReader &content_reader) {
  5563. if (req.is_multipart_form_data()) {
  5564. std::vector<FormData> items;
  5565. content_reader(
  5566. [&](const FormData &file) {
  5567. items.push_back(file);
  5568. return true;
  5569. },
  5570. [&](const char *data, size_t data_length) {
  5571. items.back().content.append(data, data_length);
  5572. return true;
  5573. });
  5574. EXPECT_EQ(5u, items.size());
  5575. {
  5576. const auto &file = get_file_value(items, "text1");
  5577. EXPECT_TRUE(file.filename.empty());
  5578. EXPECT_EQ("text default", file.content);
  5579. }
  5580. {
  5581. const auto &file = get_file_value(items, "text2");
  5582. EXPECT_TRUE(file.filename.empty());
  5583. EXPECT_EQ("aωb", file.content);
  5584. }
  5585. {
  5586. const auto &file = get_file_value(items, "file1");
  5587. EXPECT_EQ("hello.txt", file.filename);
  5588. EXPECT_EQ("text/plain", file.content_type);
  5589. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5590. }
  5591. {
  5592. const auto &file = get_file_value(items, "file2");
  5593. EXPECT_EQ("world.json", file.filename);
  5594. EXPECT_EQ("application/json", file.content_type);
  5595. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5596. }
  5597. {
  5598. const auto &file = get_file_value(items, "file3");
  5599. EXPECT_TRUE(file.filename.empty());
  5600. EXPECT_EQ("application/octet-stream", file.content_type);
  5601. EXPECT_EQ(0u, file.content.size());
  5602. }
  5603. } else {
  5604. std::string body;
  5605. content_reader([&](const char *data, size_t data_length) {
  5606. EXPECT_EQ(7U, data_length);
  5607. body.append(data, data_length);
  5608. return true;
  5609. });
  5610. EXPECT_EQ(body, "content");
  5611. res.set_content(body, "text/plain");
  5612. }
  5613. })
  5614. .Put("/content_receiver",
  5615. [&](const Request & /*req*/, Response &res,
  5616. const ContentReader &content_reader) {
  5617. std::string body;
  5618. content_reader([&](const char *data, size_t data_length) {
  5619. body.append(data, data_length);
  5620. return true;
  5621. });
  5622. EXPECT_EQ(body, "content");
  5623. res.set_content(body, "text/plain");
  5624. })
  5625. .Patch("/content_receiver",
  5626. [&](const Request & /*req*/, Response &res,
  5627. const ContentReader &content_reader) {
  5628. std::string body;
  5629. content_reader([&](const char *data, size_t data_length) {
  5630. body.append(data, data_length);
  5631. return true;
  5632. });
  5633. EXPECT_EQ(body, "content");
  5634. res.set_content(body, "text/plain");
  5635. })
  5636. .Post("/query-string-and-body",
  5637. [&](const Request &req, Response & /*res*/) {
  5638. ASSERT_TRUE(req.has_param("key"));
  5639. EXPECT_EQ(req.get_param_value("key"), "value");
  5640. EXPECT_EQ(req.body, "content");
  5641. })
  5642. .Get("/last-request",
  5643. [&](const Request &req, Response & /*res*/) {
  5644. EXPECT_EQ("close", req.get_header_value("Connection"));
  5645. })
  5646. .Get(R"(/redirect/(\d+))",
  5647. [&](const Request &req, Response &res) {
  5648. auto num = std::stoi(req.matches[1]) + 1;
  5649. std::string url = "/redirect/" + std::to_string(num);
  5650. res.set_redirect(url);
  5651. })
  5652. .Post("/binary",
  5653. [&](const Request &req, Response &res) {
  5654. EXPECT_EQ(4U, req.body.size());
  5655. EXPECT_EQ("application/octet-stream",
  5656. req.get_header_value("Content-Type"));
  5657. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5658. res.set_content(req.body, "application/octet-stream");
  5659. })
  5660. .Put("/binary",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(4U, req.body.size());
  5663. EXPECT_EQ("application/octet-stream",
  5664. req.get_header_value("Content-Type"));
  5665. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5666. res.set_content(req.body, "application/octet-stream");
  5667. })
  5668. .Patch("/binary",
  5669. [&](const Request &req, Response &res) {
  5670. EXPECT_EQ(4U, req.body.size());
  5671. EXPECT_EQ("application/octet-stream",
  5672. req.get_header_value("Content-Type"));
  5673. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5674. res.set_content(req.body, "application/octet-stream");
  5675. })
  5676. .Delete("/binary",
  5677. [&](const Request &req, Response &res) {
  5678. EXPECT_EQ(4U, req.body.size());
  5679. EXPECT_EQ("application/octet-stream",
  5680. req.get_header_value("Content-Type"));
  5681. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5682. res.set_content(req.body, "application/octet-stream");
  5683. })
  5684. .Get("/issue1772",
  5685. [&](const Request & /*req*/, Response &res) {
  5686. res.status = 401;
  5687. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5688. })
  5689. .Delete("/issue609",
  5690. [](const httplib::Request &, httplib::Response &res,
  5691. const httplib::ContentReader &) {
  5692. res.set_content("ok", "text/plain");
  5693. })
  5694. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5695. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5696. .Get("/compress",
  5697. [&](const Request & /*req*/, Response &res) {
  5698. res.set_content(
  5699. "12345678901234567890123456789012345678901234567890123456789"
  5700. "01234567890123456789012345678901234567890",
  5701. "text/plain");
  5702. })
  5703. .Get("/compress-with-charset",
  5704. [&](const Request & /*req*/, Response &res) {
  5705. res.set_content(
  5706. "12345678901234567890123456789012345678901234567890123456789"
  5707. "01234567890123456789012345678901234567890",
  5708. "application/json; charset=utf-8");
  5709. })
  5710. .Get("/nocompress",
  5711. [&](const Request & /*req*/, Response &res) {
  5712. res.set_content(
  5713. "12345678901234567890123456789012345678901234567890123456789"
  5714. "01234567890123456789012345678901234567890",
  5715. "application/octet-stream");
  5716. })
  5717. .Post("/compress-multipart",
  5718. [&](const Request &req, Response & /*res*/) {
  5719. EXPECT_EQ(2u, req.form.fields.size());
  5720. ASSERT_TRUE(!req.form.has_field("???"));
  5721. {
  5722. const auto &text = req.form.get_field("key1");
  5723. EXPECT_EQ("test", text);
  5724. }
  5725. {
  5726. const auto &text = req.form.get_field("key2");
  5727. EXPECT_EQ("--abcdefg123", text);
  5728. }
  5729. })
  5730. #endif
  5731. ;
  5732. persons_["john"] = "programmer";
  5733. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5734. svr_.wait_until_ready();
  5735. }
  5736. virtual void TearDown() {
  5737. svr_.stop();
  5738. if (!request_threads_.empty()) {
  5739. std::this_thread::sleep_for(std::chrono::seconds(1));
  5740. for (auto &t : request_threads_) {
  5741. t.join();
  5742. }
  5743. }
  5744. t_.join();
  5745. }
  5746. map<string, string> persons_;
  5747. #ifdef CPPHTTPLIB_SSL_ENABLED
  5748. SSLClient cli_;
  5749. SSLServer svr_;
  5750. #else
  5751. Client cli_;
  5752. Server svr_;
  5753. #endif
  5754. thread t_;
  5755. std::vector<thread> request_threads_;
  5756. };
  5757. TEST_F(ServerTest, GetMethod200) {
  5758. auto res = cli_.Get("/hi");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ("HTTP/1.1", res->version);
  5761. EXPECT_EQ(StatusCode::OK_200, res->status);
  5762. EXPECT_EQ("OK", res->reason);
  5763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5764. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5765. EXPECT_EQ("Hello World!", res->body);
  5766. }
  5767. TEST_F(ServerTest, GetEmptyFile) {
  5768. auto res = cli_.Get("/empty_file");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. EXPECT_EQ(StatusCode::OK_200, res->status);
  5771. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5772. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5773. EXPECT_EQ("", res->body);
  5774. }
  5775. TEST_F(ServerTest, GetFileContent) {
  5776. auto res = cli_.Get("/file_content");
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5780. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5781. EXPECT_EQ("test.html", res->body);
  5782. }
  5783. TEST_F(ServerTest, GetFileContentWithRange) {
  5784. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5787. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5788. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5789. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5790. EXPECT_EQ("est", res->body);
  5791. }
  5792. TEST_F(ServerTest, GetFileContentWithContentType) {
  5793. auto res = cli_.Get("/file_content_with_content_type");
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. EXPECT_EQ(StatusCode::OK_200, res->status);
  5796. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5797. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5798. EXPECT_EQ("file\n", res->body);
  5799. }
  5800. TEST_F(ServerTest, GetInvalidFileContent) {
  5801. auto res = cli_.Get("/invalid_file_content");
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5804. }
  5805. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5806. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ("HTTP/1.1", res->version);
  5809. EXPECT_EQ(StatusCode::OK_200, res->status);
  5810. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5811. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5812. EXPECT_EQ("Hello World!", res->body);
  5813. }
  5814. TEST_F(ServerTest, GetMethod302) {
  5815. auto res = cli_.Get("/");
  5816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5817. EXPECT_EQ(StatusCode::Found_302, res->status);
  5818. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5819. }
  5820. TEST_F(ServerTest, GetMethod302Redirect) {
  5821. cli_.set_follow_location(true);
  5822. auto res = cli_.Get("/");
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. EXPECT_EQ(StatusCode::OK_200, res->status);
  5825. EXPECT_EQ("Hello World!", res->body);
  5826. EXPECT_EQ("/hi", res->location);
  5827. }
  5828. TEST_F(ServerTest, GetMethod404) {
  5829. auto res = cli_.Get("/invalid");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5832. }
  5833. TEST_F(ServerTest, HeadMethod200) {
  5834. auto res = cli_.Head("/hi");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5838. EXPECT_TRUE(res->body.empty());
  5839. }
  5840. TEST_F(ServerTest, HeadMethod200Static) {
  5841. auto res = cli_.Head("/mount/dir/index.html");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5845. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5846. EXPECT_TRUE(res->body.empty());
  5847. }
  5848. TEST_F(ServerTest, HeadMethod404) {
  5849. auto res = cli_.Head("/invalid");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5852. EXPECT_TRUE(res->body.empty());
  5853. }
  5854. TEST_F(ServerTest, GetMethodPersonJohn) {
  5855. auto res = cli_.Get("/person/john");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5859. EXPECT_EQ("programmer", res->body);
  5860. }
  5861. TEST_F(ServerTest, PostMethod1) {
  5862. auto res = cli_.Get("/person/john1");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5865. res = cli_.Post("/person", "name=john1&note=coder",
  5866. "application/x-www-form-urlencoded");
  5867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5868. ASSERT_EQ(StatusCode::OK_200, res->status);
  5869. res = cli_.Get("/person/john1");
  5870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5871. ASSERT_EQ(StatusCode::OK_200, res->status);
  5872. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5873. ASSERT_EQ("coder", res->body);
  5874. }
  5875. TEST_F(ServerTest, PostMethod2) {
  5876. auto res = cli_.Get("/person/john2");
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5879. Params params;
  5880. params.emplace("name", "john2");
  5881. params.emplace("note", "coder");
  5882. res = cli_.Post("/person", params);
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. ASSERT_EQ(StatusCode::OK_200, res->status);
  5885. res = cli_.Get("/person/john2");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. ASSERT_EQ(StatusCode::OK_200, res->status);
  5888. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5889. ASSERT_EQ("coder", res->body);
  5890. }
  5891. TEST_F(ServerTest, PutMethod3) {
  5892. auto res = cli_.Get("/person/john3");
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5895. Params params;
  5896. params.emplace("name", "john3");
  5897. params.emplace("note", "coder");
  5898. res = cli_.Put("/person", params);
  5899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5900. ASSERT_EQ(StatusCode::OK_200, res->status);
  5901. res = cli_.Get("/person/john3");
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. ASSERT_EQ(StatusCode::OK_200, res->status);
  5904. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5905. ASSERT_EQ("coder", res->body);
  5906. }
  5907. TEST_F(ServerTest, DeleteMethod1) {
  5908. auto res = cli_.Get("/person/john4");
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5911. Params params;
  5912. params.emplace("name", "john4");
  5913. params.emplace("note", "coder");
  5914. res = cli_.Post("/person", params);
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. ASSERT_EQ(StatusCode::OK_200, res->status);
  5917. res = cli_.Get("/person/john4");
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. ASSERT_EQ(StatusCode::OK_200, res->status);
  5920. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5921. ASSERT_EQ("coder", res->body);
  5922. Params delete_params;
  5923. delete_params.emplace("name", "john4");
  5924. res = cli_.Delete("/person", delete_params);
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. ASSERT_EQ(StatusCode::OK_200, res->status);
  5927. ASSERT_EQ("DELETED", res->body);
  5928. res = cli_.Get("/person/john4");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5931. }
  5932. TEST_F(ServerTest, DeleteMethod2) {
  5933. auto res = cli_.Get("/person/john5");
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5936. Params params;
  5937. params.emplace("name", "john5");
  5938. params.emplace("note", "developer");
  5939. res = cli_.Post("/person", params);
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. ASSERT_EQ(StatusCode::OK_200, res->status);
  5942. res = cli_.Get("/person/john5");
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. ASSERT_EQ(StatusCode::OK_200, res->status);
  5945. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5946. ASSERT_EQ("developer", res->body);
  5947. Params delete_params;
  5948. delete_params.emplace("name", "john5");
  5949. Headers headers;
  5950. headers.emplace("Custom-Header", "test-value");
  5951. res = cli_.Delete("/person", headers, delete_params);
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. ASSERT_EQ(StatusCode::OK_200, res->status);
  5954. ASSERT_EQ("DELETED", res->body);
  5955. res = cli_.Get("/person/john5");
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5958. }
  5959. TEST_F(ServerTest, DeleteMethod3) {
  5960. auto res = cli_.Get("/person/john6");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5963. Params params;
  5964. params.emplace("name", "john6");
  5965. params.emplace("note", "tester");
  5966. res = cli_.Post("/person", params);
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. ASSERT_EQ(StatusCode::OK_200, res->status);
  5969. res = cli_.Get("/person/john6");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. ASSERT_EQ(StatusCode::OK_200, res->status);
  5972. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5973. ASSERT_EQ("tester", res->body);
  5974. Params delete_params;
  5975. delete_params.emplace("name", "john6");
  5976. Headers headers;
  5977. headers.emplace("Custom-Header", "test-value");
  5978. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5980. ASSERT_EQ(StatusCode::OK_200, res->status);
  5981. ASSERT_EQ("DELETED", res->body);
  5982. res = cli_.Get("/person/john6");
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5985. }
  5986. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5987. Params params;
  5988. params.emplace("json", JSON_DATA);
  5989. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5991. ASSERT_EQ(StatusCode::OK_200, res->status);
  5992. ASSERT_EQ(JSON_DATA, res->body);
  5993. }
  5994. TEST_F(ServerTest, PostEmptyContent) {
  5995. auto res = cli_.Post("/empty", "", "text/plain");
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. ASSERT_EQ(StatusCode::OK_200, res->status);
  5998. ASSERT_EQ("empty", res->body);
  5999. }
  6000. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6001. auto res = cli_.Post("/empty-no-content-type");
  6002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6003. ASSERT_EQ(StatusCode::OK_200, res->status);
  6004. ASSERT_EQ("empty-no-content-type", res->body);
  6005. }
  6006. TEST_F(ServerTest, PostPathOnly) {
  6007. auto res = cli_.Post("/path-only");
  6008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6009. ASSERT_EQ(StatusCode::OK_200, res->status);
  6010. ASSERT_EQ("path-only", res->body);
  6011. }
  6012. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6013. auto res = cli_.Post("/path-headers-only",
  6014. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. ASSERT_EQ(StatusCode::OK_200, res->status);
  6017. ASSERT_EQ("path-headers-only", res->body);
  6018. }
  6019. TEST_F(ServerTest, PostLarge) {
  6020. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. ASSERT_EQ(StatusCode::OK_200, res->status);
  6023. EXPECT_EQ(LARGE_DATA, res->body);
  6024. }
  6025. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6026. auto res = cli_.Put("/empty-no-content-type");
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. ASSERT_EQ(StatusCode::OK_200, res->status);
  6029. ASSERT_EQ("empty-no-content-type", res->body);
  6030. }
  6031. TEST_F(ServerTest, GetMethodDir) {
  6032. auto res = cli_.Get("/dir/");
  6033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6034. EXPECT_EQ(StatusCode::OK_200, res->status);
  6035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6036. auto body = R"(<html>
  6037. <head>
  6038. </head>
  6039. <body>
  6040. <a href="/dir/test.html">Test</a>
  6041. <a href="/hi">hi</a>
  6042. </body>
  6043. </html>
  6044. )";
  6045. EXPECT_EQ(body, res->body);
  6046. }
  6047. TEST_F(ServerTest, GetMethodDirTest) {
  6048. auto res = cli_.Get("/dir/test.html");
  6049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6050. EXPECT_EQ(StatusCode::OK_200, res->status);
  6051. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6052. EXPECT_EQ("test.html", res->body);
  6053. }
  6054. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6055. auto res = cli_.Get("/dir/../dir/test.html");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::OK_200, res->status);
  6058. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6059. EXPECT_EQ("test.html", res->body);
  6060. }
  6061. TEST_F(ServerTest, GetMethodInvalidPath) {
  6062. auto res = cli_.Get("/dir/../test.html");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6065. }
  6066. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6067. auto res = cli_.Get("/../www/dir/test.html");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6070. }
  6071. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6072. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6075. }
  6076. TEST_F(ServerTest, GetMethodDirMountTest) {
  6077. auto res = cli_.Get("/mount/dir/test.html");
  6078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6079. EXPECT_EQ(StatusCode::OK_200, res->status);
  6080. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6081. EXPECT_EQ("test.html", res->body);
  6082. }
  6083. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6084. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::OK_200, res->status);
  6087. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6088. EXPECT_EQ("test.html", res->body);
  6089. }
  6090. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6091. auto res = cli_.Get("/mount/dir/../test.html");
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6094. }
  6095. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6096. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6099. }
  6100. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6101. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6103. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6104. }
  6105. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6106. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6109. }
  6110. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6111. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6114. }
  6115. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6116. auto res = cli_.Get("/mount/dir");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6119. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6120. }
  6121. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6122. auto res = cli_.Get("//dir");
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6125. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6126. }
  6127. TEST_F(ServerTest, PostMethod303) {
  6128. auto res = cli_.Post("/1", "body", "text/plain");
  6129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6130. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6131. EXPECT_EQ("/2", res->get_header_value("Location"));
  6132. }
  6133. TEST_F(ServerTest, PostMethod303Redirect) {
  6134. cli_.set_follow_location(true);
  6135. auto res = cli_.Post("/1", "body", "text/plain");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("redirected.", res->body);
  6139. EXPECT_EQ("/2", res->location);
  6140. }
  6141. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6142. auto res = cli_.Get("/dir/test.abcde");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. EXPECT_EQ(StatusCode::OK_200, res->status);
  6145. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6146. EXPECT_EQ("abcde", res->body);
  6147. }
  6148. TEST_F(ServerTest, StaticFileRange) {
  6149. auto res =
  6150. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6153. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6155. EXPECT_EQ(true, res->has_header("Content-Range"));
  6156. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6157. EXPECT_EQ(std::string("cd"), res->body);
  6158. }
  6159. TEST_F(ServerTest, StaticFileRanges) {
  6160. auto res = cli_.Get("/dir/test.abcde",
  6161. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_TRUE(
  6165. res->get_header_value("Content-Type")
  6166. .find(
  6167. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6168. 0);
  6169. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6170. }
  6171. TEST_F(ServerTest, StaticFileRangeHead) {
  6172. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6175. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6176. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6177. EXPECT_EQ(true, res->has_header("Content-Range"));
  6178. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6179. }
  6180. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6181. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6185. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6186. EXPECT_EQ(true, res->has_header("Content-Range"));
  6187. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6188. res->get_header_value("Content-Range"));
  6189. EXPECT_EQ("LAST\n", res->body);
  6190. }
  6191. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6192. auto res =
  6193. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6197. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6198. EXPECT_EQ(true, res->has_header("Content-Range"));
  6199. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6200. }
  6201. TEST_F(ServerTest, StaticFileBigFile) {
  6202. auto res = cli_.Get("/dir/1MB.txt");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6206. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6207. }
  6208. TEST_F(ServerTest, InvalidBaseDirMount) {
  6209. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6210. }
  6211. TEST_F(ServerTest, Binary) {
  6212. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6213. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6214. "application/octet-stream");
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. ASSERT_EQ(StatusCode::OK_200, res->status);
  6217. ASSERT_EQ(4U, res->body.size());
  6218. res = cli_.Put("/binary", binary.data(), binary.size(),
  6219. "application/octet-stream");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::OK_200, res->status);
  6222. ASSERT_EQ(4U, res->body.size());
  6223. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6224. "application/octet-stream");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. ASSERT_EQ(StatusCode::OK_200, res->status);
  6227. ASSERT_EQ(4U, res->body.size());
  6228. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6229. "application/octet-stream");
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ(4U, res->body.size());
  6233. }
  6234. TEST_F(ServerTest, BinaryString) {
  6235. auto binary = std::string("\x00\x01\x02\x03", 4);
  6236. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. ASSERT_EQ(4U, res->body.size());
  6240. res = cli_.Put("/binary", binary, "application/octet-stream");
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. ASSERT_EQ(StatusCode::OK_200, res->status);
  6243. ASSERT_EQ(4U, res->body.size());
  6244. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6246. ASSERT_EQ(StatusCode::OK_200, res->status);
  6247. ASSERT_EQ(4U, res->body.size());
  6248. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ(4U, res->body.size());
  6252. }
  6253. TEST_F(ServerTest, EmptyRequest) {
  6254. auto res = cli_.Get("");
  6255. ASSERT_TRUE(!res);
  6256. EXPECT_EQ(Error::Connection, res.error());
  6257. }
  6258. TEST_F(ServerTest, LongRequest) {
  6259. std::string request;
  6260. for (size_t i = 0; i < 545; i++) {
  6261. request += "/TooLongRequest";
  6262. }
  6263. request += "OK";
  6264. auto res = cli_.Get(request.c_str());
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6267. }
  6268. TEST_F(ServerTest, TooLongRequest) {
  6269. std::string request;
  6270. for (size_t i = 0; i < 546; i++) {
  6271. request += "/TooLongRequest";
  6272. }
  6273. request += "_NG";
  6274. auto start = std::chrono::high_resolution_clock::now();
  6275. cli_.set_keep_alive(true);
  6276. auto res = cli_.Get(request.c_str());
  6277. auto end = std::chrono::high_resolution_clock::now();
  6278. auto elapsed =
  6279. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6280. .count();
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6283. EXPECT_LE(elapsed, 1000);
  6284. EXPECT_EQ("close", res->get_header_value("Connection"));
  6285. EXPECT_FALSE(cli_.is_socket_open());
  6286. }
  6287. TEST_F(ServerTest, AlmostTooLongRequest) {
  6288. // test for #2046 - URI length check shouldn't include other content on req
  6289. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6290. // leading /, space, HTTP/1.1)
  6291. std::string request =
  6292. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6293. auto res = cli_.Get(request.c_str());
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6296. }
  6297. TEST_F(ServerTest, LongHeader) {
  6298. Request req;
  6299. req.method = "GET";
  6300. req.path = "/hi";
  6301. std::string host_and_port;
  6302. host_and_port += HOST;
  6303. host_and_port += ":";
  6304. host_and_port += std::to_string(PORT);
  6305. req.headers.emplace("Host", host_and_port.c_str());
  6306. req.headers.emplace("Accept", "*/*");
  6307. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6308. req.headers.emplace(
  6309. "Header-Name",
  6310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6338. "@@@@@@@@@@@@@@@@");
  6339. auto res = std::make_shared<Response>();
  6340. auto error = Error::Success;
  6341. auto ret = cli_.send(req, *res, error);
  6342. ASSERT_TRUE(ret);
  6343. EXPECT_EQ(StatusCode::OK_200, res->status);
  6344. }
  6345. TEST_F(ServerTest, LongQueryValue) {
  6346. auto start = std::chrono::high_resolution_clock::now();
  6347. cli_.set_keep_alive(true);
  6348. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6349. auto end = std::chrono::high_resolution_clock::now();
  6350. auto elapsed =
  6351. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6352. .count();
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6355. EXPECT_LE(elapsed, 1000);
  6356. EXPECT_EQ("close", res->get_header_value("Connection"));
  6357. EXPECT_FALSE(cli_.is_socket_open());
  6358. }
  6359. TEST_F(ServerTest, TooLongQueryValue) {
  6360. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6361. ASSERT_FALSE(res);
  6362. EXPECT_EQ(Error::Read, res.error());
  6363. }
  6364. TEST_F(ServerTest, TooLongHeader) {
  6365. Request req;
  6366. req.method = "GET";
  6367. req.path = "/hi";
  6368. std::string host_and_port;
  6369. host_and_port += HOST;
  6370. host_and_port += ":";
  6371. host_and_port += std::to_string(PORT);
  6372. req.headers.emplace("Host", host_and_port.c_str());
  6373. req.headers.emplace("Accept", "*/*");
  6374. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6375. req.headers.emplace(
  6376. "Header-Name",
  6377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6385. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6386. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6387. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6388. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6389. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6390. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6395. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6396. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6405. "@@@@@@@@@@@@@@@@@");
  6406. auto res = std::make_shared<Response>();
  6407. auto error = Error::Success;
  6408. auto ret = cli_.send(req, *res, error);
  6409. ASSERT_TRUE(ret);
  6410. EXPECT_EQ(StatusCode::OK_200, res->status);
  6411. }
  6412. TEST_F(ServerTest, HeaderCountAtLimit) {
  6413. // Test with headers just under the 100 limit
  6414. httplib::Headers headers;
  6415. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6416. // This should keep us just under the 100 header limit
  6417. for (int i = 0; i < 95; i++) {
  6418. std::string name = "X-Test-Header-" + std::to_string(i);
  6419. std::string value = "value" + std::to_string(i);
  6420. headers.emplace(name, value);
  6421. }
  6422. // This should work fine as we're under the limit
  6423. auto res = cli_.Get("/hi", headers);
  6424. EXPECT_TRUE(res);
  6425. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6426. }
  6427. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6428. // Test with many headers to exceed the 100 limit
  6429. httplib::Headers headers;
  6430. // Add 150 headers to definitely exceed the 100 limit
  6431. for (int i = 0; i < 150; i++) {
  6432. std::string name = "X-Test-Header-" + std::to_string(i);
  6433. std::string value = "value" + std::to_string(i);
  6434. headers.emplace(name, value);
  6435. }
  6436. // This should fail due to exceeding header count limit
  6437. cli_.set_keep_alive(true);
  6438. auto res = cli_.Get("/hi", headers);
  6439. // The server should respond with 400 Bad Request
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6442. EXPECT_EQ("close", res->get_header_value("Connection"));
  6443. EXPECT_FALSE(cli_.is_socket_open());
  6444. }
  6445. TEST_F(ServerTest, PercentEncoding) {
  6446. auto res = cli_.Get("/e%6edwith%");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. EXPECT_EQ(StatusCode::OK_200, res->status);
  6449. }
  6450. TEST_F(ServerTest, PercentEncodingUnicode) {
  6451. auto res = cli_.Get("/e%u006edwith%");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::OK_200, res->status);
  6454. }
  6455. TEST_F(ServerTest, InvalidPercentEncoding) {
  6456. auto res = cli_.Get("/%endwith%");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6459. }
  6460. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6461. auto res = cli_.Get("/%uendwith%");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6464. }
  6465. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6466. auto res = cli_.Get("/hello?aaa=bbb%");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6469. }
  6470. TEST_F(ServerTest, PlusSignEncoding) {
  6471. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("a +b", res->body);
  6475. }
  6476. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6477. // This test simulates a potential DoS attack using many headers
  6478. // to verify our security fix prevents memory exhaustion
  6479. httplib::Headers attack_headers;
  6480. // Attempt to add many headers like an attacker would (200 headers to far
  6481. // exceed limit)
  6482. for (int i = 0; i < 200; i++) {
  6483. std::string name = "X-Attack-Header-" + std::to_string(i);
  6484. std::string value = "attack_payload_" + std::to_string(i);
  6485. attack_headers.emplace(name, value);
  6486. }
  6487. // Try to POST with excessive headers
  6488. cli_.set_keep_alive(true);
  6489. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6490. // Should either fail or return 400 Bad Request due to security limit
  6491. if (res) {
  6492. // If we get a response, it should be 400 Bad Request
  6493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6494. EXPECT_EQ("close", res->get_header_value("Connection"));
  6495. }
  6496. EXPECT_FALSE(cli_.is_socket_open());
  6497. }
  6498. TEST_F(ServerTest, MultipartFormData) {
  6499. UploadFormDataItems items = {
  6500. {"text1", "text default", "", ""},
  6501. {"text2", "aωb", "", ""},
  6502. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6503. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6504. {"file3", "", "", "application/octet-stream"},
  6505. {"file4", "", "", " application/json tmp-string "}};
  6506. auto res = cli_.Post("/multipart", items);
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::OK_200, res->status);
  6509. }
  6510. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6511. UploadFormDataItems items = {
  6512. {"text", "default text", "", ""},
  6513. {"multi_text1", "aaaaa", "", ""},
  6514. {"multi_text1", "bbbbb", "", ""},
  6515. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6516. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6517. "application/json"},
  6518. };
  6519. auto res = cli_.Post("/multipart/multi_file_values", items);
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::OK_200, res->status);
  6522. }
  6523. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6524. auto res = cli_.Get("/hi");
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::OK_200, res->status);
  6527. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6528. EXPECT_EQ("Hello World!", res->body);
  6529. }
  6530. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6531. Request req;
  6532. req.method = "POST";
  6533. req.path = "/chunked";
  6534. std::string host_and_port;
  6535. host_and_port += HOST;
  6536. host_and_port += ":";
  6537. host_and_port += std::to_string(PORT);
  6538. req.headers.emplace("Host", host_and_port.c_str());
  6539. req.headers.emplace("Accept", "*/*");
  6540. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6541. req.headers.emplace("Content-Type", "text/plain");
  6542. req.headers.emplace("Content-Length", "0");
  6543. req.headers.emplace(
  6544. "Transfer-Encoding",
  6545. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6546. // Client does not chunk, so make a chunked body manually.
  6547. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6548. auto res = std::make_shared<Response>();
  6549. auto error = Error::Success;
  6550. auto ret = cli_.send(req, *res, error);
  6551. ASSERT_TRUE(ret);
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. }
  6554. template <typename ClientT>
  6555. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6556. int expected_status) {
  6557. Request req;
  6558. req.method = "POST";
  6559. req.path = "/chunked";
  6560. std::string host_and_port;
  6561. host_and_port += HOST;
  6562. host_and_port += ":";
  6563. host_and_port += std::to_string(PORT);
  6564. req.headers.emplace("Host", host_and_port.c_str());
  6565. req.headers.emplace("Content-Length", "0");
  6566. req.headers.emplace("Transfer-Encoding", "chunked");
  6567. req.body = body;
  6568. auto res = std::make_shared<Response>();
  6569. auto error = Error::Success;
  6570. ASSERT_TRUE(cli.send(req, *res, error));
  6571. EXPECT_EQ(expected_status, res->status);
  6572. }
  6573. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6574. // rather than treat them as valid lengths.
  6575. template <typename ClientT>
  6576. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6577. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6578. }
  6579. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6580. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6581. }
  6582. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6583. expect_chunked_body_rejected(
  6584. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6585. }
  6586. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6587. // chunk-size line carries no CR, LF or other control character ahead of its
  6588. // terminator. Such a line must be refused rather than read as extension text.
  6589. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6590. expect_chunked_body_rejected(
  6591. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6592. }
  6593. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6594. expect_chunked_body_rejected(
  6595. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6596. }
  6597. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6598. expect_chunked_body_rejected(
  6599. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6600. }
  6601. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6602. // The literal stays split: a hex escape consumes every hex digit that
  6603. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6604. expect_chunked_body_rejected(
  6605. cli_, "4;a\x01"
  6606. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6607. }
  6608. TEST_F(ServerTest, AcceptsChunkExtension) {
  6609. expect_chunked_body_status(cli_,
  6610. "4;name=value\r\ndech\r\n"
  6611. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6612. "0;last\r\n\r\n",
  6613. StatusCode::OK_200);
  6614. }
  6615. TEST_F(ServerTest, GetStreamed2) {
  6616. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6619. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6620. EXPECT_EQ(true, res->has_header("Content-Range"));
  6621. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6622. EXPECT_EQ(std::string("ab"), res->body);
  6623. }
  6624. TEST_F(ServerTest, GetStreamed) {
  6625. auto res = cli_.Get("/streamed");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::OK_200, res->status);
  6628. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6629. EXPECT_EQ(std::string("aaabbb"), res->body);
  6630. }
  6631. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6632. auto res = cli_.Get("/streamed-without-length",
  6633. Headers{make_range_header({{0, -1}})});
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ(false, res->has_header("Content-Length"));
  6637. EXPECT_EQ(false, res->has_header("Content-Range"));
  6638. EXPECT_EQ(std::string("abcdefg"), res->body);
  6639. }
  6640. TEST_F(ServerTest, GetStreamedWithRange1) {
  6641. auto res =
  6642. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6645. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6646. EXPECT_EQ(true, res->has_header("Content-Range"));
  6647. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6648. EXPECT_EQ(std::string("def"), res->body);
  6649. }
  6650. TEST_F(ServerTest, GetStreamedWithRange2) {
  6651. auto res =
  6652. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6655. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6656. EXPECT_EQ(true, res->has_header("Content-Range"));
  6657. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6658. EXPECT_EQ(std::string("bcdefg"), res->body);
  6659. }
  6660. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6661. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6664. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6665. EXPECT_EQ(true, res->has_header("Content-Range"));
  6666. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6667. EXPECT_EQ(std::string("efg"), res->body);
  6668. }
  6669. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6670. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6671. // the entire representation.
  6672. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6673. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6676. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6677. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6678. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6679. }
  6680. }
  6681. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6682. auto res =
  6683. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6686. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(false, res->has_header("Content-Range"));
  6688. EXPECT_EQ(0U, res->body.size());
  6689. }
  6690. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6691. // Only a 206 is served as a partial representation. Under any other status
  6692. // `apply_ranges()` reported the full content length, so the body must match
  6693. // that header, and the content provider must never be asked for an offset
  6694. // outside the representation.
  6695. auto check = [&](int status, const char *range) {
  6696. auto path =
  6697. std::string("/streamed-with-range?status=") + std::to_string(status);
  6698. auto ctx = path + " Range: " + range;
  6699. auto res = cli_.Get(path, Headers{{"Range", range}});
  6700. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6701. EXPECT_EQ(status, res->status) << ctx;
  6702. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6704. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6705. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6706. };
  6707. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6708. check(403, "bytes=3-5");
  6709. // The offset is far past the representation.
  6710. check(403, "bytes=100000-100200");
  6711. // `first_pos` is still -1 here, and the bounds asserts in
  6712. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6713. check(403, "bytes=-3");
  6714. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6715. // multipart branch would have written one that is empty.
  6716. check(403, "bytes=1-2, 4-5");
  6717. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6718. // covers the whole representation.
  6719. check(200, "bytes=3-5");
  6720. check(200, "bytes=1-2, 4-5");
  6721. }
  6722. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6723. auto res =
  6724. cli_.Get("/streamed-with-range",
  6725. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6726. "92233720368547758079223372036854775807"}});
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6729. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6730. EXPECT_EQ(false, res->has_header("Content-Range"));
  6731. EXPECT_EQ(0U, res->body.size());
  6732. }
  6733. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6734. auto res = cli_.Get(
  6735. "/with-range",
  6736. Headers{{"Range",
  6737. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6738. {"Accept-Encoding", ""}});
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6741. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6742. EXPECT_EQ(true, res->has_header("Content-Range"));
  6743. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6744. EXPECT_EQ(std::string("abcdefg"), res->body);
  6745. }
  6746. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6747. auto res = cli_.Get("/with-range", Headers{
  6748. {"Range", "bytes=0-"},
  6749. {"Accept-Encoding", ""},
  6750. });
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6753. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6754. EXPECT_EQ(true, res->has_header("Content-Range"));
  6755. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6756. EXPECT_EQ(std::string("abcdefg"), res->body);
  6757. }
  6758. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6759. auto res = cli_.Get("/streamed-with-range",
  6760. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6763. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6764. EXPECT_EQ(false, res->has_header("Content-Range"));
  6765. EXPECT_EQ(267U, res->body.size());
  6766. // Check that both range contents are present
  6767. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6768. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6769. // Check that Content-Range headers are present for both ranges
  6770. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6771. std::string::npos);
  6772. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6773. std::string::npos);
  6774. }
  6775. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6776. Ranges ranges;
  6777. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6778. ranges.emplace_back(0, -1);
  6779. }
  6780. auto res = cli_.Get("/streamed-with-range?error",
  6781. Headers{{make_range_header(ranges)}});
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6784. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6785. EXPECT_EQ(false, res->has_header("Content-Range"));
  6786. EXPECT_EQ(0U, res->body.size());
  6787. }
  6788. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6789. auto res = cli_.Get("/streamed-with-range",
  6790. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6793. EXPECT_EQ(5U, res->body.size());
  6794. // Check that overlapping ranges are coalesced into a single range
  6795. EXPECT_EQ("bcdef", res->body);
  6796. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6797. // Should be single range, not multipart
  6798. EXPECT_TRUE(res->has_header("Content-Range"));
  6799. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6800. }
  6801. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6802. auto res = cli_.Get("/streamed-with-range",
  6803. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6806. EXPECT_EQ(268U, res->body.size());
  6807. // Check that both range contents are present
  6808. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6809. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6810. // Check that Content-Range headers are present for both ranges
  6811. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6812. std::string::npos);
  6813. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6814. std::string::npos);
  6815. }
  6816. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6817. auto res = cli_.Get("/streamed-with-range",
  6818. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6821. EXPECT_EQ(269U, res->body.size());
  6822. // Check that both duplicate range contents are present
  6823. size_t first_abc = res->body.find("abc\r\n");
  6824. EXPECT_TRUE(first_abc != std::string::npos);
  6825. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6826. EXPECT_TRUE(second_abc != std::string::npos);
  6827. // Check that Content-Range headers are present for both ranges
  6828. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6829. EXPECT_TRUE(first_range != std::string::npos);
  6830. size_t second_range =
  6831. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6832. EXPECT_TRUE(second_range != std::string::npos);
  6833. }
  6834. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6835. auto res =
  6836. cli_.Get("/streamed-with-range?error",
  6837. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6840. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6841. EXPECT_EQ(false, res->has_header("Content-Range"));
  6842. EXPECT_EQ(0U, res->body.size());
  6843. }
  6844. TEST_F(ServerTest, GetStreamedEndless) {
  6845. uint64_t offset = 0;
  6846. auto res = cli_.Get("/streamed-cancel",
  6847. [&](const char * /*data*/, uint64_t data_length) {
  6848. if (offset < 100) {
  6849. offset += data_length;
  6850. return true;
  6851. }
  6852. return false;
  6853. });
  6854. ASSERT_TRUE(!res);
  6855. EXPECT_EQ(Error::Canceled, res.error());
  6856. }
  6857. TEST_F(ServerTest, ClientStop) {
  6858. std::atomic_size_t count{4};
  6859. std::vector<std::thread> threads;
  6860. for (auto i = count.load(); i != 0; --i) {
  6861. threads.emplace_back([&]() {
  6862. auto res = cli_.Get("/streamed-cancel",
  6863. [&](const char *, uint64_t) { return true; });
  6864. --count;
  6865. ASSERT_TRUE(!res);
  6866. EXPECT_TRUE(res.error() == Error::Canceled ||
  6867. res.error() == Error::Read || res.error() == Error::Write);
  6868. });
  6869. }
  6870. std::this_thread::sleep_for(std::chrono::seconds(2));
  6871. while (count != 0) {
  6872. cli_.stop();
  6873. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6874. }
  6875. for (auto &t : threads) {
  6876. t.join();
  6877. }
  6878. }
  6879. TEST_F(ServerTest, GetWithRange1) {
  6880. auto res = cli_.Get("/with-range", Headers{
  6881. make_range_header({{3, 5}}),
  6882. {"Accept-Encoding", ""},
  6883. });
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6886. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6887. EXPECT_EQ(true, res->has_header("Content-Range"));
  6888. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6889. EXPECT_EQ(std::string("def"), res->body);
  6890. }
  6891. TEST_F(ServerTest, GetWithRange2) {
  6892. auto res = cli_.Get("/with-range", Headers{
  6893. make_range_header({{1, -1}}),
  6894. {"Accept-Encoding", ""},
  6895. });
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6898. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6899. EXPECT_EQ(true, res->has_header("Content-Range"));
  6900. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6901. EXPECT_EQ(std::string("bcdefg"), res->body);
  6902. }
  6903. TEST_F(ServerTest, GetWithRange3) {
  6904. auto res = cli_.Get("/with-range", Headers{
  6905. make_range_header({{0, 0}}),
  6906. {"Accept-Encoding", ""},
  6907. });
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6910. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6911. EXPECT_EQ(true, res->has_header("Content-Range"));
  6912. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6913. EXPECT_EQ(std::string("a"), res->body);
  6914. }
  6915. TEST_F(ServerTest, GetWithRange4) {
  6916. auto res = cli_.Get("/with-range", Headers{
  6917. make_range_header({{-1, 2}}),
  6918. {"Accept-Encoding", ""},
  6919. });
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6922. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6923. EXPECT_EQ(true, res->has_header("Content-Range"));
  6924. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6925. EXPECT_EQ(std::string("fg"), res->body);
  6926. }
  6927. TEST_F(ServerTest, GetWithRange5) {
  6928. auto res = cli_.Get("/with-range", Headers{
  6929. make_range_header({{0, 5}}),
  6930. {"Accept-Encoding", ""},
  6931. });
  6932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6933. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6934. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6935. EXPECT_EQ(true, res->has_header("Content-Range"));
  6936. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6937. EXPECT_EQ(std::string("abcdef"), res->body);
  6938. }
  6939. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6940. auto res =
  6941. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6944. }
  6945. TEST_F(ServerTest, GetWithRangeMultipart) {
  6946. auto res =
  6947. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6950. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6951. EXPECT_EQ(false, res->has_header("Content-Range"));
  6952. EXPECT_EQ(267U, res->body.size());
  6953. }
  6954. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6955. auto res = cli_.Get("/with-range",
  6956. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6959. }
  6960. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6961. auto res = cli_.Get("/with-range-customized-response",
  6962. Headers{{make_range_header({{1, 2}})}});
  6963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6964. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6965. EXPECT_EQ(true, res->has_header("Content-Length"));
  6966. EXPECT_EQ(false, res->has_header("Content-Range"));
  6967. EXPECT_EQ(JSON_DATA, res->body);
  6968. }
  6969. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6970. auto res = cli_.Get("/with-range-customized-response",
  6971. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6973. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6974. EXPECT_EQ(true, res->has_header("Content-Length"));
  6975. EXPECT_EQ(false, res->has_header("Content-Range"));
  6976. EXPECT_EQ(JSON_DATA, res->body);
  6977. }
  6978. TEST_F(ServerTest, Issue1772) {
  6979. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6982. }
  6983. TEST_F(ServerTest, Issue609) {
  6984. auto res = cli_.Delete("/issue609");
  6985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6986. EXPECT_EQ(StatusCode::OK_200, res->status);
  6987. EXPECT_EQ(std::string("ok"), res->body);
  6988. }
  6989. TEST_F(ServerTest, GetStreamedChunked) {
  6990. auto res = cli_.Get("/streamed-chunked");
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. EXPECT_EQ(std::string("123456789"), res->body);
  6994. }
  6995. TEST_F(ServerTest, GetStreamedChunked2) {
  6996. auto res = cli_.Get("/streamed-chunked2");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. EXPECT_EQ(std::string("123456789"), res->body);
  7000. }
  7001. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7002. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7004. EXPECT_EQ(StatusCode::OK_200, res->status);
  7005. EXPECT_EQ(std::string("123456789"), res->body);
  7006. EXPECT_TRUE(res->has_header("Trailer"));
  7007. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7008. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7009. // Trailers are now stored separately from headers (security fix)
  7010. EXPECT_EQ(2U, res->trailers.size());
  7011. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7012. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7013. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7014. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7015. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7016. // Verify trailers are NOT in headers (security verification)
  7017. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7018. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7019. }
  7020. TEST_F(ServerTest, LargeChunkedPost) {
  7021. Request req;
  7022. req.method = "POST";
  7023. req.path = "/large-chunked";
  7024. std::string host_and_port;
  7025. host_and_port += HOST;
  7026. host_and_port += ":";
  7027. host_and_port += std::to_string(PORT);
  7028. req.headers.emplace("Host", host_and_port.c_str());
  7029. req.headers.emplace("Accept", "*/*");
  7030. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7031. req.headers.emplace("Content-Type", "text/plain");
  7032. req.headers.emplace("Content-Length", "0");
  7033. req.headers.emplace("Transfer-Encoding", "chunked");
  7034. std::string long_string(30 * 1024u, 'a');
  7035. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7036. // Attempt to make a large enough post to exceed OS buffers, to test that
  7037. // the server handles short reads if the full chunk data isn't available.
  7038. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7039. auto res = std::make_shared<Response>();
  7040. auto error = Error::Success;
  7041. auto ret = cli_.send(req, *res, error);
  7042. ASSERT_TRUE(ret);
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. }
  7045. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7046. auto res = cli_.Get("/remote_addr");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7050. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7051. }
  7052. TEST_F(ServerTest, GetMethodLocalAddr) {
  7053. auto res = cli_.Get("/local_addr");
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::OK_200, res->status);
  7056. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7057. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7058. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7059. }
  7060. TEST_F(ServerTest, HTTPResponseSplitting) {
  7061. auto res = cli_.Get("/http_response_splitting");
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. EXPECT_EQ(StatusCode::OK_200, res->status);
  7064. }
  7065. TEST_F(ServerTest, SlowRequest) {
  7066. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7067. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7068. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7069. }
  7070. #if 0
  7071. TEST_F(ServerTest, SlowPost) {
  7072. char buffer[64 * 1024];
  7073. memset(buffer, 0x42, sizeof(buffer));
  7074. auto res = cli_.Post(
  7075. "/slowpost", 64 * 1024 * 1024,
  7076. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7077. auto ret = sink.write(buffer, sizeof(buffer));
  7078. EXPECT_TRUE(ret);
  7079. return true;
  7080. },
  7081. "text/plain");
  7082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7083. EXPECT_EQ(StatusCode::OK_200, res->status);
  7084. }
  7085. TEST_F(ServerTest, SlowPostFail) {
  7086. char buffer[64 * 1024];
  7087. memset(buffer, 0x42, sizeof(buffer));
  7088. cli_.set_write_timeout(std::chrono::seconds(0));
  7089. auto res = cli_.Post(
  7090. "/slowpost", 64 * 1024 * 1024,
  7091. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7092. sink.write(buffer, sizeof(buffer));
  7093. return true;
  7094. },
  7095. "text/plain");
  7096. ASSERT_TRUE(!res);
  7097. EXPECT_EQ(Error::Write, res.error());
  7098. }
  7099. #endif
  7100. TEST_F(ServerTest, Put) {
  7101. auto res = cli_.Put("/put", "PUT", "text/plain");
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::OK_200, res->status);
  7104. EXPECT_EQ("PUT", res->body);
  7105. }
  7106. TEST_F(ServerTest, PutWithContentProvider) {
  7107. auto res = cli_.Put(
  7108. "/put", 3,
  7109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7110. sink.os << "PUT";
  7111. return true;
  7112. },
  7113. "text/plain");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::OK_200, res->status);
  7116. EXPECT_EQ("PUT", res->body);
  7117. }
  7118. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7119. auto res = cli_.Post(
  7120. "/post", 42,
  7121. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7122. return false;
  7123. },
  7124. "text/plain");
  7125. ASSERT_TRUE(!res);
  7126. EXPECT_EQ(Error::Canceled, res.error());
  7127. }
  7128. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7129. auto res = cli_.Put(
  7130. "/put",
  7131. [](size_t /*offset*/, DataSink &sink) {
  7132. sink.os << "PUT";
  7133. sink.done();
  7134. return true;
  7135. },
  7136. "text/plain");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ("PUT", res->body);
  7140. }
  7141. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7142. auto res = cli_.Post(
  7143. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7144. "text/plain");
  7145. ASSERT_TRUE(!res);
  7146. EXPECT_EQ(Error::Canceled, res.error());
  7147. }
  7148. TEST_F(ServerTest, PostLoopBack) {
  7149. std::string body;
  7150. auto res = cli_.Post(
  7151. "/post-loopback", 9,
  7152. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7153. EXPECT_EQ(9u, length);
  7154. sink.write("123", 3);
  7155. sink.write("456", 3);
  7156. sink.write("789", 3);
  7157. return true;
  7158. },
  7159. "text/plain",
  7160. [&body](const char *data, size_t data_length) {
  7161. body.append(data, data_length);
  7162. return true;
  7163. });
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::OK_200, res->status);
  7166. EXPECT_EQ("123456789", body);
  7167. }
  7168. TEST_F(ServerTest, PutLoopBack) {
  7169. std::string body;
  7170. auto res = cli_.Put(
  7171. "/put-loopback", 9,
  7172. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7173. EXPECT_EQ(9u, length);
  7174. sink.write("123", 3);
  7175. sink.write("456", 3);
  7176. sink.write("789", 3);
  7177. return true;
  7178. },
  7179. "text/plain",
  7180. [&body](const char *data, size_t data_length) {
  7181. body.append(data, data_length);
  7182. return true;
  7183. });
  7184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7185. EXPECT_EQ(StatusCode::OK_200, res->status);
  7186. EXPECT_EQ("123456789", body);
  7187. }
  7188. TEST_F(ServerTest, PatchLoopBack) {
  7189. std::string body;
  7190. auto res = cli_.Patch(
  7191. "/patch-loopback", 9,
  7192. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7193. EXPECT_EQ(9u, length);
  7194. sink.write("123", 3);
  7195. sink.write("456", 3);
  7196. sink.write("789", 3);
  7197. return true;
  7198. },
  7199. "text/plain",
  7200. [&body](const char *data, size_t data_length) {
  7201. body.append(data, data_length);
  7202. return true;
  7203. });
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. EXPECT_EQ(StatusCode::OK_200, res->status);
  7206. EXPECT_EQ("123456789", body);
  7207. }
  7208. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7209. std::string body;
  7210. auto res = cli_.Post(
  7211. "/post-loopback",
  7212. [](size_t /*offset*/, DataSink &sink) {
  7213. sink.write("123", 3);
  7214. sink.write("456", 3);
  7215. sink.write("789", 3);
  7216. sink.done();
  7217. return true;
  7218. },
  7219. "text/plain",
  7220. [&body](const char *data, size_t data_length) {
  7221. body.append(data, data_length);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7225. EXPECT_EQ(StatusCode::OK_200, res->status);
  7226. EXPECT_EQ("123456789", body);
  7227. }
  7228. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7229. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7230. cli_.set_compress(true);
  7231. auto res = cli_.Put(
  7232. "/put", 3,
  7233. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7234. sink.os << "PUT";
  7235. return true;
  7236. },
  7237. "text/plain");
  7238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7239. EXPECT_EQ(StatusCode::OK_200, res->status);
  7240. EXPECT_EQ("PUT", res->body);
  7241. }
  7242. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7243. cli_.set_compress(true);
  7244. auto res = cli_.Post(
  7245. "/post", 42,
  7246. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7247. return false;
  7248. },
  7249. "text/plain");
  7250. ASSERT_TRUE(!res);
  7251. EXPECT_EQ(Error::Canceled, res.error());
  7252. }
  7253. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7254. cli_.set_compress(true);
  7255. auto res = cli_.Put(
  7256. "/put",
  7257. [](size_t /*offset*/, DataSink &sink) {
  7258. sink.os << "PUT";
  7259. sink.done();
  7260. return true;
  7261. },
  7262. "text/plain");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("PUT", res->body);
  7266. }
  7267. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7268. cli_.set_compress(true);
  7269. auto res = cli_.Post(
  7270. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7271. "text/plain");
  7272. ASSERT_TRUE(!res);
  7273. EXPECT_EQ(Error::Canceled, res.error());
  7274. }
  7275. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7276. cli_.set_compress(true);
  7277. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7279. EXPECT_EQ(StatusCode::OK_200, res->status);
  7280. EXPECT_EQ(LARGE_DATA, res->body);
  7281. }
  7282. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7283. #ifdef CPPHTTPLIB_SSL_ENABLED
  7284. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7285. Client cli(s.c_str());
  7286. cli.enable_server_certificate_verification(false);
  7287. #else
  7288. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7289. Client cli(s.c_str());
  7290. #endif
  7291. cli.set_compress(true);
  7292. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ(LARGE_DATA, res->body);
  7296. // The compressed size should be less than a 10th of the original. May vary
  7297. // depending on the zlib library.
  7298. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7299. static_cast<uint64_t>(10 * 1024 * 1024));
  7300. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7301. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7302. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7303. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7304. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7305. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7306. #endif
  7307. }
  7308. TEST_F(ServerTest, PutContentWithDeflate) {
  7309. cli_.set_compress(false);
  7310. Headers headers;
  7311. headers.emplace("Content-Encoding", "deflate");
  7312. // PUT in deflate format:
  7313. auto res = cli_.Put("/put", headers,
  7314. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7316. EXPECT_EQ(StatusCode::OK_200, res->status);
  7317. EXPECT_EQ("PUT", res->body);
  7318. }
  7319. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7320. Headers headers;
  7321. headers.emplace("Accept-Encoding", "gzip, deflate");
  7322. auto res = cli_.Get("/streamed-chunked", headers);
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::OK_200, res->status);
  7325. EXPECT_EQ(std::string("123456789"), res->body);
  7326. }
  7327. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7328. Headers headers;
  7329. headers.emplace("Accept-Encoding", "gzip, deflate");
  7330. auto res = cli_.Get("/streamed-chunked2", headers);
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. EXPECT_EQ(std::string("123456789"), res->body);
  7334. }
  7335. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7336. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. }
  7340. TEST(GzipDecompressor, ChunkedDecompression) {
  7341. std::string data;
  7342. for (size_t i = 0; i < 32 * 1024; ++i) {
  7343. data.push_back(static_cast<char>('a' + i % 26));
  7344. }
  7345. std::string compressed_data;
  7346. {
  7347. httplib::detail::gzip_compressor compressor;
  7348. bool result = compressor.compress(
  7349. data.data(), data.size(),
  7350. /*last=*/true,
  7351. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7352. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7353. compressed_data_size);
  7354. return true;
  7355. });
  7356. ASSERT_TRUE(result);
  7357. }
  7358. std::string decompressed_data;
  7359. {
  7360. httplib::detail::gzip_decompressor decompressor;
  7361. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7362. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7363. size_t chunk_size = 130;
  7364. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7365. chunk_begin += chunk_size) {
  7366. size_t current_chunk_size =
  7367. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7368. bool result = decompressor.decompress(
  7369. compressed_data.data() + chunk_begin, current_chunk_size,
  7370. [&](const char *decompressed_data_chunk,
  7371. size_t decompressed_data_chunk_size) {
  7372. decompressed_data.insert(decompressed_data.size(),
  7373. decompressed_data_chunk,
  7374. decompressed_data_chunk_size);
  7375. return true;
  7376. });
  7377. ASSERT_TRUE(result);
  7378. }
  7379. }
  7380. ASSERT_EQ(data, decompressed_data);
  7381. }
  7382. TEST(GzipDecompressor, DeflateDecompression) {
  7383. std::string original_text = "Raw deflate without gzip";
  7384. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7385. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7386. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7387. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7388. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7389. std::string decompressed_data;
  7390. {
  7391. httplib::detail::gzip_decompressor decompressor;
  7392. bool result = decompressor.decompress(
  7393. compressed_data.data(), compressed_data.size(),
  7394. [&](const char *decompressed_data_chunk,
  7395. size_t decompressed_data_chunk_size) {
  7396. decompressed_data.insert(decompressed_data.size(),
  7397. decompressed_data_chunk,
  7398. decompressed_data_chunk_size);
  7399. return true;
  7400. });
  7401. ASSERT_TRUE(result);
  7402. }
  7403. ASSERT_EQ(original_text, decompressed_data);
  7404. }
  7405. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7406. std::string original_text = "Raw deflate without gzip";
  7407. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7408. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7409. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7410. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7411. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7412. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7413. std::string decompressed_data;
  7414. {
  7415. httplib::detail::gzip_decompressor decompressor;
  7416. bool result = decompressor.decompress(
  7417. compressed_data.data(), compressed_data.size(),
  7418. [&](const char *decompressed_data_chunk,
  7419. size_t decompressed_data_chunk_size) {
  7420. decompressed_data.insert(decompressed_data.size(),
  7421. decompressed_data_chunk,
  7422. decompressed_data_chunk_size);
  7423. return true;
  7424. });
  7425. ASSERT_TRUE(result);
  7426. }
  7427. ASSERT_EQ(original_text, decompressed_data);
  7428. }
  7429. #endif
  7430. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7431. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7432. Headers headers;
  7433. headers.emplace("Accept-Encoding", "br");
  7434. auto res = cli_.Get("/streamed-chunked", headers);
  7435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7436. EXPECT_EQ(StatusCode::OK_200, res->status);
  7437. EXPECT_EQ(std::string("123456789"), res->body);
  7438. }
  7439. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7440. Headers headers;
  7441. headers.emplace("Accept-Encoding", "br");
  7442. auto res = cli_.Get("/streamed-chunked2", headers);
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. EXPECT_EQ(std::string("123456789"), res->body);
  7446. }
  7447. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7448. cli_.set_compress(true);
  7449. auto res = cli_.Put(
  7450. "/put", 3,
  7451. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7452. sink.os << "PUT";
  7453. return true;
  7454. },
  7455. "text/plain");
  7456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7457. EXPECT_EQ(StatusCode::OK_200, res->status);
  7458. EXPECT_EQ("PUT", res->body);
  7459. }
  7460. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7461. cli_.set_compress(true);
  7462. auto res = cli_.Put(
  7463. "/put",
  7464. [](size_t /*offset*/, DataSink &sink) {
  7465. sink.os << "PUT";
  7466. sink.done();
  7467. return true;
  7468. },
  7469. "text/plain");
  7470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7471. EXPECT_EQ(StatusCode::OK_200, res->status);
  7472. EXPECT_EQ("PUT", res->body);
  7473. }
  7474. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7475. cli_.set_compress(true);
  7476. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::OK_200, res->status);
  7479. EXPECT_EQ(LARGE_DATA, res->body);
  7480. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7481. }
  7482. #endif
  7483. TEST_F(ServerTest, Patch) {
  7484. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. EXPECT_EQ("PATCH", res->body);
  7488. }
  7489. TEST_F(ServerTest, Delete) {
  7490. auto res = cli_.Delete("/delete");
  7491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7492. EXPECT_EQ(StatusCode::OK_200, res->status);
  7493. EXPECT_EQ("DELETE", res->body);
  7494. }
  7495. TEST_F(ServerTest, DeleteContentReceiver) {
  7496. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::OK_200, res->status);
  7499. EXPECT_EQ("content", res->body);
  7500. }
  7501. TEST_F(ServerTest, Options) {
  7502. auto res = cli_.Options("*");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7506. EXPECT_TRUE(res->body.empty());
  7507. }
  7508. TEST_F(ServerTest, URL) {
  7509. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. TEST_F(ServerTest, ArrayParam) {
  7514. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. }
  7518. TEST_F(ServerTest, ArrayParamValues) {
  7519. auto res =
  7520. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(StatusCode::OK_200, res->status);
  7523. }
  7524. TEST_F(ServerTest, NoMultipleHeaders) {
  7525. Headers headers = {{"Content-Length", "5"}};
  7526. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7527. "text/plain");
  7528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7529. EXPECT_EQ(StatusCode::OK_200, res->status);
  7530. }
  7531. TEST_F(ServerTest, PostContentReceiver) {
  7532. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. ASSERT_EQ(StatusCode::OK_200, res->status);
  7535. ASSERT_EQ("content", res->body);
  7536. }
  7537. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7538. UploadFormDataItems items = {
  7539. {"text1", "text default", "", ""},
  7540. {"text2", "aωb", "", ""},
  7541. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7542. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7543. {"file3", "", "", "application/octet-stream"},
  7544. };
  7545. auto res = cli_.Post("/content_receiver", items);
  7546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7547. EXPECT_EQ(StatusCode::OK_200, res->status);
  7548. }
  7549. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7550. UploadFormDataItems items = {
  7551. {"text1", "text default", "", ""},
  7552. {"text2", "aωb", "", ""},
  7553. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7554. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7555. {"file3", "", "", "application/octet-stream"},
  7556. };
  7557. auto boundary = std::string("+++++");
  7558. std::string body;
  7559. for (const auto &item : items) {
  7560. body += "--" + boundary + "\r\n";
  7561. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7562. if (!item.filename.empty()) {
  7563. body += "; filename=\"" + item.filename + "\"";
  7564. }
  7565. body += "\r\n";
  7566. if (!item.content_type.empty()) {
  7567. body += "Content-Type: " + item.content_type + "\r\n";
  7568. }
  7569. body += "\r\n";
  7570. body += item.content + "\r\n";
  7571. }
  7572. body += "--" + boundary + "--\r\n";
  7573. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7574. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7576. EXPECT_EQ(StatusCode::OK_200, res->status);
  7577. }
  7578. TEST(MultipartFormDataTest, FieldEscaping) {
  7579. Server svr;
  7580. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7581. const ContentReader &content_reader) {
  7582. ASSERT_TRUE(req.is_multipart_form_data());
  7583. std::vector<FormData> received;
  7584. content_reader(
  7585. [&](const FormData &file) {
  7586. received.push_back(file);
  7587. return true;
  7588. },
  7589. [&](const char *data, size_t data_length) {
  7590. received.back().content.append(data, data_length);
  7591. return true;
  7592. });
  7593. // '"', CR and LF in names and filenames are escaped following the
  7594. // WHATWG HTML standard, so each part still parses as a single part
  7595. // with no injected headers. Content types get CR/LF escaped too,
  7596. // while '"' (legal there, e.g. quoted charset) is preserved.
  7597. ASSERT_EQ(4U, received.size());
  7598. EXPECT_EQ("na%22me", received[0].name);
  7599. EXPECT_EQ("quoted name", received[0].content);
  7600. EXPECT_EQ("file", received[1].name);
  7601. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7602. received[1].filename);
  7603. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7604. EXPECT_EQ("injected", received[1].content);
  7605. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7606. EXPECT_EQ("my%22file.txt", received[2].filename);
  7607. EXPECT_EQ("cr lf name", received[2].content);
  7608. EXPECT_EQ("typed", received[3].name);
  7609. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7610. received[3].content_type);
  7611. EXPECT_EQ("typed content", received[3].content);
  7612. });
  7613. auto port = svr.bind_to_any_port("localhost");
  7614. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7615. auto se = detail::scope_exit([&] {
  7616. svr.stop();
  7617. t.join();
  7618. ASSERT_FALSE(svr.is_running());
  7619. });
  7620. svr.wait_until_ready();
  7621. Client cli("localhost", port);
  7622. UploadFormDataItems items = {
  7623. {"na\"me", "quoted name", "", ""},
  7624. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7625. "application/octet-stream"},
  7626. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7627. {"typed", "typed content", "",
  7628. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7629. };
  7630. auto res = cli.Post("/post", items);
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. EXPECT_EQ(StatusCode::OK_200, res->status);
  7633. }
  7634. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7635. const UploadFormDataItems items = {
  7636. {"name1", "Content 1", "", ""},
  7637. {"name2", "Content 2", "file2.txt", "text/plain"},
  7638. };
  7639. Server svr;
  7640. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7641. const ContentReader &content_reader) {
  7642. ASSERT_TRUE(req.is_multipart_form_data());
  7643. std::vector<FormData> received;
  7644. content_reader(
  7645. [&](const FormData &file) {
  7646. received.push_back(file);
  7647. return true;
  7648. },
  7649. [&](const char *data, size_t data_length) {
  7650. received.back().content.append(data, data_length);
  7651. return true;
  7652. });
  7653. ASSERT_EQ(2U, received.size());
  7654. EXPECT_EQ("name1", received[0].name);
  7655. EXPECT_EQ("Content 1", received[0].content);
  7656. EXPECT_EQ("name2", received[1].name);
  7657. EXPECT_EQ("Content 2", received[1].content);
  7658. EXPECT_EQ("file2.txt", received[1].filename);
  7659. EXPECT_EQ("text/plain", received[1].content_type);
  7660. });
  7661. auto port = svr.bind_to_any_port("localhost");
  7662. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7663. auto se = detail::scope_exit([&] {
  7664. svr.stop();
  7665. t.join();
  7666. ASSERT_FALSE(svr.is_running());
  7667. });
  7668. svr.wait_until_ready();
  7669. Client cli("localhost", port);
  7670. // Whole-body serialization with a generated boundary
  7671. {
  7672. MultipartFormDataWriter writer;
  7673. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7674. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7675. writer.content_type());
  7676. auto body = writer.serialize(items);
  7677. EXPECT_EQ(body.size(), writer.content_length(items));
  7678. auto res = cli.Post("/post", body, writer.content_type());
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. }
  7682. // Per-part framing with a custom boundary via a content provider
  7683. {
  7684. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7685. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7686. MultipartFormDataWriter writer("custom-boundary_123");
  7687. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7688. std::string body;
  7689. for (const auto &item : items) {
  7690. body += writer.item_begin(item);
  7691. body += item.content;
  7692. body += MultipartFormDataWriter::item_end();
  7693. }
  7694. body += writer.finish();
  7695. EXPECT_EQ(body.size(), writer.content_length(items));
  7696. auto res = cli.Post(
  7697. "/post", body.size(),
  7698. [&](size_t offset, size_t length, DataSink &sink) {
  7699. sink.write(body.data() + offset, length);
  7700. return true;
  7701. },
  7702. writer.content_type());
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. }
  7706. }
  7707. TEST_F(ServerTest, PostContentReceiverGzip) {
  7708. cli_.set_compress(true);
  7709. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. ASSERT_EQ(StatusCode::OK_200, res->status);
  7712. ASSERT_EQ("content", res->body);
  7713. }
  7714. TEST_F(ServerTest, PutContentReceiver) {
  7715. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. ASSERT_EQ(StatusCode::OK_200, res->status);
  7718. ASSERT_EQ("content", res->body);
  7719. }
  7720. TEST_F(ServerTest, PatchContentReceiver) {
  7721. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7723. ASSERT_EQ(StatusCode::OK_200, res->status);
  7724. ASSERT_EQ("content", res->body);
  7725. }
  7726. template <typename ClientType>
  7727. void TestWithHeadersAndContentReceiver(
  7728. ClientType &cli,
  7729. std::function<Result(ClientType &, const std::string &, const Headers &,
  7730. const std::string &, const std::string &,
  7731. ContentReceiver, DownloadProgress)>
  7732. request_func) {
  7733. Headers headers;
  7734. headers.emplace("X-Custom-Header", "test-value");
  7735. std::string received_body;
  7736. auto res = request_func(
  7737. cli, "/content_receiver", headers, "content", "application/json",
  7738. [&](const char *data, size_t data_length) {
  7739. received_body.append(data, data_length);
  7740. return true;
  7741. },
  7742. nullptr);
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("content", received_body);
  7746. }
  7747. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7748. #ifdef CPPHTTPLIB_SSL_ENABLED
  7749. using ClientT = SSLClient;
  7750. #else
  7751. using ClientT = Client;
  7752. #endif
  7753. TestWithHeadersAndContentReceiver<ClientT>(
  7754. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7755. const std::string &body, const std::string &content_type,
  7756. ContentReceiver receiver, DownloadProgress progress) {
  7757. return cli.Post(path, headers, body, content_type, receiver, progress);
  7758. });
  7759. }
  7760. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7761. #ifdef CPPHTTPLIB_SSL_ENABLED
  7762. using ClientT = SSLClient;
  7763. #else
  7764. using ClientT = Client;
  7765. #endif
  7766. TestWithHeadersAndContentReceiver<ClientT>(
  7767. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7768. const std::string &body, const std::string &content_type,
  7769. ContentReceiver receiver, DownloadProgress progress) {
  7770. return cli.Put(path, headers, body, content_type, receiver, progress);
  7771. });
  7772. }
  7773. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7774. #ifdef CPPHTTPLIB_SSL_ENABLED
  7775. using ClientT = SSLClient;
  7776. #else
  7777. using ClientT = Client;
  7778. #endif
  7779. TestWithHeadersAndContentReceiver<ClientT>(
  7780. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7781. const std::string &body, const std::string &content_type,
  7782. ContentReceiver receiver, DownloadProgress progress) {
  7783. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7784. });
  7785. }
  7786. template <typename ClientType>
  7787. void TestWithHeadersAndContentReceiverWithProgress(
  7788. ClientType &cli,
  7789. std::function<Result(ClientType &, const std::string &, const Headers &,
  7790. const std::string &, const std::string &,
  7791. ContentReceiver, DownloadProgress)>
  7792. request_func) {
  7793. Headers headers;
  7794. headers.emplace("X-Test-Header", "progress-test");
  7795. std::string received_body;
  7796. auto progress_called = false;
  7797. auto res = request_func(
  7798. cli, "/content_receiver", headers, "content", "text/plain",
  7799. [&](const char *data, size_t data_length) {
  7800. received_body.append(data, data_length);
  7801. return true;
  7802. },
  7803. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7804. progress_called = true;
  7805. return true;
  7806. });
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::OK_200, res->status);
  7809. EXPECT_EQ("content", received_body);
  7810. EXPECT_TRUE(progress_called);
  7811. }
  7812. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7813. #ifdef CPPHTTPLIB_SSL_ENABLED
  7814. using ClientT = SSLClient;
  7815. #else
  7816. using ClientT = Client;
  7817. #endif
  7818. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7819. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7820. const std::string &body, const std::string &content_type,
  7821. ContentReceiver receiver, DownloadProgress progress) {
  7822. return cli.Post(path, headers, body, content_type, receiver, progress);
  7823. });
  7824. }
  7825. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7826. #ifdef CPPHTTPLIB_SSL_ENABLED
  7827. using ClientT = SSLClient;
  7828. #else
  7829. using ClientT = Client;
  7830. #endif
  7831. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7832. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7833. const std::string &body, const std::string &content_type,
  7834. ContentReceiver receiver, DownloadProgress progress) {
  7835. return cli.Put(path, headers, body, content_type, receiver, progress);
  7836. });
  7837. }
  7838. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7839. #ifdef CPPHTTPLIB_SSL_ENABLED
  7840. using ClientT = SSLClient;
  7841. #else
  7842. using ClientT = Client;
  7843. #endif
  7844. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7845. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7846. const std::string &body, const std::string &content_type,
  7847. ContentReceiver receiver, DownloadProgress progress) {
  7848. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7849. });
  7850. }
  7851. template <typename ClientType>
  7852. void TestWithHeadersAndContentReceiverError(
  7853. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7854. const Headers &, const std::string &,
  7855. const std::string &, ContentReceiver)>
  7856. request_func) {
  7857. Headers headers;
  7858. headers.emplace("X-Error-Test", "true");
  7859. std::string received_body;
  7860. auto receiver_failed = false;
  7861. auto res =
  7862. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7863. [&](const char *data, size_t data_length) {
  7864. received_body.append(data, data_length);
  7865. receiver_failed = true;
  7866. return false;
  7867. });
  7868. ASSERT_FALSE(res);
  7869. EXPECT_TRUE(receiver_failed);
  7870. }
  7871. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7872. #ifdef CPPHTTPLIB_SSL_ENABLED
  7873. using ClientT = SSLClient;
  7874. #else
  7875. using ClientT = Client;
  7876. #endif
  7877. TestWithHeadersAndContentReceiverError<ClientT>(
  7878. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7879. const std::string &body, const std::string &content_type,
  7880. ContentReceiver receiver) {
  7881. return cli.Post(path, headers, body, content_type, receiver);
  7882. });
  7883. }
  7884. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7885. #ifdef CPPHTTPLIB_SSL_ENABLED
  7886. using ClientT = SSLClient;
  7887. #else
  7888. using ClientT = Client;
  7889. #endif
  7890. TestWithHeadersAndContentReceiverError<ClientT>(
  7891. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7892. const std::string &body, const std::string &content_type,
  7893. ContentReceiver receiver) {
  7894. return cli.Put(path, headers, body, content_type, receiver);
  7895. });
  7896. }
  7897. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7898. #ifdef CPPHTTPLIB_SSL_ENABLED
  7899. using ClientT = SSLClient;
  7900. #else
  7901. using ClientT = Client;
  7902. #endif
  7903. TestWithHeadersAndContentReceiverError<ClientT>(
  7904. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7905. const std::string &body, const std::string &content_type,
  7906. ContentReceiver receiver) {
  7907. return cli.Patch(path, headers, body, content_type, receiver);
  7908. });
  7909. }
  7910. TEST_F(ServerTest, PostQueryStringAndBody) {
  7911. auto res =
  7912. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. ASSERT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. TEST_F(ServerTest, HTTP2Magic) {
  7917. Request req;
  7918. req.method = "PRI";
  7919. req.path = "*";
  7920. req.body = "SM";
  7921. auto res = std::make_shared<Response>();
  7922. auto error = Error::Success;
  7923. auto ret = cli_.send(req, *res, error);
  7924. ASSERT_TRUE(ret);
  7925. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7926. }
  7927. TEST_F(ServerTest, KeepAlive) {
  7928. auto res = cli_.Get("/hi");
  7929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7930. EXPECT_EQ(StatusCode::OK_200, res->status);
  7931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7932. EXPECT_EQ("Hello World!", res->body);
  7933. res = cli_.Get("/hi");
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7937. EXPECT_EQ("Hello World!", res->body);
  7938. res = cli_.Get("/hi");
  7939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7942. EXPECT_EQ("Hello World!", res->body);
  7943. res = cli_.Get("/not-exist");
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7946. res = cli_.Post("/empty", "", "text/plain");
  7947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7950. EXPECT_EQ("empty", res->body);
  7951. EXPECT_EQ("close", res->get_header_value("Connection"));
  7952. res = cli_.Post(
  7953. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7954. "text/plain");
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7958. EXPECT_EQ("empty", res->body);
  7959. cli_.set_keep_alive(false);
  7960. res = cli_.Get("/last-request");
  7961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7962. EXPECT_EQ(StatusCode::OK_200, res->status);
  7963. EXPECT_EQ("close", res->get_header_value("Connection"));
  7964. }
  7965. TEST_F(ServerTest, TooManyRedirect) {
  7966. cli_.set_follow_location(true);
  7967. auto res = cli_.Get("/redirect/0");
  7968. ASSERT_TRUE(!res);
  7969. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7970. }
  7971. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7972. Request req;
  7973. req.method = "FOOBAR";
  7974. req.path = "/hi";
  7975. cli_.set_keep_alive(true);
  7976. auto res = cli_.send(req);
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7979. EXPECT_EQ("close", res->get_header_value("Connection"));
  7980. EXPECT_FALSE(cli_.is_socket_open());
  7981. }
  7982. TEST_F(ServerTest, CustomRouteReadsBody) {
  7983. const std::string xml =
  7984. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7985. Request req;
  7986. req.method = "PROPFIND";
  7987. req.path = "/dav/dir";
  7988. req.set_header("Depth", "1");
  7989. req.body = xml;
  7990. auto res = cli_.send(req);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7993. EXPECT_EQ(xml, res->body);
  7994. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7995. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7996. }
  7997. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7998. Request req;
  7999. req.method = "PROPFIND";
  8000. req.path = "/dav/42";
  8001. auto res = cli_.send(req);
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8004. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8005. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8006. }
  8007. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8008. Request req;
  8009. req.method = "PROPFIND";
  8010. req.path = "/dav-re/123";
  8011. auto res = cli_.send(req);
  8012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8013. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8014. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8015. }
  8016. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8017. Request req;
  8018. req.method = "MKCOL";
  8019. req.path = "/dav-mkcol";
  8020. auto res = cli_.send(req);
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. EXPECT_EQ(StatusCode::Created_201, res->status);
  8023. }
  8024. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8025. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8026. Request req;
  8027. req.method = "REPORT";
  8028. req.path = "/dav-report";
  8029. req.body = xml;
  8030. auto res = cli_.send(req);
  8031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8032. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8033. EXPECT_EQ(xml, res->body);
  8034. }
  8035. // A content reader route must fire even when the request carries no body,
  8036. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8037. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8038. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8039. Request req;
  8040. req.method = "REPORT";
  8041. req.path = "/dav-report";
  8042. auto res = cli_.send(req);
  8043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8044. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8045. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8046. }
  8047. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8048. Request req;
  8049. req.method = "PROPFIND";
  8050. req.path = "/not-dav";
  8051. auto res = cli_.send(req);
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8054. }
  8055. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8056. Request req;
  8057. req.method = "UNLOCK";
  8058. req.path = "/dav/dir";
  8059. cli_.set_keep_alive(true);
  8060. auto res = cli_.send(req);
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8063. EXPECT_EQ("close", res->get_header_value("Connection"));
  8064. EXPECT_FALSE(cli_.is_socket_open());
  8065. }
  8066. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8067. // The mount point serves this path, but only for GET and HEAD.
  8068. auto get_res = cli_.Get("/dir/index.html");
  8069. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8070. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8071. Request req;
  8072. req.method = "PROPFIND";
  8073. req.path = "/dir/index.html";
  8074. auto res = cli_.send(req);
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8077. }
  8078. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8079. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8080. cli_.set_keep_alive(true);
  8081. for (auto i = 0; i < 2; i++) {
  8082. Request req;
  8083. req.method = "PROPFIND";
  8084. req.path = "/dav/dir";
  8085. req.body = xml;
  8086. auto res = cli_.send(req);
  8087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8088. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8089. EXPECT_EQ(xml, res->body);
  8090. EXPECT_TRUE(cli_.is_socket_open());
  8091. }
  8092. // A built-in method must still be served on the same connection.
  8093. cli_.set_keep_alive(false);
  8094. auto res = cli_.Get("/hi");
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. EXPECT_EQ("close", res->get_header_value("Connection"));
  8098. }
  8099. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8100. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8101. Request req;
  8102. req.method = "PROPFIND";
  8103. req.path = "/dav/dir";
  8104. req.set_header("Expect", "100-continue");
  8105. req.body = xml;
  8106. auto res = cli_.send(req);
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8109. EXPECT_EQ(xml, res->body);
  8110. }
  8111. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8112. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8113. TEST_F(ServerTest, Gzip) {
  8114. Headers headers;
  8115. headers.emplace("Accept-Encoding", "gzip, deflate");
  8116. auto res = cli_.Get("/compress", headers);
  8117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8118. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8120. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8121. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8122. "7890123456789012345678901234567890",
  8123. res->body);
  8124. EXPECT_EQ(StatusCode::OK_200, res->status);
  8125. }
  8126. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8127. Headers headers;
  8128. headers.emplace("Accept-Encoding", "gzip, deflate");
  8129. auto res = cli_.Get("/compress-with-charset", headers);
  8130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8131. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8132. EXPECT_EQ("application/json; charset=utf-8",
  8133. res->get_header_value("Content-Type"));
  8134. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8135. "7890123456789012345678901234567890",
  8136. res->body);
  8137. EXPECT_EQ(StatusCode::OK_200, res->status);
  8138. }
  8139. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8140. Headers headers;
  8141. headers.emplace("Accept-Encoding", "");
  8142. auto res = cli_.Get("/compress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8146. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8147. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8148. "7890123456789012345678901234567890",
  8149. res->body);
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. }
  8152. TEST_F(ServerTest, GzipWithContentReceiver) {
  8153. Headers headers;
  8154. headers.emplace("Accept-Encoding", "gzip, deflate");
  8155. std::string body;
  8156. auto res = cli_.Get("/compress", headers,
  8157. [&](const char *data, uint64_t data_length) {
  8158. EXPECT_EQ(100U, data_length);
  8159. body.append(data, data_length);
  8160. return true;
  8161. });
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8165. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8166. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8167. "7890123456789012345678901234567890",
  8168. body);
  8169. EXPECT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip, deflate");
  8174. cli_.set_decompress(false);
  8175. auto res = cli_.Get("/compress", headers);
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8179. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8180. EXPECT_EQ(33U, res->body.size());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. }
  8183. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8184. Headers headers;
  8185. headers.emplace("Accept-Encoding", "");
  8186. std::string body;
  8187. auto res = cli_.Get("/compress", headers,
  8188. [&](const char *data, uint64_t data_length) {
  8189. EXPECT_EQ(100U, data_length);
  8190. body.append(data, data_length);
  8191. return true;
  8192. });
  8193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8194. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8195. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8196. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8197. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8198. "7890123456789012345678901234567890",
  8199. body);
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. }
  8202. TEST_F(ServerTest, NoGzip) {
  8203. Headers headers;
  8204. headers.emplace("Accept-Encoding", "gzip, deflate");
  8205. auto res = cli_.Get("/nocompress", headers);
  8206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8207. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8208. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8209. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8210. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8211. "7890123456789012345678901234567890",
  8212. res->body);
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. }
  8215. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8216. Headers headers;
  8217. headers.emplace("Accept-Encoding", "gzip, deflate");
  8218. std::string body;
  8219. auto res = cli_.Get("/nocompress", headers,
  8220. [&](const char *data, uint64_t data_length) {
  8221. EXPECT_EQ(100U, data_length);
  8222. body.append(data, data_length);
  8223. return true;
  8224. });
  8225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8226. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8227. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8228. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8230. "7890123456789012345678901234567890",
  8231. body);
  8232. EXPECT_EQ(StatusCode::OK_200, res->status);
  8233. }
  8234. TEST_F(ServerTest, MultipartFormDataGzip) {
  8235. UploadFormDataItems items = {
  8236. {"key1", "test", "", ""},
  8237. {"key2", "--abcdefg123", "", ""},
  8238. };
  8239. cli_.set_compress(true);
  8240. auto res = cli_.Post("/compress-multipart", items);
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::OK_200, res->status);
  8243. }
  8244. #endif
  8245. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8246. // Static file compression is opt-in, so these run their own server rather than
  8247. // flipping it on for the shared ServerTest fixture, which would silently
  8248. // rewrite what every other static file test is asserting.
  8249. class StaticFileCompressionTest : public ::testing::Test {
  8250. protected:
  8251. void TearDown() override {
  8252. if (t_.joinable()) {
  8253. svr_.stop();
  8254. t_.join();
  8255. }
  8256. }
  8257. int start(const std::function<void(Server &)> &configure = nullptr) {
  8258. // Serves the same tree as a directory of build-time compressed assets
  8259. // would be served: the mount point names the coding the files are already
  8260. // stored in. Registered before "/" so it is the one that matches.
  8261. svr_.set_mount_point("/pre-encoded", "./www",
  8262. {{"Content-Encoding", "gzip"}});
  8263. svr_.set_mount_point("/", "./www");
  8264. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8265. res.set_file_content("./www/dir/index.html", "text/html");
  8266. });
  8267. svr_.Get("/pre-encoded-file-content",
  8268. [](const Request & /*req*/, Response &res) {
  8269. res.set_header("Content-Encoding", "gzip");
  8270. res.set_file_content("./www/dir/index.html", "text/html");
  8271. });
  8272. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8273. res.set_content_provider(
  8274. 6, "text/plain",
  8275. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8276. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8277. return true;
  8278. });
  8279. });
  8280. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8281. res.set_content_provider(
  8282. 1000, "text/plain",
  8283. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8284. if (offset < 100) {
  8285. std::string data(100, 'A');
  8286. sink.write(data.data(), data.size());
  8287. return true;
  8288. }
  8289. std::this_thread::sleep_for(std::chrono::seconds(2));
  8290. std::string data(900, 'B');
  8291. sink.write(data.data(), data.size());
  8292. return true;
  8293. });
  8294. });
  8295. if (configure) { configure(svr_); }
  8296. auto port = svr_.bind_to_any_port(HOST);
  8297. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8298. svr_.wait_until_ready();
  8299. return port;
  8300. }
  8301. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8302. // Every file under ./www except 1MB.txt is smaller than the default
  8303. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8304. // it out of the way.
  8305. static void enable_without_floor(Server &svr) {
  8306. svr.set_static_file_compression(true);
  8307. svr.set_static_file_compression_min_length(0);
  8308. }
  8309. Server svr_;
  8310. std::thread t_;
  8311. };
  8312. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8313. auto port = start();
  8314. Client cli(HOST, port);
  8315. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8319. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8320. EXPECT_EQ(1048576U, res->body.size());
  8321. }
  8322. TEST_F(StaticFileCompressionTest, MountPoint) {
  8323. auto port = start(enable);
  8324. Client cli(HOST, port);
  8325. cli.set_decompress(false);
  8326. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::OK_200, res->status);
  8329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8330. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8331. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8332. // The response stays self-delimiting: a length, not a chunked body.
  8333. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8334. EXPECT_EQ(std::to_string(res->body.size()),
  8335. res->get_header_value("Content-Length"));
  8336. EXPECT_LT(res->body.size(), 1048576U);
  8337. EXPECT_FALSE(res->body.empty());
  8338. }
  8339. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8340. auto port = start(enable);
  8341. Client cli(HOST, port);
  8342. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::OK_200, res->status);
  8345. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8346. EXPECT_EQ(1048576U, res->body.size());
  8347. }
  8348. TEST_F(StaticFileCompressionTest, FileContent) {
  8349. auto port = start(enable_without_floor);
  8350. Client cli(HOST, port);
  8351. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(StatusCode::OK_200, res->status);
  8354. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8355. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8356. EXPECT_EQ(104U, res->body.size());
  8357. }
  8358. // A handler that serves an already-encoded file names the coding itself. The
  8359. // file-backed path decided its coding from Accept-Encoding and the content
  8360. // type alone, so it compressed the stored bytes a second time and appended a
  8361. // second Content-Encoding field line.
  8362. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8363. auto port = start(enable_without_floor);
  8364. Client cli(HOST, port);
  8365. cli.set_decompress(false);
  8366. auto res = cli.Get("/pre-encoded-file-content",
  8367. Headers{{"Accept-Encoding", "gzip"}});
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. // Vary belongs to a coding the server chose, and it chose none here.
  8373. EXPECT_FALSE(res->has_header("Vary"));
  8374. // The file travels exactly as it is stored on disk.
  8375. EXPECT_EQ(104U, res->body.size());
  8376. }
  8377. // The 1MB file clears the default floor, so this one runs the configuration a
  8378. // deployment would actually have.
  8379. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8380. auto port = start(enable);
  8381. Client cli(HOST, port);
  8382. cli.set_decompress(false);
  8383. auto res =
  8384. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8386. EXPECT_EQ(StatusCode::OK_200, res->status);
  8387. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8388. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8389. EXPECT_FALSE(res->has_header("Vary"));
  8390. EXPECT_EQ(1048576U, res->body.size());
  8391. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8392. }
  8393. TEST_F(StaticFileCompressionTest, Head) {
  8394. auto port = start(enable);
  8395. Client cli(HOST, port);
  8396. cli.set_decompress(false);
  8397. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8398. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8399. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8403. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8404. // HEAD still reports the size a GET would return.
  8405. EXPECT_EQ(get->get_header_value("Content-Length"),
  8406. res->get_header_value("Content-Length"));
  8407. EXPECT_TRUE(res->body.empty());
  8408. }
  8409. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8410. auto port = start(enable);
  8411. Client cli(HOST, port);
  8412. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8413. {"Accept-Encoding", "gzip"}});
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8416. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8417. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8419. EXPECT_EQ("cd", res->body);
  8420. }
  8421. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8422. auto port = start(enable);
  8423. Client cli(HOST, port);
  8424. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::OK_200, res->status);
  8427. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8428. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8429. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8430. }
  8431. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8432. auto port = start(enable);
  8433. Client cli(HOST, port);
  8434. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8438. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8439. EXPECT_TRUE(res->body.empty());
  8440. }
  8441. TEST_F(StaticFileCompressionTest, MinLength) {
  8442. auto port = start(enable);
  8443. Client cli(HOST, port);
  8444. // 104 bytes, well under the default floor. Compressing it would add the
  8445. // gzip header and trailer to a body that already fits in one packet.
  8446. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8450. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8451. }
  8452. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8453. auto port = start([](Server &svr) {
  8454. svr.set_static_file_compression(true);
  8455. svr.set_static_file_compression_min_length(1);
  8456. });
  8457. Client cli(HOST, port);
  8458. cli.set_decompress(false);
  8459. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8461. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8462. // A 9-byte file comes back larger than it went in, because gzip's header and
  8463. // trailer outweigh anything deflate can save. That is the end of the range
  8464. // the floor exists to keep out.
  8465. EXPECT_GT(res->body.size(), 9U);
  8466. }
  8467. TEST_F(StaticFileCompressionTest, MaxLength) {
  8468. auto port = start([](Server &svr) {
  8469. svr.set_static_file_compression(true);
  8470. svr.set_static_file_compression_min_length(0);
  8471. svr.set_static_file_compression_max_length(1024);
  8472. });
  8473. Client cli(HOST, port);
  8474. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8475. // defines `small` as a macro on Windows.
  8476. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8477. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8478. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8479. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8480. // Under it: compressed.
  8481. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8482. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8483. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8484. }
  8485. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8486. auto port = start(enable_without_floor);
  8487. Client cli(HOST, port);
  8488. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8489. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8490. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8491. auto identity_etag = identity->get_header_value("ETag");
  8492. ASSERT_FALSE(identity_etag.empty());
  8493. auto gzipped =
  8494. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8495. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8496. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8497. auto gzip_etag = gzipped->get_header_value("ETag");
  8498. ASSERT_FALSE(gzip_etag.empty());
  8499. // Two representations, two validators.
  8500. EXPECT_NE(identity_etag, gzip_etag);
  8501. // Each one revalidates against the request that would produce it...
  8502. auto fresh =
  8503. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8504. {"If-None-Match", gzip_etag}});
  8505. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8506. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8507. auto fresh_identity =
  8508. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8509. {"If-None-Match", identity_etag}});
  8510. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8511. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8512. // ...and not against the other representation.
  8513. auto crossed =
  8514. cli.Get("/dir/index.html",
  8515. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8516. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8517. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8518. }
  8519. // The opt-in covers responses the server reads off disk itself. A caller's own
  8520. // known-length provider keeps its Content-Length and, more importantly, keeps
  8521. // delivering incrementally: routing it through a compressor would hold every
  8522. // write back until zlib's window filled.
  8523. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8524. auto port = start(enable);
  8525. Client cli(HOST, port);
  8526. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8530. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8531. EXPECT_EQ("aaabbb", res->body);
  8532. }
  8533. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8534. auto port = start(enable);
  8535. Client cli(HOST, port);
  8536. cli.set_read_timeout(1, 0);
  8537. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8538. Headers{{"Accept-Encoding", "gzip"}});
  8539. ASSERT_TRUE(handle.is_valid());
  8540. // The provider writes 100 bytes and then stalls for longer than the read
  8541. // timeout. Those first bytes have to arrive anyway: run the response through
  8542. // a compressor and zlib holds them until its window fills, so the read would
  8543. // come back empty instead.
  8544. char buf[256];
  8545. auto n = handle.read(buf, sizeof(buf));
  8546. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8547. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8548. }
  8549. #endif
  8550. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8551. TEST_F(ServerTest, Brotli) {
  8552. Headers headers;
  8553. headers.emplace("Accept-Encoding", "br");
  8554. auto res = cli_.Get("/compress", headers);
  8555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8556. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8558. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8559. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8560. "7890123456789012345678901234567890",
  8561. res->body);
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. }
  8564. #endif
  8565. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8566. TEST_F(ServerTest, Zstd) {
  8567. Headers headers;
  8568. headers.emplace("Accept-Encoding", "zstd");
  8569. auto res = cli_.Get("/compress", headers);
  8570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8571. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8572. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8573. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8574. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8575. "7890123456789012345678901234567890",
  8576. res->body);
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. }
  8579. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8580. Headers headers;
  8581. headers.emplace("Accept-Encoding", "");
  8582. auto res = cli_.Get("/compress", headers);
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8586. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8587. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8588. "7890123456789012345678901234567890",
  8589. res->body);
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. }
  8592. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8593. Headers headers;
  8594. headers.emplace("Accept-Encoding", "zstd");
  8595. std::string body;
  8596. auto res = cli_.Get("/compress", headers,
  8597. [&](const char *data, uint64_t data_length) {
  8598. EXPECT_EQ(100U, data_length);
  8599. body.append(data, data_length);
  8600. return true;
  8601. });
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8605. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8606. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8607. "7890123456789012345678901234567890",
  8608. body);
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. }
  8611. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8612. Headers headers;
  8613. headers.emplace("Accept-Encoding", "zstd");
  8614. cli_.set_decompress(false);
  8615. auto res = cli_.Get("/compress", headers);
  8616. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8617. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8618. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8619. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8623. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. ASSERT_EQ(26U, res->body.size());
  8626. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8627. 0);
  8628. }
  8629. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8630. Headers headers;
  8631. headers.emplace("Accept-Encoding", "");
  8632. std::string body;
  8633. auto res = cli_.Get("/compress", headers,
  8634. [&](const char *data, uint64_t data_length) {
  8635. EXPECT_EQ(100U, data_length);
  8636. body.append(data, data_length);
  8637. return true;
  8638. });
  8639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8640. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8641. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8642. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8643. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8644. "7890123456789012345678901234567890",
  8645. body);
  8646. EXPECT_EQ(StatusCode::OK_200, res->status);
  8647. }
  8648. TEST_F(ServerTest, NoZstd) {
  8649. Headers headers;
  8650. headers.emplace("Accept-Encoding", "zstd");
  8651. auto res = cli_.Get("/nocompress", headers);
  8652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8653. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8654. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8655. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8656. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8657. "7890123456789012345678901234567890",
  8658. res->body);
  8659. EXPECT_EQ(StatusCode::OK_200, res->status);
  8660. }
  8661. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8662. Headers headers;
  8663. headers.emplace("Accept-Encoding", "zstd");
  8664. std::string body;
  8665. auto res = cli_.Get("/nocompress", headers,
  8666. [&](const char *data, uint64_t data_length) {
  8667. EXPECT_EQ(100U, data_length);
  8668. body.append(data, data_length);
  8669. return true;
  8670. });
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8673. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8674. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8675. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8676. "7890123456789012345678901234567890",
  8677. body);
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. }
  8680. // TODO: How to enable zstd ??
  8681. TEST_F(ServerTest, MultipartFormDataZstd) {
  8682. UploadFormDataItems items = {
  8683. {"key1", "test", "", ""},
  8684. {"key2", "--abcdefg123", "", ""},
  8685. };
  8686. Headers headers;
  8687. headers.emplace("Accept-Encoding", "zstd");
  8688. cli_.set_compress(true);
  8689. auto res = cli_.Post("/compress-multipart", headers, items);
  8690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8691. EXPECT_EQ(StatusCode::OK_200, res->status);
  8692. }
  8693. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8694. Headers headers;
  8695. headers.emplace("Accept-Encoding", "zstd");
  8696. cli_.set_compress(true);
  8697. auto res = cli_.Put(
  8698. "/put", headers, 3,
  8699. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8700. sink.os << "PUT";
  8701. return true;
  8702. },
  8703. "text/plain");
  8704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8705. EXPECT_EQ(StatusCode::OK_200, res->status);
  8706. EXPECT_EQ("PUT", res->body);
  8707. }
  8708. // Pre-compression logging tests
  8709. TEST_F(ServerTest, PreCompressionLogging) {
  8710. // Test data for compression (matches the actual /compress endpoint content)
  8711. const std::string test_content =
  8712. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8713. "3456789012345678901234567890";
  8714. // Variables to capture logging data
  8715. std::string pre_compression_body;
  8716. std::string pre_compression_content_type;
  8717. std::string pre_compression_content_encoding;
  8718. std::string post_compression_body;
  8719. std::string post_compression_content_type;
  8720. std::string post_compression_content_encoding;
  8721. // Set up pre-compression logger
  8722. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8723. const Response &res) {
  8724. pre_compression_body = res.body;
  8725. pre_compression_content_type = res.get_header_value("Content-Type");
  8726. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8727. });
  8728. // Set up post-compression logger
  8729. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8730. post_compression_body = res.body;
  8731. post_compression_content_type = res.get_header_value("Content-Type");
  8732. post_compression_content_encoding =
  8733. res.get_header_value("Content-Encoding");
  8734. });
  8735. // Test with gzip compression
  8736. Headers headers;
  8737. headers.emplace("Accept-Encoding", "gzip");
  8738. auto res = cli_.Get("/compress", headers);
  8739. // Verify response was compressed
  8740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8741. EXPECT_EQ(StatusCode::OK_200, res->status);
  8742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8743. // Verify pre-compression logger captured uncompressed content
  8744. EXPECT_EQ(test_content, pre_compression_body);
  8745. EXPECT_EQ("text/plain", pre_compression_content_type);
  8746. EXPECT_TRUE(pre_compression_content_encoding
  8747. .empty()); // No encoding header before compression
  8748. // Verify post-compression logger captured compressed content
  8749. EXPECT_NE(test_content,
  8750. post_compression_body); // Should be different after compression
  8751. EXPECT_EQ("text/plain", post_compression_content_type);
  8752. EXPECT_EQ("gzip", post_compression_content_encoding);
  8753. // Verify compressed content is smaller
  8754. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8755. }
  8756. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8757. const std::string test_content =
  8758. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8759. "3456789012345678901234567890";
  8760. std::string pre_compression_body;
  8761. std::string post_compression_body;
  8762. svr_.set_pre_compression_logger(
  8763. [&](const Request & /*req*/, const Response &res) {
  8764. pre_compression_body = res.body;
  8765. });
  8766. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8767. post_compression_body = res.body;
  8768. });
  8769. Headers headers;
  8770. headers.emplace("Accept-Encoding", "br");
  8771. auto res = cli_.Get("/compress", headers);
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8775. // Verify pre-compression content is uncompressed
  8776. EXPECT_EQ(test_content, pre_compression_body);
  8777. // Verify post-compression content is compressed
  8778. EXPECT_NE(test_content, post_compression_body);
  8779. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8780. }
  8781. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8782. const std::string test_content =
  8783. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8784. "3456789012345678901234567890";
  8785. std::string pre_compression_body;
  8786. std::string post_compression_body;
  8787. svr_.set_pre_compression_logger(
  8788. [&](const Request & /*req*/, const Response &res) {
  8789. pre_compression_body = res.body;
  8790. });
  8791. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8792. post_compression_body = res.body;
  8793. });
  8794. // Request without compression (use /nocompress endpoint)
  8795. Headers headers;
  8796. auto res = cli_.Get("/nocompress", headers);
  8797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8798. EXPECT_EQ(StatusCode::OK_200, res->status);
  8799. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8800. // Pre-compression logger should not be called when no compression is applied
  8801. EXPECT_TRUE(
  8802. pre_compression_body.empty()); // Pre-compression logger not called
  8803. EXPECT_EQ(
  8804. test_content,
  8805. post_compression_body); // Post-compression logger captures final content
  8806. }
  8807. TEST_F(ServerTest, LoggerSeesContentLength) {
  8808. size_t logged_content_length = 0;
  8809. std::string logged_content_length_header;
  8810. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8811. logged_content_length = res.content_length_;
  8812. logged_content_length_header = res.get_header_value("Content-Length");
  8813. });
  8814. auto res = cli_.Get("/nocompress");
  8815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8816. EXPECT_EQ(StatusCode::OK_200, res->status);
  8817. EXPECT_EQ(res->body.size(), logged_content_length);
  8818. EXPECT_EQ(std::to_string(logged_content_length),
  8819. logged_content_length_header);
  8820. }
  8821. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8822. const std::string test_content =
  8823. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8824. "3456789012345678901234567890";
  8825. std::string pre_compression_body;
  8826. bool pre_logger_called = false;
  8827. // Set only pre-compression logger
  8828. svr_.set_pre_compression_logger(
  8829. [&](const Request & /*req*/, const Response &res) {
  8830. pre_compression_body = res.body;
  8831. pre_logger_called = true;
  8832. });
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "gzip");
  8835. auto res = cli_.Get("/compress", headers);
  8836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8837. EXPECT_EQ(StatusCode::OK_200, res->status);
  8838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8839. // Verify pre-compression logger was called
  8840. EXPECT_TRUE(pre_logger_called);
  8841. EXPECT_EQ(test_content, pre_compression_body);
  8842. }
  8843. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8844. {
  8845. // Test with Expect: 100-continue header - success case
  8846. // Server returns 100 Continue, client sends body, server returns 200 OK
  8847. Request req;
  8848. req.method = "POST";
  8849. req.path = "/post-large";
  8850. req.set_header("Expect", "100-continue");
  8851. req.body = LARGE_DATA;
  8852. Response res;
  8853. auto error = Error::Success;
  8854. cli_.set_keep_alive(true);
  8855. auto ret = cli_.send(req, res, error);
  8856. EXPECT_TRUE(ret);
  8857. EXPECT_EQ(StatusCode::OK_200, res.status);
  8858. EXPECT_EQ(LARGE_DATA, res.body);
  8859. }
  8860. {
  8861. // Test with Expect: 100-continue header - error case
  8862. // Client should not send the body when server returns an error
  8863. Request req;
  8864. req.method = "POST";
  8865. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8866. req.set_header("Expect", "100-continue");
  8867. req.body = LARGE_DATA;
  8868. Response res;
  8869. auto error = Error::Success;
  8870. auto start = std::chrono::high_resolution_clock::now();
  8871. cli_.set_keep_alive(true);
  8872. auto ret = cli_.send(req, res, error);
  8873. auto end = std::chrono::high_resolution_clock::now();
  8874. auto elapsed =
  8875. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8876. .count();
  8877. // With Expect: 100-continue, request completes successfully but with error
  8878. EXPECT_TRUE(ret);
  8879. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8880. EXPECT_EQ("close", res.get_header_value("Connection"));
  8881. EXPECT_FALSE(cli_.is_socket_open());
  8882. EXPECT_LE(elapsed, 2000);
  8883. }
  8884. {
  8885. // Send an extra GET request to ensure error recovery without hanging
  8886. Request req;
  8887. req.method = "GET";
  8888. req.path = "/hi";
  8889. auto start = std::chrono::high_resolution_clock::now();
  8890. auto res = cli_.send(req);
  8891. auto end = std::chrono::high_resolution_clock::now();
  8892. auto elapsed =
  8893. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8894. .count();
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_EQ(StatusCode::OK_200, res->status);
  8897. EXPECT_EQ("Hello World!", res->body);
  8898. EXPECT_LE(elapsed, 500);
  8899. }
  8900. }
  8901. TEST(ZstdDecompressor, ChunkedDecompression) {
  8902. std::string data;
  8903. for (size_t i = 0; i < 32 * 1024; ++i) {
  8904. data.push_back(static_cast<char>('a' + i % 26));
  8905. }
  8906. std::string compressed_data;
  8907. {
  8908. httplib::detail::zstd_compressor compressor;
  8909. bool result = compressor.compress(
  8910. data.data(), data.size(),
  8911. /*last=*/true,
  8912. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8913. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8914. compressed_data_size);
  8915. return true;
  8916. });
  8917. ASSERT_TRUE(result);
  8918. }
  8919. std::string decompressed_data;
  8920. {
  8921. httplib::detail::zstd_decompressor decompressor;
  8922. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8923. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8924. size_t chunk_size = 130;
  8925. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8926. chunk_begin += chunk_size) {
  8927. size_t current_chunk_size =
  8928. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8929. bool result = decompressor.decompress(
  8930. compressed_data.data() + chunk_begin, current_chunk_size,
  8931. [&](const char *decompressed_data_chunk,
  8932. size_t decompressed_data_chunk_size) {
  8933. decompressed_data.insert(decompressed_data.size(),
  8934. decompressed_data_chunk,
  8935. decompressed_data_chunk_size);
  8936. return true;
  8937. });
  8938. ASSERT_TRUE(result);
  8939. }
  8940. }
  8941. ASSERT_EQ(data, decompressed_data);
  8942. }
  8943. TEST(ZstdDecompressor, Decompress) {
  8944. std::string original_text = "Compressed with ZSTD";
  8945. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8946. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8947. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8948. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8949. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8950. std::string decompressed_data;
  8951. {
  8952. httplib::detail::zstd_decompressor decompressor;
  8953. bool result = decompressor.decompress(
  8954. compressed_data.data(), compressed_data.size(),
  8955. [&](const char *decompressed_data_chunk,
  8956. size_t decompressed_data_chunk_size) {
  8957. decompressed_data.insert(decompressed_data.size(),
  8958. decompressed_data_chunk,
  8959. decompressed_data_chunk_size);
  8960. return true;
  8961. });
  8962. ASSERT_TRUE(result);
  8963. }
  8964. ASSERT_EQ(original_text, decompressed_data);
  8965. }
  8966. #endif
  8967. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8968. // separate chunks so that the server sees each part in its own read(). Used to
  8969. // place a read boundary at a specific offset of a request body.
  8970. static bool send_request_in_parts(time_t read_timeout_sec,
  8971. const std::vector<std::string> &parts,
  8972. std::string *resp = nullptr,
  8973. int port = PORT) {
  8974. auto error = Error::Success;
  8975. auto client_sock = detail::create_client_socket(
  8976. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8977. /*connection_timeout_sec=*/5, 0,
  8978. /*read_timeout_sec=*/5, 0,
  8979. /*write_timeout_sec=*/5, 0, std::string(), error);
  8980. if (client_sock == INVALID_SOCKET) { return false; }
  8981. auto ret = detail::process_client_socket(
  8982. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8983. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8984. for (size_t i = 0; i < parts.size(); i++) {
  8985. const auto &part = parts[i];
  8986. if (part.size() !=
  8987. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8988. return false;
  8989. }
  8990. if (i + 1 < parts.size()) {
  8991. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8992. }
  8993. }
  8994. char buf[512];
  8995. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8996. while (line_reader.getline()) {
  8997. if (resp) { *resp += line_reader.ptr(); }
  8998. }
  8999. return true;
  9000. });
  9001. detail::close_socket(client_sock);
  9002. return ret;
  9003. }
  9004. // Sends a raw request to a server listening at HOST:PORT.
  9005. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9006. std::string *resp = nullptr, int port = PORT) {
  9007. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9008. }
  9009. #ifdef CPPHTTPLIB_SSL_ENABLED
  9010. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9012. ASSERT_TRUE(svr.is_valid());
  9013. svr.set_read_timeout(1, 0);
  9014. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9015. auto se = detail::scope_exit([&] {
  9016. svr.stop();
  9017. t.join();
  9018. ASSERT_FALSE(svr.is_running());
  9019. });
  9020. svr.wait_until_ready();
  9021. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9022. // keeps each wait well within the read timeout. The server gives up a
  9023. // second in, so the bytes sent after that fail.
  9024. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9025. parts.resize(26, std::string(1, '\0'));
  9026. EXPECT_FALSE(send_request_in_parts(5, parts));
  9027. }
  9028. #endif
  9029. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9030. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9031. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9032. const std::vector<std::string> &parts,
  9033. std::string *resp = nullptr,
  9034. int port = PORT) {
  9035. auto error = Error::Success;
  9036. auto sock = detail::create_client_socket(
  9037. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9038. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9039. /*write_timeout_sec=*/5, 0, std::string(), error);
  9040. if (sock == INVALID_SOCKET) { return false; }
  9041. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9042. auto ctx = SSL_CTX_new(TLS_client_method());
  9043. auto ssl = SSL_new(ctx);
  9044. auto ssl_se = detail::scope_exit([&] {
  9045. SSL_free(ssl);
  9046. SSL_CTX_free(ctx);
  9047. });
  9048. SSL_set_fd(ssl, static_cast<int>(sock));
  9049. if (SSL_connect(ssl) != 1) { return false; }
  9050. for (size_t i = 0; i < parts.size(); i++) {
  9051. const auto &part = parts[i];
  9052. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9053. static_cast<int>(part.size())) {
  9054. return false;
  9055. }
  9056. if (i + 1 < parts.size()) {
  9057. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9058. }
  9059. }
  9060. char buf[512];
  9061. int n;
  9062. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9063. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9064. }
  9065. return true;
  9066. }
  9067. #endif
  9068. // The request line, then a header value a byte at a time.
  9069. static std::vector<std::string> slow_request_head_parts() {
  9070. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9071. parts.resize(26, "a");
  9072. parts.emplace_back("\r\n\r\n");
  9073. return parts;
  9074. }
  9075. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9076. // within the one-second read timeout. The server gives up a second in, before
  9077. // the head is complete.
  9078. static void
  9079. expect_slow_request_head_dropped(Server &svr,
  9080. const std::function<std::string()> &send) {
  9081. std::atomic<bool> handled(false);
  9082. svr.Get("/", [&](const Request &, Response &res) {
  9083. handled = true;
  9084. res.set_content("ok", "text/plain");
  9085. });
  9086. svr.set_read_timeout(1, 0);
  9087. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9088. auto se = detail::scope_exit([&] {
  9089. svr.stop();
  9090. t.join();
  9091. ASSERT_FALSE(svr.is_running());
  9092. });
  9093. svr.wait_until_ready();
  9094. auto resp = send();
  9095. EXPECT_FALSE(handled);
  9096. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9097. }
  9098. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9099. Server svr;
  9100. expect_slow_request_head_dropped(svr, [] {
  9101. std::string resp;
  9102. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9103. return resp;
  9104. });
  9105. }
  9106. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9107. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9109. ASSERT_TRUE(svr.is_valid());
  9110. expect_slow_request_head_dropped(svr, [] {
  9111. std::string resp;
  9112. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9113. return resp;
  9114. });
  9115. }
  9116. #endif
  9117. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9118. Server svr;
  9119. std::string header_value;
  9120. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9121. header_value = req.get_header_value("foo");
  9122. res.set_content("ok", "text/plain");
  9123. });
  9124. thread t = thread([&] { svr.listen(HOST, PORT); });
  9125. auto se = detail::scope_exit([&] {
  9126. svr.stop();
  9127. t.join();
  9128. ASSERT_FALSE(svr.is_running());
  9129. });
  9130. svr.wait_until_ready();
  9131. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9132. // like characters are not treated the same - use vertical tab and escape.
  9133. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9134. "foo: \t \v bar \x1B\t \r\n"
  9135. "Connection: close\r\n"
  9136. "\r\n";
  9137. std::string res;
  9138. ASSERT_TRUE(send_request(5, req, &res));
  9139. EXPECT_EQ(header_value, "");
  9140. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9141. }
  9142. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9143. Server svr;
  9144. std::string received;
  9145. svr.Get("/order", [&](const Request &req, Response &res) {
  9146. received = entries_to_string(req.headers);
  9147. res.set_content("ok", "text/plain");
  9148. });
  9149. auto port = svr.bind_to_any_port(HOST);
  9150. thread t = thread([&] { svr.listen_after_bind(); });
  9151. auto se = detail::scope_exit([&] {
  9152. svr.stop();
  9153. t.join();
  9154. ASSERT_FALSE(svr.is_running());
  9155. });
  9156. svr.wait_until_ready();
  9157. const std::string req = "GET /order HTTP/1.1\r\n"
  9158. "Host: localhost\r\n"
  9159. "X-First: 1\r\n"
  9160. "X-Dup: a\r\n"
  9161. "X-Second: 2\r\n"
  9162. "X-Dup: b\r\n"
  9163. "Connection: close\r\n"
  9164. "\r\n";
  9165. std::string res;
  9166. ASSERT_TRUE(send_request(5, req, &res, port));
  9167. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9168. EXPECT_EQ(
  9169. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9170. received);
  9171. }
  9172. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9173. Server svr;
  9174. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9175. res.set_header("Set-Cookie", "first=1");
  9176. res.set_header("X-Between", "y");
  9177. res.set_header("Set-Cookie", "second=2");
  9178. res.set_content("ok", "text/plain");
  9179. });
  9180. auto port = svr.bind_to_any_port(HOST);
  9181. thread t = thread([&] { svr.listen_after_bind(); });
  9182. auto se = detail::scope_exit([&] {
  9183. svr.stop();
  9184. t.join();
  9185. ASSERT_FALSE(svr.is_running());
  9186. });
  9187. svr.wait_until_ready();
  9188. Client cli(HOST, port);
  9189. auto res = cli.Get("/cookies");
  9190. ASSERT_TRUE(res);
  9191. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9192. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9193. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9194. }
  9195. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9196. Server svr;
  9197. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9198. auto i = new int(0);
  9199. res.set_header("Trailer", "X-Safe, X-Reflected");
  9200. res.set_chunked_content_provider(
  9201. "text/plain",
  9202. [i](size_t /*offset*/, DataSink &sink) {
  9203. if (*i == 0) {
  9204. sink.os << "body";
  9205. } else {
  9206. Headers trailer;
  9207. // A valid trailer that must survive.
  9208. trailer.emplace("X-Safe", "safe");
  9209. // Attacker-controlled value carrying CR/LF (response splitting).
  9210. trailer.emplace("X-Reflected",
  9211. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9212. // Attacker-controlled name carrying CR/LF.
  9213. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9214. sink.done_with_trailer(trailer);
  9215. }
  9216. (*i)++;
  9217. return true;
  9218. },
  9219. [i](bool /*success*/) { delete i; });
  9220. });
  9221. thread t = thread([&] { svr.listen(HOST, PORT); });
  9222. auto se = detail::scope_exit([&] {
  9223. svr.stop();
  9224. t.join();
  9225. ASSERT_FALSE(svr.is_running());
  9226. });
  9227. svr.wait_until_ready();
  9228. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9229. "Host: " + HOST +
  9230. "\r\n"
  9231. "Connection: close\r\n"
  9232. "\r\n";
  9233. std::string res;
  9234. ASSERT_TRUE(send_request(5, req, &res));
  9235. // The injected fields must not appear anywhere in the raw response.
  9236. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9237. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9238. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9239. // Invalid trailers are dropped entirely, matching set_header().
  9240. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9241. // The valid trailer still passes through.
  9242. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9243. }
  9244. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9245. Server svr;
  9246. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9247. // res.headers is a public field an application can populate directly,
  9248. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9249. // A valid header that must survive.
  9250. res.headers.emplace("X-Safe", "safe");
  9251. // Attacker-controlled value carrying CR/LF (response splitting).
  9252. res.headers.emplace("X-Reflected",
  9253. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9254. // Attacker-controlled name carrying CR/LF.
  9255. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9256. res.set_content("body", "text/plain");
  9257. });
  9258. thread t = thread([&] { svr.listen(HOST, PORT); });
  9259. auto se = detail::scope_exit([&] {
  9260. svr.stop();
  9261. t.join();
  9262. ASSERT_FALSE(svr.is_running());
  9263. });
  9264. svr.wait_until_ready();
  9265. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9266. "Host: " + HOST +
  9267. "\r\n"
  9268. "Connection: close\r\n"
  9269. "\r\n";
  9270. std::string res;
  9271. ASSERT_TRUE(send_request(5, req, &res));
  9272. // The injected fields must not appear anywhere in the raw response.
  9273. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9274. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9275. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9276. // Invalid headers are dropped entirely, matching set_header().
  9277. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9278. // The valid header still passes through.
  9279. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9280. }
  9281. // Forward declaration: in split builds split.py strips `inline` and moves the
  9282. // definition into httplib.cc, so detail::write_request_line is not visible from
  9283. // the public httplib.h. Re-declaring it here lets the tests link against the
  9284. // symbol in both header-only and split builds.
  9285. namespace httplib {
  9286. namespace detail {
  9287. ssize_t write_request_line(Stream &strm, const std::string &method,
  9288. const std::string &path);
  9289. } // namespace detail
  9290. } // namespace httplib
  9291. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9292. // A well-formed target is written verbatim.
  9293. {
  9294. detail::BufferStream strm;
  9295. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9296. EXPECT_GT(n, 0);
  9297. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9298. }
  9299. // A target carrying CR/LF, SP or other control octets must be rejected
  9300. // before anything reaches the wire, otherwise it splits the request line and
  9301. // injects a header or a whole request.
  9302. const std::string evil_targets[] = {
  9303. "/a\r\nInjected: pwned",
  9304. "/a\rInjected",
  9305. "/a\nInjected",
  9306. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9307. "/a b",
  9308. "/a\tb",
  9309. "/a\x7f",
  9310. };
  9311. for (const auto &evil : evil_targets) {
  9312. detail::BufferStream strm;
  9313. auto n = detail::write_request_line(strm, "GET", evil);
  9314. EXPECT_LT(n, 0);
  9315. EXPECT_TRUE(strm.get_buffer().empty());
  9316. }
  9317. }
  9318. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9319. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9320. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9321. // target reaches write_request. The client must fail cleanly with
  9322. // Error::Write instead of putting a request-line-less, header-injecting
  9323. // request on the wire.
  9324. Server svr;
  9325. svr.Get("/a", [](const Request &, Response &res) {
  9326. res.set_content("ok", "text/plain");
  9327. });
  9328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9329. auto se = detail::scope_exit([&] {
  9330. svr.stop();
  9331. thread.join();
  9332. ASSERT_FALSE(svr.is_running());
  9333. });
  9334. svr.wait_until_ready();
  9335. {
  9336. Client cli(HOST, PORT);
  9337. cli.set_path_encode(false);
  9338. // The request is rejected before anything is written, so the connection
  9339. // stays silent and the subsequent response read would otherwise block for
  9340. // the full default read timeout. Shorten it -- the assertion is on the
  9341. // error, not the timeout.
  9342. cli.set_read_timeout(1, 0);
  9343. auto res = cli.Get("/a\r\nInjected: pwned");
  9344. EXPECT_FALSE(res);
  9345. EXPECT_EQ(Error::Write, res.error());
  9346. }
  9347. }
  9348. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9349. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9350. // including extension methods.
  9351. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9352. for (const auto &method : good_methods) {
  9353. detail::BufferStream strm;
  9354. auto n = detail::write_request_line(strm, method, "/");
  9355. EXPECT_GT(n, 0);
  9356. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9357. }
  9358. // A method carrying CR/LF would split the request line and smuggle a whole
  9359. // request ahead of the real one. A space or an empty method corrupts the
  9360. // request line. All must be rejected before anything reaches the wire.
  9361. const std::string evil_methods[] = {
  9362. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9363. "GET\r\nInjected: pwned",
  9364. "GET\r",
  9365. "GET\n",
  9366. "GE T",
  9367. "",
  9368. };
  9369. for (const auto &evil : evil_methods) {
  9370. detail::BufferStream strm;
  9371. auto n = detail::write_request_line(strm, evil, "/");
  9372. EXPECT_LT(n, 0);
  9373. EXPECT_TRUE(strm.get_buffer().empty());
  9374. }
  9375. }
  9376. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9377. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9378. // through Client::send must fail with Error::Write and no request, neither
  9379. // the smuggled one nor the real one, may reach the server.
  9380. Server svr;
  9381. std::atomic<int> request_count(0);
  9382. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9383. request_count++;
  9384. res.status = StatusCode::OK_200;
  9385. return Server::HandlerResponse::Handled;
  9386. });
  9387. auto port = svr.bind_to_any_port(HOST);
  9388. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. thread.join();
  9392. ASSERT_FALSE(svr.is_running());
  9393. });
  9394. svr.wait_until_ready();
  9395. {
  9396. Client cli(HOST, port);
  9397. const std::string evil_methods[] = {
  9398. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9399. "GE T",
  9400. "",
  9401. };
  9402. for (const auto &evil : evil_methods) {
  9403. Request req;
  9404. req.method = evil;
  9405. req.path = "/";
  9406. auto res = cli.send(req);
  9407. EXPECT_FALSE(res);
  9408. EXPECT_EQ(Error::Write, res.error());
  9409. }
  9410. auto handle =
  9411. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9412. EXPECT_FALSE(handle.is_valid());
  9413. EXPECT_EQ(Error::Write, handle.error);
  9414. // A valid request on the same client still goes through.
  9415. auto res = cli.Get("/");
  9416. ASSERT_TRUE(res);
  9417. EXPECT_EQ(StatusCode::OK_200, res->status);
  9418. }
  9419. EXPECT_EQ(1, request_count.load());
  9420. }
  9421. // Sends a raw request and verifies that there isn't a crash or exception.
  9422. static void test_raw_request(const std::string &req,
  9423. std::string *out = nullptr) {
  9424. Server svr;
  9425. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9426. res.set_content("ok", "text/plain");
  9427. });
  9428. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9429. res.set_content("ok", "text/plain");
  9430. });
  9431. svr.Get("/header_field_value_check",
  9432. [&](const Request & /*req*/, Response &res) {
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. svr.CustomRoute("PROPFIND", "/dav",
  9436. [&](const Request & /*req*/, Response &res) {
  9437. res.status = StatusCode::MultiStatus_207;
  9438. });
  9439. // Server read timeout must be longer than the client read timeout for the
  9440. // bug to reproduce, probably to force the server to process a request
  9441. // without a trailing blank line.
  9442. const time_t client_read_timeout_sec = 1;
  9443. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9444. bool listen_thread_ok = false;
  9445. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9446. auto se = detail::scope_exit([&] {
  9447. svr.stop();
  9448. t.join();
  9449. ASSERT_FALSE(svr.is_running());
  9450. EXPECT_TRUE(listen_thread_ok);
  9451. });
  9452. svr.wait_until_ready();
  9453. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9454. }
  9455. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9456. // A certain header line causes an exception if the header property is parsed
  9457. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9458. test_raw_request(
  9459. "GET /hi HTTP/1.1\r\n"
  9460. " : "
  9461. " "
  9462. " ");
  9463. }
  9464. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9465. // A certain header line causes an exception if the header property *name* is
  9466. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9467. // greedy matcher and requires backtracking when there are a lot of ":"
  9468. // characters.
  9469. // This occurs with libc++ but not libstdc++.
  9470. test_raw_request(
  9471. "GET /hi HTTP/1.1\r\n"
  9472. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9473. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9474. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9475. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9476. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9477. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9478. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9479. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9480. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9481. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9482. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9483. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9484. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9485. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9486. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9487. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9488. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9489. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9490. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9491. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9492. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9493. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9494. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9495. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9496. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9497. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9498. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9499. "&&&%%%");
  9500. }
  9501. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9502. // Make sure this doesn't crash the server.
  9503. // In a previous version of the header line regex, the "\r" rendered the line
  9504. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9505. // a new position where the leading white space ended and the field value
  9506. // began.
  9507. // The crash occurs with libc++ but not libstdc++.
  9508. test_raw_request("GET /hi HTTP/1.1\r\n"
  9509. "a:" +
  9510. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9511. "\r\n"
  9512. "\r\n");
  9513. }
  9514. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9515. const char *rejected[] = {
  9516. // RFC 9112 §3: one SP between the parts, and nothing else
  9517. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9518. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9519. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9520. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9521. // A request-target has no fragment
  9522. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9523. // An HTTP/1.1 request needs a Host
  9524. "GET /hi HTTP/1.1\r\n\r\n",
  9525. };
  9526. for (auto request : rejected) {
  9527. std::string out;
  9528. test_raw_request(request, &out);
  9529. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9530. }
  9531. std::string out;
  9532. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9533. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9534. }
  9535. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9536. // RFC 9112 §6.1
  9537. const char *requests[] = {
  9538. "PUT /put_hi HTTP/1.1\r\n"
  9539. "Host: localhost\r\n"
  9540. "Content-Length: 0\r\n"
  9541. "Transfer-Encoding: chunked\r\n"
  9542. "\r\n"
  9543. "0\r\n\r\n",
  9544. "PUT /put_hi HTTP/1.0\r\n"
  9545. "Connection: keep-alive\r\n"
  9546. "Transfer-Encoding: chunked\r\n"
  9547. "\r\n"
  9548. "0\r\n\r\n",
  9549. };
  9550. for (auto request : requests) {
  9551. std::string out;
  9552. test_raw_request(request, &out);
  9553. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9554. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9555. }
  9556. }
  9557. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9558. std::string out;
  9559. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9560. "Content-Type: text/plain\r\n"
  9561. "Transfer-Encoding: chunked\r\n"
  9562. "\r\n"
  9563. "nothex\r\n",
  9564. &out);
  9565. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9566. }
  9567. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9568. std::string out;
  9569. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9570. "Content-Type: text/plain\r\n"
  9571. "Transfer-Encoding: chunked\r\n"
  9572. "\r\n"
  9573. "3\r\n"
  9574. "xyz\r\n"
  9575. "NaN\r\n",
  9576. &out);
  9577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9578. }
  9579. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9580. std::string out;
  9581. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9582. "Content-Type: text/plain\r\n"
  9583. "Transfer-Encoding: chunked\r\n"
  9584. "\r\n"
  9585. // Length is too large for 64 bits.
  9586. "1ffffffffffffffff\r\n"
  9587. "xyz\r\n",
  9588. &out);
  9589. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9590. }
  9591. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9592. test_raw_request("GET /hi HTTP/1.1\r\n"
  9593. "Content-Type: text/plain\r\n\r");
  9594. }
  9595. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9596. std::string out;
  9597. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9598. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9599. }
  9600. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9601. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9602. std::string out;
  9603. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9604. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9605. }
  9606. }
  9607. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9608. std::string out;
  9609. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9610. "Host: localhost\r\n"
  9611. "Connection: close\r\n\r\n",
  9612. &out);
  9613. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9614. }
  9615. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9616. Server svr;
  9617. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9618. EXPECT_TRUE(!req.remote_addr.empty());
  9619. });
  9620. thread t = thread([&] { svr.listen(HOST, PORT); });
  9621. auto se = detail::scope_exit([&] {
  9622. svr.stop();
  9623. t.join();
  9624. ASSERT_FALSE(svr.is_running());
  9625. });
  9626. svr.wait_until_ready();
  9627. // Send an invalid request line to trigger Bad Request
  9628. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9629. std::string out;
  9630. ASSERT_TRUE(send_request(5, bad_req, &out));
  9631. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9632. }
  9633. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9634. // answered right away rather than blocking on a read that waits for EOF.
  9635. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9636. std::string out;
  9637. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9638. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9639. }
  9640. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9641. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9642. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9643. for (const auto *method : methods) {
  9644. Server svr;
  9645. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9646. EXPECT_FALSE(svr.is_valid()) << method;
  9647. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9648. }
  9649. }
  9650. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9651. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9652. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9653. for (const auto *method : methods) {
  9654. Server svr;
  9655. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9656. EXPECT_FALSE(svr.is_valid()) << method;
  9657. }
  9658. }
  9659. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9660. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9661. "COPY", "MOVE", "LOCK",
  9662. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9663. Server svr;
  9664. for (const auto *method : methods) {
  9665. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9666. }
  9667. EXPECT_TRUE(svr.is_valid());
  9668. }
  9669. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9670. Server svr;
  9671. svr.CustomRoute("POST", "/x",
  9672. [](const Request &, Response &, const ContentReader &) {});
  9673. EXPECT_FALSE(svr.is_valid());
  9674. }
  9675. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9676. Server svr;
  9677. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9678. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9679. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9680. EXPECT_FALSE(svr.is_valid());
  9681. }
  9682. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9683. Server svr;
  9684. auto captured = Error::Success;
  9685. svr.set_error_logger(
  9686. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9687. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9688. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9689. }
  9690. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9691. std::string out;
  9692. std::string request(
  9693. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9694. test_raw_request(request, &out);
  9695. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9696. }
  9697. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9698. std::string out;
  9699. std::string request(
  9700. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9701. test_raw_request(request, &out);
  9702. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9703. }
  9704. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9705. std::string out;
  9706. std::string request(
  9707. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9708. test_raw_request(request, &out);
  9709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9710. }
  9711. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9712. std::string out;
  9713. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9714. "Host: localhost\r\n"
  9715. "Test: \r\n\r\n",
  9716. &out);
  9717. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9718. }
  9719. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9720. Server svr;
  9721. std::string x_custom;
  9722. std::string cookie;
  9723. std::string xff;
  9724. std::string x_unicode;
  9725. std::string x_iis;
  9726. svr.Get("/check", [&](const Request &req, Response &res) {
  9727. x_custom = req.get_header_value("X-Custom");
  9728. cookie = req.get_header_value("Cookie");
  9729. xff = req.get_header_value("X-Forwarded-For");
  9730. x_unicode = req.get_header_value("X-Unicode");
  9731. x_iis = req.get_header_value("X-IIS");
  9732. res.set_content("ok", "text/plain");
  9733. });
  9734. thread t = thread([&] { svr.listen(HOST, PORT); });
  9735. auto se = detail::scope_exit([&] {
  9736. svr.stop();
  9737. t.join();
  9738. ASSERT_FALSE(svr.is_running());
  9739. });
  9740. svr.wait_until_ready();
  9741. const std::string req = "GET /check HTTP/1.1\r\n"
  9742. "Host: localhost\r\n"
  9743. "X-Custom: a%0D%0AInjected: b\r\n"
  9744. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9745. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9746. "X-Unicode: %E3%81%82\r\n"
  9747. "X-IIS: %u00E9\r\n"
  9748. "Connection: close\r\n"
  9749. "\r\n";
  9750. std::string res;
  9751. ASSERT_TRUE(send_request(5, req, &res));
  9752. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9753. // Every value must be returned verbatim (wire form), with no decoding.
  9754. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9755. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9756. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9757. EXPECT_EQ("%E3%81%82", x_unicode);
  9758. EXPECT_EQ("%u00E9", x_iis);
  9759. }
  9760. // Applications that previously relied on automatic percent-decoding can
  9761. // reproduce the old behavior by explicitly calling decode_path_component()
  9762. // or, for RFC 3986 conformance, decode_uri_component().
  9763. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9764. Server svr;
  9765. std::string decoded;
  9766. svr.Get("/check", [&](const Request &req, Response &res) {
  9767. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9768. res.set_content("ok", "text/plain");
  9769. });
  9770. thread t = thread([&] { svr.listen(HOST, PORT); });
  9771. auto se = detail::scope_exit([&] {
  9772. svr.stop();
  9773. t.join();
  9774. ASSERT_FALSE(svr.is_running());
  9775. });
  9776. svr.wait_until_ready();
  9777. const std::string req = "GET /check HTTP/1.1\r\n"
  9778. "Host: localhost\r\n"
  9779. "X-Custom: hello%20world\r\n"
  9780. "Connection: close\r\n"
  9781. "\r\n";
  9782. std::string res;
  9783. ASSERT_TRUE(send_request(5, req, &res));
  9784. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9785. EXPECT_EQ("hello world", decoded);
  9786. }
  9787. // Regression test for #2033. Browsers send Referer values that include
  9788. // percent-encoded characters such as %0A inside the URL. Decoding the
  9789. // header value would either trip the post-decode CR/LF/NUL guard (the
  9790. // original bug, returning 400) or, after that guard was relaxed, silently
  9791. // store a literal LF — both unacceptable. The wire form must round-trip.
  9792. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9793. Server svr;
  9794. std::string referer;
  9795. svr.Get("/check", [&](const Request &req, Response &res) {
  9796. referer = req.get_header_value("Referer");
  9797. res.set_content("ok", "text/plain");
  9798. });
  9799. thread t = thread([&] { svr.listen(HOST, PORT); });
  9800. auto se = detail::scope_exit([&] {
  9801. svr.stop();
  9802. t.join();
  9803. ASSERT_FALSE(svr.is_running());
  9804. });
  9805. svr.wait_until_ready();
  9806. const std::string req = "GET /check HTTP/1.1\r\n"
  9807. "Host: localhost\r\n"
  9808. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9809. "Connection: close\r\n"
  9810. "\r\n";
  9811. std::string res;
  9812. ASSERT_TRUE(send_request(5, req, &res));
  9813. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9814. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9815. }
  9816. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9817. Server svr;
  9818. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9819. res.set_header("Cache-Control", "no-cache");
  9820. res.set_chunked_content_provider(
  9821. "text/event-stream", [](size_t offset, DataSink &sink) {
  9822. std::string s = "data:";
  9823. s += std::to_string(offset);
  9824. s += "\n\n";
  9825. auto ret = sink.write(s.data(), s.size());
  9826. EXPECT_TRUE(ret);
  9827. std::this_thread::sleep_for(std::chrono::seconds(1));
  9828. return true;
  9829. });
  9830. });
  9831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9832. svr.wait_until_ready();
  9833. Client client(HOST, PORT);
  9834. const Headers headers = {{"Accept", "text/event-stream"}};
  9835. auto get_thread = std::thread([&client, &headers]() {
  9836. auto res = client.Get(
  9837. "/events", headers,
  9838. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9839. });
  9840. auto se = detail::scope_exit([&] {
  9841. svr.stop();
  9842. get_thread.join();
  9843. listen_thread.join();
  9844. ASSERT_FALSE(svr.is_running());
  9845. });
  9846. // Give GET time to get a few messages.
  9847. std::this_thread::sleep_for(std::chrono::seconds(2));
  9848. }
  9849. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9850. httplib::Server svr;
  9851. svr.Post("/hi",
  9852. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9853. res.status = StatusCode::OK_200;
  9854. });
  9855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9856. svr.wait_until_ready();
  9857. Client cli(HOST, PORT);
  9858. auto res = cli.Post("/hi", "data", "text/plain");
  9859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9860. EXPECT_EQ(StatusCode::OK_200, res->status);
  9861. svr.stop();
  9862. thread.join();
  9863. ASSERT_FALSE(svr.is_running());
  9864. res = cli.Post("/hi", "data", "text/plain");
  9865. ASSERT_FALSE(res);
  9866. }
  9867. TEST(ServerStopTest, ListenFailure) {
  9868. Server svr;
  9869. auto t = thread([&]() {
  9870. auto ret = svr.listen("????", PORT);
  9871. EXPECT_FALSE(ret);
  9872. });
  9873. svr.wait_until_ready();
  9874. svr.stop();
  9875. t.join();
  9876. }
  9877. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9878. TEST(ServerStopTest, Decommision) {
  9879. Server svr;
  9880. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9881. for (int i = 0; i < 4; i++) {
  9882. auto is_even = !(i % 2);
  9883. std::thread t{[&] {
  9884. try {
  9885. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9886. if (is_even) {
  9887. throw std::runtime_error("Some thing that happens to go wrong.");
  9888. }
  9889. svr.listen(HOST, PORT);
  9890. } catch (...) { svr.decommission(); }
  9891. }};
  9892. svr.wait_until_ready();
  9893. // Server is up
  9894. {
  9895. Client cli(HOST, PORT);
  9896. auto res = cli.Get("/hi");
  9897. if (is_even) {
  9898. EXPECT_FALSE(res);
  9899. } else {
  9900. EXPECT_TRUE(res);
  9901. EXPECT_EQ("hi...", res->body);
  9902. }
  9903. }
  9904. svr.stop();
  9905. t.join();
  9906. // Server is down...
  9907. {
  9908. Client cli(HOST, PORT);
  9909. auto res = cli.Get("/hi");
  9910. EXPECT_FALSE(res);
  9911. }
  9912. }
  9913. }
  9914. #endif
  9915. // Helper function for string body upload progress tests
  9916. template <typename SetupHandler, typename ClientCall>
  9917. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9918. ClientCall &&client_call,
  9919. const string &body) {
  9920. Server svr;
  9921. setup_handler(svr);
  9922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9923. auto se = detail::scope_exit([&] {
  9924. svr.stop();
  9925. t.join();
  9926. });
  9927. svr.wait_until_ready();
  9928. Client cli(HOST, PORT);
  9929. vector<uint64_t> progress_values;
  9930. bool progress_called = false;
  9931. auto res =
  9932. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9933. progress_values.push_back(current);
  9934. progress_called = true;
  9935. return true;
  9936. });
  9937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9938. EXPECT_EQ(200, res->status);
  9939. EXPECT_TRUE(progress_called);
  9940. }
  9941. TEST(UploadProgressTest, PostStringBodyBasic) {
  9942. TestStringBodyUploadProgress(
  9943. [](Server &svr) {
  9944. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9945. res.set_content("received", "text/plain");
  9946. });
  9947. },
  9948. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9949. return cli.Post("/test", body, "text/plain", progress_callback);
  9950. },
  9951. "test data for upload progress");
  9952. }
  9953. TEST(UploadProgressTest, PutStringBodyBasic) {
  9954. TestStringBodyUploadProgress(
  9955. [](Server &svr) {
  9956. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9957. res.set_content("put received", "text/plain");
  9958. });
  9959. },
  9960. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9961. return cli.Put("/test", body, "text/plain", progress_callback);
  9962. },
  9963. "put test data for upload progress");
  9964. }
  9965. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9966. TestStringBodyUploadProgress(
  9967. [](Server &svr) {
  9968. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9969. res.set_content("patch received", "text/plain");
  9970. });
  9971. },
  9972. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9973. return cli.Patch("/test", body, "text/plain", progress_callback);
  9974. },
  9975. "patch test data for upload progress");
  9976. }
  9977. // Helper function for content provider upload progress tests
  9978. template <typename SetupHandler, typename ClientCall>
  9979. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9980. ClientCall &&client_call) {
  9981. Server svr;
  9982. setup_handler(svr);
  9983. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9984. auto se = detail::scope_exit([&] {
  9985. svr.stop();
  9986. t.join();
  9987. });
  9988. svr.wait_until_ready();
  9989. Client cli(HOST, PORT);
  9990. vector<uint64_t> progress_values;
  9991. auto res =
  9992. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9993. progress_values.push_back(current);
  9994. return true;
  9995. });
  9996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9997. EXPECT_EQ(200, res->status);
  9998. EXPECT_FALSE(progress_values.empty());
  9999. }
  10000. TEST(UploadProgressTest, PostContentProviderProgress) {
  10001. TestContentProviderUploadProgress(
  10002. [](Server &svr) {
  10003. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10004. res.set_content("provider received", "text/plain");
  10005. });
  10006. },
  10007. [](Client &cli, UploadProgress progress_callback) {
  10008. return cli.Post(
  10009. "/test", 9,
  10010. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10011. sink.os << "test data";
  10012. return true;
  10013. },
  10014. "text/plain", progress_callback);
  10015. });
  10016. }
  10017. // Helper function for multipart upload progress tests
  10018. template <typename SetupHandler, typename ClientCall>
  10019. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10020. ClientCall &&client_call,
  10021. const string &endpoint) {
  10022. Server svr;
  10023. setup_handler(svr);
  10024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10025. auto se = detail::scope_exit([&] {
  10026. svr.stop();
  10027. t.join();
  10028. });
  10029. svr.wait_until_ready();
  10030. Client cli(HOST, PORT);
  10031. vector<uint64_t> progress_values;
  10032. UploadFormDataItems items = {
  10033. {"field1", "value1", "", ""},
  10034. {"field2", "longer value for progress tracking test", "", ""},
  10035. {"file1", "file content data for upload progress", "test.txt",
  10036. "text/plain"}};
  10037. auto res = client_call(cli, endpoint, items,
  10038. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10039. progress_values.push_back(current);
  10040. return true;
  10041. });
  10042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10043. EXPECT_EQ(200, res->status);
  10044. EXPECT_FALSE(progress_values.empty());
  10045. }
  10046. TEST(UploadProgressTest, PostMultipartProgress) {
  10047. TestMultipartUploadProgress(
  10048. [](Server &svr) {
  10049. svr.Post("/multipart", [](const Request &req, Response &res) {
  10050. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10051. res.set_content("multipart received", "text/plain");
  10052. });
  10053. },
  10054. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10055. UploadProgress progress_callback) {
  10056. return cli.Post(endpoint, items, progress_callback);
  10057. },
  10058. "/multipart");
  10059. }
  10060. // Helper function for basic download progress tests
  10061. template <typename SetupHandler, typename ClientCall>
  10062. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10063. ClientCall &&client_call, const string &endpoint,
  10064. size_t expected_content_size) {
  10065. Server svr;
  10066. setup_handler(svr);
  10067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10068. auto se = detail::scope_exit([&] {
  10069. svr.stop();
  10070. t.join();
  10071. });
  10072. svr.wait_until_ready();
  10073. Client cli(HOST, PORT);
  10074. vector<uint64_t> progress_values;
  10075. auto res = client_call(cli, endpoint,
  10076. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10077. progress_values.push_back(current);
  10078. return true;
  10079. });
  10080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10081. EXPECT_EQ(200, res->status);
  10082. EXPECT_FALSE(progress_values.empty());
  10083. EXPECT_EQ(expected_content_size, res->body.size());
  10084. }
  10085. TEST(DownloadProgressTest, GetBasic) {
  10086. TestBasicDownloadProgress(
  10087. [](Server &svr) {
  10088. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10089. string content(1000, 'D');
  10090. res.set_content(content, "text/plain");
  10091. });
  10092. },
  10093. [](Client &cli, const string &endpoint,
  10094. DownloadProgress progress_callback) {
  10095. return cli.Get(endpoint, progress_callback);
  10096. },
  10097. "/download", 1000u);
  10098. }
  10099. // Helper function for content receiver download progress tests
  10100. template <typename SetupHandler, typename ClientCall>
  10101. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10102. ClientCall &&client_call,
  10103. const string &endpoint,
  10104. size_t expected_content_size) {
  10105. Server svr;
  10106. setup_handler(svr);
  10107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10108. auto se = detail::scope_exit([&] {
  10109. svr.stop();
  10110. t.join();
  10111. });
  10112. svr.wait_until_ready();
  10113. Client cli(HOST, PORT);
  10114. vector<uint64_t> progress_values;
  10115. string received_body;
  10116. auto res = client_call(
  10117. cli, endpoint,
  10118. [&](const char *data, size_t data_length) -> bool {
  10119. received_body.append(data, data_length);
  10120. return true;
  10121. },
  10122. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10123. progress_values.push_back(current);
  10124. return true;
  10125. });
  10126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10127. EXPECT_EQ(200, res->status);
  10128. EXPECT_FALSE(progress_values.empty());
  10129. EXPECT_EQ(expected_content_size, received_body.size());
  10130. EXPECT_TRUE(res->body.empty());
  10131. }
  10132. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10133. TestContentReceiverDownloadProgress(
  10134. [](Server &svr) {
  10135. svr.Get("/download-receiver",
  10136. [](const Request & /*req*/, Response &res) {
  10137. string content(2000, 'R');
  10138. res.set_content(content, "text/plain");
  10139. });
  10140. },
  10141. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10142. DownloadProgress progress_callback) {
  10143. return cli.Get(endpoint, content_receiver, progress_callback);
  10144. },
  10145. "/download-receiver", 2000u);
  10146. }
  10147. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10148. // A provider reaching a pass with nothing to hand over - an empty buffer
  10149. // popped off a queue, say - must not be taken to mean the body is finished.
  10150. // It used to end the loop with the terminating chunk unwritten while the
  10151. // server still considered the response complete, so the peer waited for an
  10152. // end that never arrived.
  10153. Server svr;
  10154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10155. auto step = std::make_shared<int>(0);
  10156. res.set_chunked_content_provider("text/plain",
  10157. [step](size_t /*offset*/, DataSink &sink) {
  10158. switch ((*step)++) {
  10159. case 0: sink.write("", 0); break;
  10160. case 1: sink.write("hello", 5); break;
  10161. default: sink.done(); break;
  10162. }
  10163. return true;
  10164. });
  10165. });
  10166. auto port = svr.bind_to_any_port(HOST);
  10167. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10168. auto listen_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(HOST, port);
  10175. // Without the fix the body is never terminated, so bound the wait rather
  10176. // than letting the test hang on the default read timeout.
  10177. cli.set_read_timeout(5, 0);
  10178. auto res = cli.Get("/stream");
  10179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10180. EXPECT_EQ(StatusCode::OK_200, res->status);
  10181. EXPECT_EQ("hello", res->body);
  10182. }
  10183. TEST(StreamingTest, NoContentLengthStreaming) {
  10184. Server svr;
  10185. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10186. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10187. if (offset < 6) {
  10188. sink.os << (offset < 3 ? "a" : "b");
  10189. } else {
  10190. sink.done();
  10191. }
  10192. return true;
  10193. });
  10194. });
  10195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10196. auto listen_se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. listen_thread.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. });
  10201. svr.wait_until_ready();
  10202. Client client(HOST, PORT);
  10203. auto get_thread = std::thread([&client]() {
  10204. std::string s;
  10205. auto res =
  10206. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10207. s += std::string(data, len);
  10208. return true;
  10209. });
  10210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10211. EXPECT_EQ(StatusCode::OK_200, res->status);
  10212. EXPECT_EQ("aaabbb", s);
  10213. });
  10214. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10215. // Give GET time to get a few messages.
  10216. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10217. }
  10218. TEST(MountTest, Unmount) {
  10219. Server svr;
  10220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10221. auto se = detail::scope_exit([&] {
  10222. svr.stop();
  10223. listen_thread.join();
  10224. ASSERT_FALSE(svr.is_running());
  10225. });
  10226. svr.wait_until_ready();
  10227. Client cli("localhost", PORT);
  10228. svr.set_mount_point("/mount2", "./www2");
  10229. auto res = cli.Get("/");
  10230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10232. res = cli.Get("/mount2/dir/test.html");
  10233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10234. EXPECT_EQ(StatusCode::OK_200, res->status);
  10235. svr.set_mount_point("/", "./www");
  10236. res = cli.Get("/dir/");
  10237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10238. EXPECT_EQ(StatusCode::OK_200, res->status);
  10239. svr.remove_mount_point("/");
  10240. res = cli.Get("/dir/");
  10241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10243. svr.remove_mount_point("/mount2");
  10244. res = cli.Get("/mount2/dir/test.html");
  10245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10247. }
  10248. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10249. Server svr;
  10250. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10251. svr.Get("/api/hello", [](const Request &, Response &res) {
  10252. res.set_content("api", "text/plain");
  10253. });
  10254. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. listen_thread.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. Client cli(HOST, PORT);
  10262. auto res = cli.Get("/dir/test.html");
  10263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10264. EXPECT_EQ(StatusCode::OK_200, res->status);
  10265. res = cli.Get("/api/hello");
  10266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10267. EXPECT_EQ(StatusCode::OK_200, res->status);
  10268. EXPECT_EQ("api", res->body);
  10269. }
  10270. TEST(MountTest, PathSegmentBoundary) {
  10271. Server svr;
  10272. svr.set_mount_point("/mount2", "./www2");
  10273. svr.set_mount_point("/", "./www");
  10274. auto port = svr.bind_to_any_port(HOST);
  10275. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10276. auto se = detail::scope_exit([&] {
  10277. svr.stop();
  10278. listen_thread.join();
  10279. ASSERT_FALSE(svr.is_running());
  10280. });
  10281. svr.wait_until_ready();
  10282. Client cli(HOST, port);
  10283. auto res = cli.Get("/mount2/dir/test.html");
  10284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. // "/mount2" must not match part-way through a path segment.
  10287. res = cli.Get("/mount2dir/test.html");
  10288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10290. // A mount point ending in '/' keeps matching every path below it.
  10291. res = cli.Get("/dir/test.html");
  10292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10293. EXPECT_EQ(StatusCode::OK_200, res->status);
  10294. }
  10295. TEST(MountTest, Redicect) {
  10296. Server svr;
  10297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10298. auto se = detail::scope_exit([&] {
  10299. svr.stop();
  10300. listen_thread.join();
  10301. ASSERT_FALSE(svr.is_running());
  10302. });
  10303. svr.set_mount_point("/", "./www");
  10304. svr.wait_until_ready();
  10305. Client cli("localhost", PORT);
  10306. auto res = cli.Get("/dir/");
  10307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10308. EXPECT_EQ(StatusCode::OK_200, res->status);
  10309. res = cli.Get("/dir");
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10312. res = cli.Get("/file");
  10313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10314. EXPECT_EQ(StatusCode::OK_200, res->status);
  10315. res = cli.Get("/file/");
  10316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10317. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10318. cli.set_follow_location(true);
  10319. res = cli.Get("/dir");
  10320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10321. EXPECT_EQ(StatusCode::OK_200, res->status);
  10322. }
  10323. TEST(MountTest, MultibytesPathName) {
  10324. Server svr;
  10325. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10326. auto se = detail::scope_exit([&] {
  10327. svr.stop();
  10328. listen_thread.join();
  10329. ASSERT_FALSE(svr.is_running());
  10330. });
  10331. svr.set_mount_point("/", "./www");
  10332. svr.wait_until_ready();
  10333. Client cli("localhost", PORT);
  10334. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10336. EXPECT_EQ(StatusCode::OK_200, res->status);
  10337. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10338. }
  10339. #ifdef _WIN32
  10340. // Issue #2435: mmap::open() must succeed even when another handle holds
  10341. // the file open for writing (e.g. an active log file).
  10342. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10343. const char *path = "mmap_concurrent_writer_test.txt";
  10344. const char *content = "hello";
  10345. {
  10346. std::ofstream f(path, std::ios::binary);
  10347. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10348. }
  10349. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10350. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10351. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10352. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10353. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10354. detail::mmap m(path);
  10355. ASSERT_TRUE(m.is_open());
  10356. EXPECT_EQ(strlen(content), m.size());
  10357. char buf[8];
  10358. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10359. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10360. }
  10361. #endif
  10362. #ifndef _WIN32
  10363. // A directory or a device has no size to serve.
  10364. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10365. const char *path = "./mmap_not_regular_test_dir";
  10366. ASSERT_EQ(0, ::mkdir(path, 0755));
  10367. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10368. for (auto p : {path, "/dev/null"}) {
  10369. detail::mmap m(p);
  10370. EXPECT_FALSE(m.is_open()) << p;
  10371. EXPECT_EQ(0U, m.size()) << p;
  10372. }
  10373. Server svr;
  10374. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10375. res.set_file_content("/dev/null");
  10376. });
  10377. auto port = svr.bind_to_any_port(HOST);
  10378. thread t = thread([&] { svr.listen_after_bind(); });
  10379. auto se = detail::scope_exit([&] {
  10380. svr.stop();
  10381. t.join();
  10382. });
  10383. svr.wait_until_ready();
  10384. auto res = Client(HOST, port).Get("/null");
  10385. ASSERT_TRUE(res);
  10386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10387. }
  10388. #endif
  10389. #ifdef __linux__
  10390. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10391. TEST(MmapTest, FileIsNotMapped) {
  10392. const char *path = "mmap_not_mapped_test.txt";
  10393. {
  10394. std::ofstream f(path, std::ios::binary);
  10395. f << "hello";
  10396. }
  10397. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10398. detail::mmap m(path);
  10399. ASSERT_TRUE(m.is_open());
  10400. std::ifstream maps("/proc/self/maps");
  10401. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10402. std::istreambuf_iterator<char>());
  10403. EXPECT_EQ(std::string::npos, mappings.find(path));
  10404. }
  10405. #endif
  10406. TEST(KeepAliveTest, ReadTimeout) {
  10407. Server svr;
  10408. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10409. std::this_thread::sleep_for(std::chrono::seconds(2));
  10410. res.set_content("a", "text/plain");
  10411. });
  10412. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10413. res.set_content("b", "text/plain");
  10414. });
  10415. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10416. auto se = detail::scope_exit([&] {
  10417. svr.stop();
  10418. listen_thread.join();
  10419. ASSERT_FALSE(svr.is_running());
  10420. });
  10421. svr.wait_until_ready();
  10422. Client cli("localhost", PORT);
  10423. cli.set_keep_alive(true);
  10424. cli.set_read_timeout(std::chrono::seconds(1));
  10425. auto resa = cli.Get("/a");
  10426. ASSERT_FALSE(resa);
  10427. EXPECT_EQ(Error::Read, resa.error());
  10428. auto resb = cli.Get("/b");
  10429. ASSERT_TRUE(resb);
  10430. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10431. EXPECT_EQ("b", resb->body);
  10432. }
  10433. TEST(KeepAliveTest, MaxCount) {
  10434. size_t keep_alive_max_count = 3;
  10435. Server svr;
  10436. svr.set_keep_alive_max_count(keep_alive_max_count);
  10437. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10438. res.set_content("Hello World!", "text/plain");
  10439. });
  10440. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10441. auto se = detail::scope_exit([&] {
  10442. svr.stop();
  10443. listen_thread.join();
  10444. ASSERT_FALSE(svr.is_running());
  10445. });
  10446. svr.wait_until_ready();
  10447. Client cli(HOST, PORT);
  10448. cli.set_keep_alive(true);
  10449. for (size_t i = 0; i < 5; i++) {
  10450. auto result = cli.Get("/hi");
  10451. ASSERT_TRUE(result);
  10452. EXPECT_EQ(StatusCode::OK_200, result->status);
  10453. if (i == keep_alive_max_count - 1) {
  10454. EXPECT_EQ("close", result->get_header_value("Connection"));
  10455. } else {
  10456. EXPECT_FALSE(result->has_header("Connection"));
  10457. }
  10458. }
  10459. }
  10460. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10461. // can pull the next one into the server's buffer. The server must serve it
  10462. // without waiting for the socket to become readable again. The keep-alive
  10463. // timeout outlasts the client's read timeout, so a request left waiting for it
  10464. // shows up as a missing response.
  10465. static void serve_pipelining_routes(Server &svr,
  10466. const std::function<void(int)> &client) {
  10467. svr.set_keep_alive_timeout(5);
  10468. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10469. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10470. });
  10471. svr.Post("/echo", [](const Request &req, Response &res) {
  10472. res.set_content("echo " + req.body, "text/plain");
  10473. });
  10474. auto port = svr.bind_to_any_port(HOST);
  10475. thread t = thread([&] { svr.listen_after_bind(); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. });
  10480. svr.wait_until_ready();
  10481. client(port);
  10482. }
  10483. static std::string
  10484. send_pipelined_requests(const std::vector<std::string> &parts) {
  10485. Server svr;
  10486. std::string res;
  10487. serve_pipelining_routes(svr, [&](int port) {
  10488. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10489. });
  10490. return res;
  10491. }
  10492. static void expect_in_order(const std::string &res,
  10493. const std::vector<std::string> &bodies) {
  10494. size_t pos = 0;
  10495. for (const auto &body : bodies) {
  10496. pos = res.find(body, pos);
  10497. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10498. pos += body.size();
  10499. }
  10500. }
  10501. TEST(KeepAliveTest, PipelinedRequests) {
  10502. auto res = send_pipelined_requests(
  10503. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10504. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10505. "Content-Length: 4\r\n\r\nbody"
  10506. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10507. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10508. }
  10509. // The second request starts in the server's buffer and ends on the socket.
  10510. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10511. auto res =
  10512. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10513. "GET /hi/2 HTTP/1.1\r\nHo",
  10514. "st: localhost\r\nConnection: close\r\n\r\n"});
  10515. expect_in_order(res, {"hi 1", "hi 2"});
  10516. }
  10517. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10518. // CRLF after a body does not turn into a 400 for the next request.
  10519. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10520. auto res = send_pipelined_requests(
  10521. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10522. "Content-Length: 4\r\n\r\nbody\r\n"
  10523. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10524. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10525. expect_in_order(res, {"echo body", "hi 2"});
  10526. }
  10527. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10528. // must not be served as the next request.
  10529. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10530. auto res = send_pipelined_requests(
  10531. {"INVALID REQUEST LINE\r\n\r\n"
  10532. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10533. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10534. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10535. }
  10536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10537. // Over TLS, the next request is held by the TLS library as already decrypted
  10538. // data rather than on the socket.
  10539. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10540. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10541. std::string res;
  10542. serve_pipelining_routes(svr, [&](int port) {
  10543. // One part, so all three requests arrive in one TLS record
  10544. EXPECT_TRUE(send_ssl_request_in_parts(
  10545. 2,
  10546. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10547. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10548. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10549. &res, port));
  10550. });
  10551. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10552. }
  10553. #endif
  10554. TEST(KeepAliveTest, Issue1041) {
  10555. Server svr;
  10556. svr.set_keep_alive_timeout(3);
  10557. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10558. res.set_content("Hello World!", "text/plain");
  10559. });
  10560. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10561. auto se = detail::scope_exit([&] {
  10562. svr.stop();
  10563. listen_thread.join();
  10564. ASSERT_FALSE(svr.is_running());
  10565. });
  10566. svr.wait_until_ready();
  10567. Client cli(HOST, PORT);
  10568. cli.set_keep_alive(true);
  10569. auto result = cli.Get("/hi");
  10570. ASSERT_TRUE(result);
  10571. EXPECT_EQ(StatusCode::OK_200, result->status);
  10572. std::this_thread::sleep_for(std::chrono::seconds(5));
  10573. result = cli.Get("/hi");
  10574. ASSERT_TRUE(result);
  10575. EXPECT_EQ(StatusCode::OK_200, result->status);
  10576. }
  10577. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10578. Server svr;
  10579. svr.set_keep_alive_max_count(0);
  10580. std::set<int> remote_ports;
  10581. svr.Get("/hi", [&](const Request &req, Response &res) {
  10582. remote_ports.insert(req.remote_port);
  10583. res.set_content("hi", "text/plain");
  10584. });
  10585. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10586. auto se = detail::scope_exit([&] {
  10587. svr.stop();
  10588. listen_thread.join();
  10589. ASSERT_FALSE(svr.is_running());
  10590. });
  10591. svr.wait_until_ready();
  10592. Client cli(HOST, PORT);
  10593. cli.set_keep_alive(true);
  10594. for (int i = 0; i < 3; i++) {
  10595. auto res = cli.Get("/hi");
  10596. ASSERT_TRUE(res);
  10597. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10598. }
  10599. // All three over one connection
  10600. EXPECT_EQ(1u, remote_ports.size());
  10601. }
  10602. TEST(KeepAliveTest, Issue1959) {
  10603. Server svr;
  10604. svr.set_keep_alive_timeout(5);
  10605. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10606. res.set_content("a", "text/plain");
  10607. });
  10608. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10609. auto se = detail::scope_exit([&] {
  10610. if (!svr.is_running()) return;
  10611. svr.stop();
  10612. listen_thread.join();
  10613. ASSERT_FALSE(svr.is_running());
  10614. });
  10615. svr.wait_until_ready();
  10616. Client cli("localhost", PORT);
  10617. cli.set_keep_alive(true);
  10618. using namespace std::chrono;
  10619. auto start = steady_clock::now();
  10620. cli.Get("/a");
  10621. svr.stop();
  10622. listen_thread.join();
  10623. auto end = steady_clock::now();
  10624. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10625. EXPECT_LT(elapsed, 5000);
  10626. }
  10627. #ifdef CPPHTTPLIB_SSL_ENABLED
  10628. TEST(KeepAliveTest, SSLClientReconnection) {
  10629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10630. ASSERT_TRUE(svr.is_valid());
  10631. svr.set_keep_alive_timeout(1);
  10632. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10633. res.set_content("Hello World!", "text/plain");
  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. SSLClient cli(HOST, PORT);
  10643. cli.enable_server_certificate_verification(false);
  10644. cli.set_keep_alive(true);
  10645. auto result = cli.Get("/hi");
  10646. ASSERT_TRUE(result);
  10647. EXPECT_EQ(StatusCode::OK_200, result->status);
  10648. result = cli.Get("/hi");
  10649. ASSERT_TRUE(result);
  10650. EXPECT_EQ(StatusCode::OK_200, result->status);
  10651. std::this_thread::sleep_for(std::chrono::seconds(2));
  10652. // Recoonect
  10653. result = cli.Get("/hi");
  10654. ASSERT_TRUE(result);
  10655. EXPECT_EQ(StatusCode::OK_200, result->status);
  10656. result = cli.Get("/hi");
  10657. ASSERT_TRUE(result);
  10658. EXPECT_EQ(StatusCode::OK_200, result->status);
  10659. }
  10660. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10662. ASSERT_TRUE(svr.is_valid());
  10663. svr.set_keep_alive_timeout(1);
  10664. std::string content = "reconnect";
  10665. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10666. res.set_content("Hello World!", "text/plain");
  10667. });
  10668. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10669. auto se = detail::scope_exit([&] {
  10670. svr.stop();
  10671. listen_thread.join();
  10672. ASSERT_FALSE(svr.is_running());
  10673. });
  10674. svr.wait_until_ready();
  10675. SSLClient cli(HOST, PORT);
  10676. cli.enable_server_certificate_verification(false);
  10677. cli.set_keep_alive(true);
  10678. auto result = cli.Post(
  10679. "/hi", content.size(),
  10680. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10681. sink.write(content.c_str(), content.size());
  10682. return true;
  10683. },
  10684. "text/plain");
  10685. ASSERT_TRUE(result);
  10686. EXPECT_EQ(200, result->status);
  10687. std::this_thread::sleep_for(std::chrono::seconds(2));
  10688. // Recoonect
  10689. result = cli.Post(
  10690. "/hi", content.size(),
  10691. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10692. sink.write(content.c_str(), content.size());
  10693. return true;
  10694. },
  10695. "text/plain");
  10696. ASSERT_TRUE(result);
  10697. EXPECT_EQ(200, result->status);
  10698. result = cli.Post(
  10699. "/hi", content.size(),
  10700. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10701. sink.write(content.c_str(), content.size());
  10702. return true;
  10703. },
  10704. "text/plain");
  10705. ASSERT_TRUE(result);
  10706. EXPECT_EQ(200, result->status);
  10707. }
  10708. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10709. using namespace httplib::tls;
  10710. {
  10711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10712. ASSERT_TRUE(svr.is_valid());
  10713. svr.Get("/sni", [&](const Request &req, Response &res) {
  10714. std::string expected = req.sni();
  10715. EXPECT_EQ(expected, req.get_param_value("expected"));
  10716. res.set_content("ok", "text/plain");
  10717. });
  10718. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10719. auto se = detail::scope_exit([&] {
  10720. svr.stop();
  10721. listen_thread.join();
  10722. ASSERT_FALSE(svr.is_running());
  10723. });
  10724. svr.wait_until_ready();
  10725. {
  10726. SSLClient cli("localhost", PORT);
  10727. cli.enable_server_certificate_verification(false);
  10728. auto res = cli.Get("/sni?expected=localhost");
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. }
  10731. {
  10732. SSLClient cli("::1", PORT);
  10733. cli.enable_server_certificate_verification(false);
  10734. auto res = cli.Get("/sni?expected=");
  10735. // NOTE: This may fail if the server is listening on IPv4 only
  10736. // (e.g., when localhost resolves to 127.0.0.1 only)
  10737. if (res) {
  10738. EXPECT_EQ(StatusCode::OK_200, res->status);
  10739. } else {
  10740. EXPECT_EQ(Error::Connection, res.error());
  10741. }
  10742. }
  10743. }
  10744. }
  10745. #endif
  10746. TEST(ClientProblemDetectionTest, ContentProvider) {
  10747. Server svr;
  10748. size_t content_length = 1024 * 1024;
  10749. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10750. res.set_content_provider(
  10751. content_length, "text/plain",
  10752. [&](size_t offset, size_t length, DataSink &sink) {
  10753. auto out_len = std::min(length, static_cast<size_t>(1024));
  10754. std::string out(out_len, '@');
  10755. sink.write(out.data(), out_len);
  10756. return offset < 4096;
  10757. },
  10758. [](bool success) { ASSERT_FALSE(success); });
  10759. });
  10760. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10761. res.set_content_provider(
  10762. 0, "text/plain",
  10763. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10764. EXPECT_TRUE(false);
  10765. return true;
  10766. },
  10767. [](bool success) { ASSERT_FALSE(success); });
  10768. });
  10769. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10770. auto se = detail::scope_exit([&] {
  10771. svr.stop();
  10772. listen_thread.join();
  10773. ASSERT_FALSE(svr.is_running());
  10774. });
  10775. svr.wait_until_ready();
  10776. Client cli("localhost", PORT);
  10777. {
  10778. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10779. size_t /*data_length*/) { return false; });
  10780. ASSERT_FALSE(res);
  10781. }
  10782. {
  10783. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10784. size_t /*data_length*/) { return false; });
  10785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10786. }
  10787. }
  10788. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10789. // A provider that reports success without writing anything and without
  10790. // calling done() used to be handed the same offset and length again on every
  10791. // pass, so it spun for as long as the peer stayed connected.
  10792. Server svr;
  10793. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10794. res.set_content("ok", "text/plain");
  10795. });
  10796. auto port = svr.bind_to_any_port(HOST);
  10797. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. listen_thread.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. std::atomic<int> call_count{0};
  10805. Client cli(HOST, port);
  10806. auto res = cli.Post(
  10807. "/", 1024,
  10808. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10809. // Give up after enough passes to show the spin, so that losing the
  10810. // check below fails this test instead of hanging it.
  10811. return ++call_count < 100;
  10812. },
  10813. "text/plain");
  10814. ASSERT_FALSE(res);
  10815. EXPECT_EQ(Error::Write, res.error());
  10816. EXPECT_EQ(1, call_count.load());
  10817. }
  10818. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10819. // A writer only has to assign `write`. The other three used to be left as
  10820. // empty std::functions, so a provider calling one threw
  10821. // std::bad_function_call out of the thread running it and took the whole
  10822. // process down.
  10823. DataSink sink;
  10824. std::string written;
  10825. sink.write = [&](const char *data, size_t data_len) {
  10826. written.append(data, data_len);
  10827. return true;
  10828. };
  10829. EXPECT_TRUE(sink.is_writable());
  10830. sink.done();
  10831. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10832. EXPECT_TRUE(written.empty());
  10833. }
  10834. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10835. // A sink that cannot carry trailers still has to finish.
  10836. DataSink sink;
  10837. auto done_count = 0;
  10838. sink.done = [&]() { done_count++; };
  10839. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10840. EXPECT_EQ(1, done_count);
  10841. }
  10842. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10843. Server svr;
  10844. const std::string body(4096, 'x');
  10845. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10846. res.set_content_provider(body.size(), "text/plain",
  10847. [&](size_t offset, size_t length, DataSink &sink) {
  10848. sink.write(body.data() + offset, length);
  10849. sink.done();
  10850. return true;
  10851. });
  10852. });
  10853. auto port = svr.bind_to_any_port(HOST);
  10854. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10855. auto se = detail::scope_exit([&] {
  10856. svr.stop();
  10857. listen_thread.join();
  10858. ASSERT_FALSE(svr.is_running());
  10859. });
  10860. svr.wait_until_ready();
  10861. Client cli(HOST, port);
  10862. auto res = cli.Get("/");
  10863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10864. EXPECT_EQ(StatusCode::OK_200, res->status);
  10865. EXPECT_EQ(body, res->body);
  10866. }
  10867. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10868. Server svr;
  10869. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10870. res.set_content_provider(
  10871. 1024, "text/plain",
  10872. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10873. sink.write("hello", 5);
  10874. sink.done(); // short of the 1024 bytes the response promised
  10875. return true;
  10876. });
  10877. });
  10878. auto port = svr.bind_to_any_port(HOST);
  10879. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10880. auto se = detail::scope_exit([&] {
  10881. svr.stop();
  10882. listen_thread.join();
  10883. ASSERT_FALSE(svr.is_running());
  10884. });
  10885. svr.wait_until_ready();
  10886. Client cli(HOST, port);
  10887. cli.set_read_timeout(5, 0);
  10888. // The response is short of its Content-Length, so the client cannot read a
  10889. // complete body. What matters is that this returns at all: a no-op done()
  10890. // would leave the writer looping over a provider that never makes progress.
  10891. auto res = cli.Get("/");
  10892. EXPECT_FALSE(res);
  10893. }
  10894. // Read as the next response by a peer that sees it after a framed body.
  10895. static const std::string smuggled_response =
  10896. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  10897. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  10898. Server svr;
  10899. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10900. res.set_content_provider(
  10901. 5, "text/plain",
  10902. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10903. auto data = "AAAAA" + smuggled_response;
  10904. sink.write(data.data(), data.size());
  10905. return true;
  10906. });
  10907. });
  10908. thread t = thread([&] { svr.listen(HOST, PORT); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. t.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. std::string resp;
  10916. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10917. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  10918. resp.clear();
  10919. ASSERT_TRUE(send_request(
  10920. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  10921. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  10922. }
  10923. TEST(NoContentTest, BodyIsNotSent) {
  10924. Server svr;
  10925. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  10926. res.status = StatusCode::NoContent_204;
  10927. res.set_content(smuggled_response, "text/plain");
  10928. });
  10929. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  10930. res.status = StatusCode::NotModified_304;
  10931. res.set_chunked_content_provider(
  10932. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  10933. sink.write(smuggled_response.data(), smuggled_response.size());
  10934. sink.done();
  10935. return true;
  10936. });
  10937. });
  10938. thread t = thread([&] { svr.listen(HOST, PORT); });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. t.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. for (auto path : {"/204", "/304"}) {
  10946. std::string resp;
  10947. ASSERT_TRUE(send_request(
  10948. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  10949. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  10950. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  10951. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  10952. }
  10953. }
  10954. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  10955. Server svr;
  10956. std::atomic<bool> smuggled(false);
  10957. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10958. res.set_content("ok", "text/plain");
  10959. });
  10960. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  10961. smuggled = true;
  10962. });
  10963. auto port = svr.bind_to_any_port(HOST);
  10964. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. listen_thread.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. // What follows the body would be read as the next request.
  10972. Client cli(HOST, port);
  10973. auto res = cli.Post(
  10974. "/", 5,
  10975. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10976. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  10977. sink.write(data.data(), data.size());
  10978. return true;
  10979. },
  10980. "text/plain");
  10981. ASSERT_FALSE(res);
  10982. EXPECT_EQ(Error::Write, res.error());
  10983. EXPECT_FALSE(smuggled);
  10984. }
  10985. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10986. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10987. // The compressed path builds the whole body before connecting, so this
  10988. // fails client-side and never reaches a server.
  10989. Client cli(HOST, PORT);
  10990. cli.set_compress(true);
  10991. auto res = cli.Post(
  10992. "/", 1024,
  10993. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10994. sink.write("hello", 5);
  10995. sink.done(); // short of the 1024 bytes the request announced
  10996. return true;
  10997. },
  10998. "text/plain");
  10999. ASSERT_FALSE(res);
  11000. EXPECT_EQ(Error::Write, res.error());
  11001. }
  11002. #endif
  11003. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11004. Server svr;
  11005. svr.set_error_handler([](Request const &, Response &res) -> void {
  11006. res.set_chunked_content_provider(
  11007. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11008. sink.os << "hello";
  11009. sink.os << "world";
  11010. sink.done();
  11011. return true;
  11012. });
  11013. });
  11014. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11015. auto se = detail::scope_exit([&] {
  11016. svr.stop();
  11017. listen_thread.join();
  11018. ASSERT_FALSE(svr.is_running());
  11019. });
  11020. svr.wait_until_ready();
  11021. Client cli("localhost", PORT);
  11022. auto res = cli.Get("/");
  11023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11025. EXPECT_EQ("helloworld", res->body);
  11026. }
  11027. // A body set after a content provider must replace it, not be sent through it.
  11028. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11029. Server svr;
  11030. svr.set_mount_point("/", "./www");
  11031. svr.set_file_request_handler([](const Request &req, Response &res) {
  11032. if (req.path == "/dir/test.html") {
  11033. res.status = StatusCode::Forbidden_403;
  11034. res.set_content(std::string(5000, 'D'), "text/plain");
  11035. } else if (req.path == "/file") {
  11036. res.status = StatusCode::Forbidden_403;
  11037. res.body = "Denied";
  11038. }
  11039. });
  11040. auto port = svr.bind_to_any_port(HOST);
  11041. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11042. auto se = detail::scope_exit([&] {
  11043. svr.stop();
  11044. t.join();
  11045. ASSERT_FALSE(svr.is_running());
  11046. });
  11047. svr.wait_until_ready();
  11048. Client cli(HOST, port);
  11049. {
  11050. auto res = cli.Get("/dir/test.html");
  11051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11052. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11053. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11054. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11055. }
  11056. {
  11057. auto res = cli.Get("/file");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11060. EXPECT_EQ("Denied", res->body);
  11061. }
  11062. {
  11063. auto res = cli.Get("/dir/index.html");
  11064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11065. EXPECT_EQ(StatusCode::OK_200, res->status);
  11066. EXPECT_EQ(0U, res->body.find("<html>"));
  11067. }
  11068. }
  11069. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11070. Server svr;
  11071. std::vector<bool> released;
  11072. std::mutex released_mutex;
  11073. auto releaser = [&](bool success) {
  11074. std::lock_guard<std::mutex> guard(released_mutex);
  11075. released.push_back(success);
  11076. };
  11077. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11078. return sink.write(&"hello"[offset], length);
  11079. };
  11080. svr.Get("/sized", [&](const Request &, Response &res) {
  11081. res.status = StatusCode::NotFound_404;
  11082. res.set_content_provider(5, "text/plain", provider, releaser);
  11083. });
  11084. svr.Get("/chunked", [&](const Request &, Response &res) {
  11085. res.status = StatusCode::ServiceUnavailable_503;
  11086. res.set_chunked_content_provider(
  11087. "text/plain",
  11088. [](size_t, DataSink &sink) {
  11089. sink.os << "chunk";
  11090. sink.done();
  11091. return true;
  11092. },
  11093. releaser);
  11094. });
  11095. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11096. res.set_content_provider(5, "text/plain", provider, releaser);
  11097. throw std::runtime_error("after the provider");
  11098. });
  11099. svr.set_error_handler([](const Request &req, Response &res) {
  11100. // Leave the exception handler's content to it.
  11101. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11102. res.set_content(std::string(1000, 'E'), "text/html");
  11103. return Server::HandlerResponse::Handled;
  11104. });
  11105. svr.set_exception_handler(
  11106. [](const Request &, Response &res, std::exception_ptr) {
  11107. res.status = StatusCode::InternalServerError_500;
  11108. res.set_content(std::string(1000, 'X'), "text/html");
  11109. });
  11110. auto port = svr.bind_to_any_port(HOST);
  11111. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11112. auto se = detail::scope_exit([&] {
  11113. svr.stop();
  11114. t.join();
  11115. ASSERT_FALSE(svr.is_running());
  11116. });
  11117. svr.wait_until_ready();
  11118. Client cli(HOST, port);
  11119. {
  11120. auto res = cli.Get("/sized");
  11121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11123. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11124. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11125. }
  11126. {
  11127. auto res = cli.Get("/chunked");
  11128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11129. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11130. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11131. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11132. }
  11133. {
  11134. auto res = cli.Get("/throw");
  11135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11136. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11137. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11138. }
  11139. std::lock_guard<std::mutex> guard(released_mutex);
  11140. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11141. }
  11142. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11143. Server svr;
  11144. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11145. return sink.write(&"abc"[offset], length);
  11146. };
  11147. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11148. res.set_file_content("./www/dir/test.html");
  11149. res.set_content("body", "text/plain");
  11150. });
  11151. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11152. res.set_content(std::string(100, 'B'), "text/plain");
  11153. res.set_file_content("./www/dir/test.html");
  11154. });
  11155. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11156. res.set_content(std::string(100, 'B'), "text/plain");
  11157. res.set_content_provider(3, "text/plain", abc);
  11158. });
  11159. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11160. res.set_content_provider(3, "text/plain", abc);
  11161. res.set_content(std::string(100, 'B'), "text/plain");
  11162. });
  11163. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11164. res.set_content_provider(3, "text/plain", abc);
  11165. res.body = "direct";
  11166. });
  11167. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11168. res.set_file_content("./www/dir/test.html");
  11169. res.body = "direct";
  11170. });
  11171. auto port = svr.bind_to_any_port(HOST);
  11172. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11173. auto se = detail::scope_exit([&] {
  11174. svr.stop();
  11175. t.join();
  11176. ASSERT_FALSE(svr.is_running());
  11177. });
  11178. svr.wait_until_ready();
  11179. Client cli(HOST, port);
  11180. auto expect_body = [&](const char *path, const std::string &body) {
  11181. // Uncompressed, so Content-Length can be compared with the body.
  11182. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11183. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11184. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11185. EXPECT_EQ(body, res->body) << path;
  11186. EXPECT_EQ(std::to_string(body.size()),
  11187. res->get_header_value("Content-Length"))
  11188. << path;
  11189. };
  11190. expect_body("/file-then-body", "body");
  11191. expect_body("/body-then-file", "test.html");
  11192. expect_body("/body-then-provider", "abc");
  11193. expect_body("/provider-then-body", std::string(100, 'B'));
  11194. expect_body("/provider-then-direct-body", "direct");
  11195. expect_body("/file-then-direct-body", "direct");
  11196. // Ranges are checked against the body, not the dropped provider.
  11197. {
  11198. auto res = cli.Get("/provider-then-direct-body",
  11199. Headers{{make_range_header({{1, 2}})}});
  11200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11201. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11202. EXPECT_EQ("ir", res->body);
  11203. }
  11204. {
  11205. auto res = cli.Get("/file-then-direct-body",
  11206. Headers{{make_range_header({{7, 8}})}});
  11207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11208. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11209. }
  11210. }
  11211. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11212. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11213. const char *path = "./truncated_while_served.txt";
  11214. const size_t size = 32 * 1024 * 1024;
  11215. {
  11216. std::ofstream f(path, std::ios::binary);
  11217. f << std::string(size, 'x');
  11218. }
  11219. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11220. // Over TLS, where the bytes are encrypted in this process rather than
  11221. // copied by send().
  11222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11223. svr.Get("/file", [&](const Request &, Response &res) {
  11224. res.set_file_content(path, "text/plain");
  11225. });
  11226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11227. auto se = detail::scope_exit([&] {
  11228. svr.stop();
  11229. thread.join();
  11230. ASSERT_FALSE(svr.is_running());
  11231. });
  11232. svr.wait_until_ready();
  11233. // The file shrinks once the first bytes are in, as a rewrite in place
  11234. // would, and reading the mapping past its new end used to raise SIGBUS.
  11235. SSLClient cli(HOST, PORT);
  11236. cli.enable_server_certificate_verification(false);
  11237. size_t received = 0;
  11238. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11239. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11240. received += len;
  11241. return true;
  11242. });
  11243. EXPECT_FALSE(res);
  11244. EXPECT_LT(received, size);
  11245. }
  11246. #endif
  11247. // Forward declaration (see the base64_encode note).
  11248. namespace httplib {
  11249. namespace detail {
  11250. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11251. const std::string &content_type,
  11252. EncodingType encoding);
  11253. } // namespace detail
  11254. } // namespace httplib
  11255. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11256. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11257. ASSERT_TRUE(mm->is_open());
  11258. Response res;
  11259. detail::set_file_content_provider(res, mm, "text/html",
  11260. detail::EncodingType::None);
  11261. std::string out;
  11262. DataSink sink;
  11263. sink.write = [&](const char *d, size_t l) {
  11264. out.append(d, l);
  11265. return true;
  11266. };
  11267. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11268. EXPECT_EQ("test.html", out);
  11269. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11270. EXPECT_EQ("test.html", out);
  11271. }
  11272. TEST(LongPollingTest, ClientCloseDetection) {
  11273. Server svr;
  11274. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11275. res.set_chunked_content_provider(
  11276. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11277. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11278. sink.os << "hello";
  11279. auto count = 10;
  11280. while (count > 0 && sink.is_writable()) {
  11281. this_thread::sleep_for(chrono::milliseconds(10));
  11282. count--;
  11283. }
  11284. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11285. return true;
  11286. });
  11287. });
  11288. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11289. auto se = detail::scope_exit([&] {
  11290. svr.stop();
  11291. listen_thread.join();
  11292. ASSERT_FALSE(svr.is_running());
  11293. });
  11294. svr.wait_until_ready();
  11295. Client cli("localhost", PORT);
  11296. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11297. EXPECT_EQ("hello", string(data, data_length));
  11298. return false; // close the socket immediately.
  11299. });
  11300. ASSERT_FALSE(res);
  11301. }
  11302. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11303. Server svr;
  11304. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11305. res.set_chunked_content_provider(
  11306. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11307. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11308. sink.os << "hello";
  11309. EXPECT_TRUE(sink.os.good());
  11310. // Wait for the client to close the connection
  11311. auto count = 10;
  11312. while (count > 0 && sink.is_writable()) {
  11313. this_thread::sleep_for(chrono::milliseconds(10));
  11314. count--;
  11315. }
  11316. // After client disconnect, write repeatedly until the socket
  11317. // write actually fails (small writes may be absorbed by the
  11318. // kernel buffer)
  11319. std::string chunk(1024, 'x');
  11320. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11321. sink.os << chunk;
  11322. }
  11323. EXPECT_TRUE(sink.os.fail());
  11324. return true;
  11325. });
  11326. });
  11327. auto port = svr.bind_to_any_port("localhost");
  11328. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11329. auto se = detail::scope_exit([&] {
  11330. svr.stop();
  11331. listen_thread.join();
  11332. ASSERT_FALSE(svr.is_running());
  11333. });
  11334. svr.wait_until_ready();
  11335. Client cli("localhost", port);
  11336. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11337. EXPECT_EQ("hello", string(data, data_length));
  11338. return false; // close the socket immediately.
  11339. });
  11340. ASSERT_FALSE(res);
  11341. }
  11342. TEST(GetWithParametersTest, GetWithParameters) {
  11343. Server svr;
  11344. svr.Get("/", [&](const Request &req, Response &) {
  11345. EXPECT_EQ("world", req.get_param_value("hello"));
  11346. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11347. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11348. });
  11349. svr.Get("/params", [&](const Request &req, Response &) {
  11350. EXPECT_EQ("world", req.get_param_value("hello"));
  11351. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11352. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11353. });
  11354. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11355. EXPECT_EQ("resource-id", req.matches[1]);
  11356. EXPECT_EQ("foo", req.get_param_value("param1"));
  11357. EXPECT_EQ("bar", req.get_param_value("param2"));
  11358. });
  11359. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11360. EXPECT_EQ("user-id", req.path_params.at("id"));
  11361. EXPECT_EQ("foo", req.get_param_value("param1"));
  11362. EXPECT_EQ("bar", req.get_param_value("param2"));
  11363. });
  11364. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11365. auto se = detail::scope_exit([&] {
  11366. svr.stop();
  11367. listen_thread.join();
  11368. ASSERT_FALSE(svr.is_running());
  11369. });
  11370. svr.wait_until_ready();
  11371. {
  11372. Client cli(HOST, PORT);
  11373. Params params;
  11374. params.emplace("hello", "world");
  11375. params.emplace("hello2", "world2");
  11376. params.emplace("hello3", "world3");
  11377. auto res = cli.Get("/", params, Headers{});
  11378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11379. EXPECT_EQ(StatusCode::OK_200, res->status);
  11380. }
  11381. {
  11382. Client cli(HOST, PORT);
  11383. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11385. EXPECT_EQ(StatusCode::OK_200, res->status);
  11386. }
  11387. {
  11388. Client cli(HOST, PORT);
  11389. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. }
  11393. {
  11394. Client cli(HOST, PORT);
  11395. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11397. EXPECT_EQ(StatusCode::OK_200, res->status);
  11398. }
  11399. }
  11400. TEST(GetWithParametersTest, GetWithParameters2) {
  11401. Server svr;
  11402. svr.Get("/", [&](const Request &req, Response &res) {
  11403. auto text = req.get_param_value("hello");
  11404. res.set_content(text, "text/plain");
  11405. });
  11406. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11407. auto se = detail::scope_exit([&] {
  11408. svr.stop();
  11409. listen_thread.join();
  11410. ASSERT_FALSE(svr.is_running());
  11411. });
  11412. svr.wait_until_ready();
  11413. Client cli("localhost", PORT);
  11414. Params params;
  11415. params.emplace("hello", "world");
  11416. std::string body;
  11417. auto res = cli.Get("/", params, Headers{},
  11418. [&](const char *data, size_t data_length) {
  11419. body.append(data, data_length);
  11420. return true;
  11421. });
  11422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11423. EXPECT_EQ(StatusCode::OK_200, res->status);
  11424. EXPECT_EQ("world", body);
  11425. }
  11426. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11427. Server svr;
  11428. svr.Get("/search", [&](const Request &req, Response &res) {
  11429. auto q = req.get_param_value("q");
  11430. res.set_content(q, "text/plain");
  11431. });
  11432. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11433. auto se = detail::scope_exit([&] {
  11434. svr.stop();
  11435. listen_thread.join();
  11436. ASSERT_FALSE(svr.is_running());
  11437. });
  11438. svr.wait_until_ready();
  11439. Client cli("localhost", PORT);
  11440. // Verify that Get(path, params) works without requiring Headers argument
  11441. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11443. EXPECT_EQ(StatusCode::OK_200, res->status);
  11444. EXPECT_EQ("cpp-httplib", res->body);
  11445. }
  11446. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11447. auto host = "httpbingo.org";
  11448. auto path = std::string{"/range/32"};
  11449. #ifdef CPPHTTPLIB_SSL_ENABLED
  11450. SSLClient cli(host);
  11451. #else
  11452. Client cli(host);
  11453. #endif
  11454. cli.set_default_headers({make_range_header({{1, 10}})});
  11455. cli.set_connection_timeout(5);
  11456. {
  11457. auto res = cli.Get(path);
  11458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11459. EXPECT_EQ("bcdefghijk", res->body);
  11460. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11461. }
  11462. {
  11463. auto res = cli.Get(path);
  11464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11465. EXPECT_EQ("bcdefghijk", res->body);
  11466. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11467. }
  11468. }
  11469. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11470. Server svr;
  11471. svr.set_default_headers({{"Hello", "World"}});
  11472. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11473. res.set_content("ok", "text/plain");
  11474. });
  11475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11476. auto se = detail::scope_exit([&] {
  11477. svr.stop();
  11478. listen_thread.join();
  11479. ASSERT_FALSE(svr.is_running());
  11480. });
  11481. svr.wait_until_ready();
  11482. Client cli("localhost", PORT);
  11483. auto res = cli.Get("/");
  11484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. EXPECT_EQ("ok", res->body);
  11487. EXPECT_EQ("World", res->get_header_value("Hello"));
  11488. }
  11489. #ifdef CPPHTTPLIB_SSL_ENABLED
  11490. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11492. ASSERT_TRUE(svr.is_valid());
  11493. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11494. std::this_thread::sleep_for(std::chrono::seconds(2));
  11495. res.set_content("a", "text/plain");
  11496. });
  11497. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11498. res.set_content("b", "text/plain");
  11499. });
  11500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11501. auto se = detail::scope_exit([&] {
  11502. svr.stop();
  11503. listen_thread.join();
  11504. ASSERT_FALSE(svr.is_running());
  11505. });
  11506. svr.wait_until_ready();
  11507. SSLClient cli("localhost", PORT);
  11508. cli.enable_server_certificate_verification(false);
  11509. cli.set_keep_alive(true);
  11510. cli.set_read_timeout(std::chrono::seconds(1));
  11511. auto resa = cli.Get("/a");
  11512. ASSERT_TRUE(!resa);
  11513. EXPECT_EQ(Error::Read, resa.error());
  11514. auto resb = cli.Get("/b");
  11515. ASSERT_TRUE(resb);
  11516. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11517. EXPECT_EQ("b", resb->body);
  11518. }
  11519. // Closing an idle keep-alive connection sends close_notify and returns. The
  11520. // server must not wait for the client's close_notify: an idle client never
  11521. // sends one, so the worker would be held until the read timeout expires, and
  11522. // stop() would wait for it.
  11523. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11525. ASSERT_TRUE(svr.is_valid());
  11526. svr.set_keep_alive_timeout(1);
  11527. svr.set_read_timeout(10, 0);
  11528. svr.Get("/", [](const Request &, Response &res) {
  11529. res.set_content("ok", "text/plain");
  11530. });
  11531. auto port = svr.bind_to_any_port(HOST);
  11532. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11533. auto se = detail::scope_exit([&] {
  11534. if (listen_thread.joinable()) {
  11535. svr.stop();
  11536. listen_thread.join();
  11537. }
  11538. });
  11539. svr.wait_until_ready();
  11540. SSLClient cli(HOST, port);
  11541. cli.enable_server_certificate_verification(false);
  11542. cli.set_keep_alive(true);
  11543. auto res = cli.Get("/");
  11544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11545. EXPECT_EQ(StatusCode::OK_200, res->status);
  11546. // Stay idle past the keep-alive timeout so the server closes the connection.
  11547. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11548. auto start = std::chrono::steady_clock::now();
  11549. svr.stop();
  11550. listen_thread.join();
  11551. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11552. std::chrono::steady_clock::now() - start)
  11553. .count();
  11554. EXPECT_LT(elapsed, 3000);
  11555. }
  11556. #endif
  11557. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11558. protected:
  11559. ServerTestWithAI_PASSIVE()
  11560. : cli_(HOST, PORT)
  11561. #ifdef CPPHTTPLIB_SSL_ENABLED
  11562. ,
  11563. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11564. #endif
  11565. {
  11566. #ifdef CPPHTTPLIB_SSL_ENABLED
  11567. cli_.enable_server_certificate_verification(false);
  11568. #endif
  11569. }
  11570. virtual void SetUp() {
  11571. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11572. res.set_content("Hello World!", "text/plain");
  11573. });
  11574. t_ = thread(
  11575. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11576. svr_.wait_until_ready();
  11577. }
  11578. virtual void TearDown() {
  11579. svr_.stop();
  11580. t_.join();
  11581. }
  11582. #ifdef CPPHTTPLIB_SSL_ENABLED
  11583. SSLClient cli_;
  11584. SSLServer svr_;
  11585. #else
  11586. Client cli_;
  11587. Server svr_;
  11588. #endif
  11589. thread t_;
  11590. };
  11591. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11592. auto res = cli_.Get("/hi");
  11593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11594. EXPECT_EQ(StatusCode::OK_200, res->status);
  11595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11596. EXPECT_EQ("Hello World!", res->body);
  11597. }
  11598. class ServerUpDownTest : public ::testing::Test {
  11599. protected:
  11600. ServerUpDownTest() : cli_(HOST, PORT) {}
  11601. virtual void SetUp() {
  11602. t_ = thread([&]() {
  11603. svr_.bind_to_any_port(HOST);
  11604. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11605. ASSERT_TRUE(svr_.listen_after_bind());
  11606. });
  11607. svr_.wait_until_ready();
  11608. }
  11609. virtual void TearDown() {
  11610. svr_.stop();
  11611. t_.join();
  11612. }
  11613. Client cli_;
  11614. Server svr_;
  11615. thread t_;
  11616. };
  11617. TEST_F(ServerUpDownTest, QuickStartStop) {
  11618. // Should not crash, especially when run with
  11619. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11620. }
  11621. class PayloadMaxLengthTest : public ::testing::Test {
  11622. protected:
  11623. PayloadMaxLengthTest()
  11624. : cli_(HOST, PORT)
  11625. #ifdef CPPHTTPLIB_SSL_ENABLED
  11626. ,
  11627. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11628. #endif
  11629. {
  11630. #ifdef CPPHTTPLIB_SSL_ENABLED
  11631. cli_.enable_server_certificate_verification(false);
  11632. #endif
  11633. }
  11634. virtual void SetUp() {
  11635. svr_.set_payload_max_length(8);
  11636. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11637. res.set_content("test", "text/plain");
  11638. });
  11639. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11640. svr_.wait_until_ready();
  11641. }
  11642. virtual void TearDown() {
  11643. svr_.stop();
  11644. t_.join();
  11645. }
  11646. #ifdef CPPHTTPLIB_SSL_ENABLED
  11647. SSLClient cli_;
  11648. SSLServer svr_;
  11649. #else
  11650. Client cli_;
  11651. Server svr_;
  11652. #endif
  11653. thread t_;
  11654. };
  11655. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11656. auto res = cli_.Post("/test", "123456789", "text/plain");
  11657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11658. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11659. res = cli_.Post("/test", "12345678", "text/plain");
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::OK_200, res->status);
  11662. }
  11663. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11664. // Test chunked encoding with payload exceeding the 8-byte limit
  11665. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11666. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11669. }
  11670. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11671. // Test chunked encoding with payload within the 8-byte limit
  11672. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11673. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11675. EXPECT_EQ(StatusCode::OK_200, res->status);
  11676. }
  11677. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11678. // Test using send_request to send chunked data exceeding payload limit
  11679. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11680. "Host: " +
  11681. std::string(HOST) + ":" + std::to_string(PORT) +
  11682. "\r\n"
  11683. "Transfer-Encoding: chunked\r\n"
  11684. "Connection: close\r\n"
  11685. "\r\n"
  11686. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11687. "0123456789\r\n"
  11688. "0\r\n" // End chunk
  11689. "\r\n";
  11690. std::string response;
  11691. bool result = send_request(1, chunked_request, &response);
  11692. if (!result) {
  11693. // If send_request fails, it might be because the server closed the
  11694. // connection due to payload limit enforcement, which is acceptable
  11695. SUCCEED()
  11696. << "Server rejected oversized chunked request (connection closed)";
  11697. } else {
  11698. // If we got a response, check if it's an error response or connection was
  11699. // closed early Short response length indicates connection was closed due to
  11700. // payload limit
  11701. if (response.length() <= 10) {
  11702. SUCCEED() << "Server closed connection for oversized chunked request";
  11703. } else {
  11704. // Check for error status codes
  11705. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11706. response.find("Payload Too Large") != std::string::npos ||
  11707. response.find("400") != std::string::npos);
  11708. }
  11709. }
  11710. }
  11711. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11712. // Test request without Content-Length header exceeding payload limit
  11713. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11714. "Host: " +
  11715. std::string(HOST) + ":" +
  11716. std::to_string(PORT) +
  11717. "\r\n"
  11718. "Connection: close\r\n"
  11719. "\r\n";
  11720. // Add payload exceeding the 8-byte limit
  11721. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11722. request_without_content_length += large_payload;
  11723. std::string response;
  11724. bool result = send_request(1, request_without_content_length, &response);
  11725. if (!result) {
  11726. // If send_request fails, server likely closed connection due to payload
  11727. // limit
  11728. SUCCEED() << "Server rejected oversized request without Content-Length "
  11729. "(connection closed)";
  11730. } else {
  11731. // Check if server responded with error or closed connection early
  11732. if (response.length() <= 10) {
  11733. SUCCEED() << "Server closed connection for oversized request without "
  11734. "Content-Length";
  11735. } else {
  11736. // Check for error status codes
  11737. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11738. response.find("Payload Too Large") != std::string::npos ||
  11739. response.find("400") != std::string::npos);
  11740. }
  11741. }
  11742. }
  11743. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11744. // Test request without Content-Length header within payload limit
  11745. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11746. "Host: " +
  11747. std::string(HOST) + ":" +
  11748. std::to_string(PORT) +
  11749. "\r\n"
  11750. "Connection: close\r\n"
  11751. "\r\n";
  11752. // Add payload within the 8-byte limit
  11753. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11754. request_without_content_length += small_payload;
  11755. std::string response;
  11756. bool result = send_request(1, request_without_content_length, &response);
  11757. // For requests without Content-Length, the server may have different behavior
  11758. // The key is that it should not reject due to payload limit for small
  11759. // payloads
  11760. if (result) {
  11761. // Check for any HTTP response (success or error, but not connection closed)
  11762. if (response.length() > 10) {
  11763. SUCCEED()
  11764. << "Server processed request without Content-Length within limit";
  11765. } else {
  11766. // Short response might indicate connection closed, which is acceptable
  11767. SUCCEED() << "Server closed connection for request without "
  11768. "Content-Length (acceptable behavior)";
  11769. }
  11770. } else {
  11771. // Connection failure might be due to protocol requirements
  11772. SUCCEED() << "Connection issue with request without Content-Length "
  11773. "(environment-specific)";
  11774. }
  11775. }
  11776. class LargePayloadMaxLengthTest : public ::testing::Test {
  11777. protected:
  11778. LargePayloadMaxLengthTest()
  11779. : cli_(HOST, PORT)
  11780. #ifdef CPPHTTPLIB_SSL_ENABLED
  11781. ,
  11782. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11783. #endif
  11784. {
  11785. #ifdef CPPHTTPLIB_SSL_ENABLED
  11786. cli_.enable_server_certificate_verification(false);
  11787. #endif
  11788. }
  11789. virtual void SetUp() {
  11790. // Set 10MB payload limit
  11791. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11792. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11793. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11794. res.set_content("Large payload test", "text/plain");
  11795. });
  11796. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11797. svr_.wait_until_ready();
  11798. }
  11799. virtual void TearDown() {
  11800. svr_.stop();
  11801. t_.join();
  11802. }
  11803. #ifdef CPPHTTPLIB_SSL_ENABLED
  11804. SSLClient cli_;
  11805. SSLServer svr_;
  11806. #else
  11807. Client cli_;
  11808. Server svr_;
  11809. #endif
  11810. thread t_;
  11811. };
  11812. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11813. // Test chunked encoding with payload within 10MB limit
  11814. std::string medium_payload(5 * 1024 * 1024,
  11815. 'A'); // 5MB payload, within 10MB limit
  11816. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11818. EXPECT_EQ(StatusCode::OK_200, res->status);
  11819. }
  11820. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11821. // Test chunked encoding with payload exceeding 10MB limit
  11822. std::string large_payload(12 * 1024 * 1024,
  11823. 'B'); // 12MB payload, exceeds 10MB limit
  11824. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11825. // Server may either return 413 or close the connection
  11826. if (res) {
  11827. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11828. } else {
  11829. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11830. }
  11831. }
  11832. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11833. // Test request without Content-Length header within 10MB limit
  11834. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11835. "Host: " +
  11836. std::string(HOST) + ":" +
  11837. std::to_string(PORT) +
  11838. "\r\n"
  11839. "Connection: close\r\n"
  11840. "\r\n";
  11841. // Add 1MB payload (within 10MB limit)
  11842. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11843. request_without_content_length += medium_payload;
  11844. std::string response;
  11845. bool result = send_request(5, request_without_content_length, &response);
  11846. if (result) {
  11847. // Should get a proper HTTP response for payloads within limit
  11848. if (response.length() > 10) {
  11849. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11850. "10MB limit";
  11851. } else {
  11852. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11853. "Content-Length)";
  11854. }
  11855. } else {
  11856. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11857. }
  11858. }
  11859. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11860. // Test request without Content-Length header exceeding 10MB limit
  11861. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11862. "Host: " +
  11863. std::string(HOST) + ":" +
  11864. std::to_string(PORT) +
  11865. "\r\n"
  11866. "Connection: close\r\n"
  11867. "\r\n";
  11868. // Add 12MB payload (exceeds 10MB limit)
  11869. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11870. request_without_content_length += large_payload;
  11871. std::string response;
  11872. bool result = send_request(10, request_without_content_length, &response);
  11873. if (!result) {
  11874. // Server should close connection due to payload limit
  11875. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11876. "(connection closed)";
  11877. } else {
  11878. // Check for error response
  11879. if (response.length() <= 10) {
  11880. SUCCEED()
  11881. << "Server closed connection for 12MB request exceeding 10MB limit";
  11882. } else {
  11883. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11884. response.find("Payload Too Large") != std::string::npos ||
  11885. response.find("400") != std::string::npos);
  11886. }
  11887. }
  11888. }
  11889. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11890. Server svr;
  11891. svr.Get("/", [](const Request &, Response &res) {
  11892. // Claims far more than it sends, then drops the connection.
  11893. res.set_content_provider(size_t(1) << 41, "text/plain",
  11894. [](size_t, size_t, DataSink &sink) {
  11895. sink.write("abc", 3);
  11896. return false;
  11897. });
  11898. });
  11899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11900. auto se = detail::scope_exit([&] {
  11901. svr.stop();
  11902. thread.join();
  11903. ASSERT_FALSE(svr.is_running());
  11904. });
  11905. svr.wait_until_ready();
  11906. Client cli(HOST, PORT);
  11907. cli.set_payload_max_length(0);
  11908. EXPECT_FALSE(cli.Get("/"));
  11909. }
  11910. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11911. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11912. // path.
  11913. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11914. Server svr;
  11915. const size_t LIMIT = 64 * 1024; // 64KB
  11916. svr.set_payload_max_length(LIMIT);
  11917. size_t total = 0;
  11918. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11919. const ContentReader &content_reader) {
  11920. content_reader([&](const char * /*data*/, size_t len) {
  11921. total += len;
  11922. return true;
  11923. });
  11924. res.status = 200;
  11925. res.set_content("stream_ok", "text/plain");
  11926. });
  11927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11928. auto se = detail::scope_exit([&] {
  11929. svr.stop();
  11930. thread.join();
  11931. ASSERT_FALSE(svr.is_running());
  11932. });
  11933. svr.wait_until_ready();
  11934. // Prepare 256KB raw data and gzip-compress it
  11935. std::string raw(256 * 1024, 'A');
  11936. std::string gz;
  11937. {
  11938. z_stream zs{};
  11939. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11940. Z_DEFAULT_STRATEGY);
  11941. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11942. zs.avail_in = static_cast<uInt>(raw.size());
  11943. char outbuf[4096];
  11944. int ret;
  11945. do {
  11946. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11947. zs.avail_out = sizeof(outbuf);
  11948. ret = deflate(&zs, Z_FINISH);
  11949. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11950. } while (ret != Z_STREAM_END);
  11951. deflateEnd(&zs);
  11952. }
  11953. Client cli(HOST, PORT);
  11954. cli.set_connection_timeout(std::chrono::seconds(5));
  11955. Headers headers = {{"Content-Encoding", "gzip"}};
  11956. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11957. "application/octet-stream");
  11958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11959. // Server must reject oversized decompressed payloads with 413.
  11960. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11961. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11962. EXPECT_LE(total, LIMIT);
  11963. }
  11964. #ifndef CPPHTTPLIB_SSL_ENABLED
  11965. // For a request with neither Content-Length nor Transfer-Encoding, the
  11966. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11967. // compressed wire bytes straight to the ContentReader without ever routing
  11968. // them through the decompressor, so payload_max_length_ only bounded the
  11969. // compressed size on the wire, not the decompressed size.
  11970. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11971. Server svr;
  11972. const size_t LIMIT = 64 * 1024; // 64KB
  11973. svr.set_payload_max_length(LIMIT);
  11974. size_t total = 0;
  11975. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11976. const ContentReader &content_reader) {
  11977. content_reader([&](const char * /*data*/, size_t len) {
  11978. total += len;
  11979. return true;
  11980. });
  11981. res.status = 200;
  11982. res.set_content("stream_ok", "text/plain");
  11983. });
  11984. auto port = svr.bind_to_any_port(HOST);
  11985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11986. auto se = detail::scope_exit([&] {
  11987. svr.stop();
  11988. thread.join();
  11989. ASSERT_FALSE(svr.is_running());
  11990. });
  11991. svr.wait_until_ready();
  11992. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11993. // StreamingGzipDecompression test above.
  11994. std::string raw(256 * 1024, 'A');
  11995. std::string gz;
  11996. {
  11997. httplib::detail::gzip_compressor compressor;
  11998. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11999. [&](const char *chunk, size_t len) {
  12000. gz.append(chunk, len);
  12001. return true;
  12002. });
  12003. ASSERT_TRUE(result);
  12004. }
  12005. // Send the gzip body over raw TCP with neither Content-Length nor
  12006. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12007. // kicks in.
  12008. std::string req = "POST /stream HTTP/1.1\r\n"
  12009. "Host: " +
  12010. std::string(HOST) + ":" + std::to_string(port) +
  12011. "\r\n"
  12012. "Content-Encoding: gzip\r\n"
  12013. "Connection: close\r\n"
  12014. "\r\n" +
  12015. gz;
  12016. std::string response;
  12017. ASSERT_TRUE(send_request(5, req, &response, port));
  12018. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12019. EXPECT_LE(total, LIMIT);
  12020. }
  12021. #endif
  12022. #endif
  12023. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12024. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12025. // the payload must be passed through untouched instead of being rejected.
  12026. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12027. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12028. Server svr;
  12029. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12030. res.set_content(body, "image/jpeg");
  12031. res.set_header("Content-Encoding", "UTF-8");
  12032. });
  12033. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12034. res.set_content(body, "image/jpeg");
  12035. res.set_header("Content-Encoding", "identity");
  12036. });
  12037. svr.Post("/echo", [](const Request &req, Response &res) {
  12038. res.set_content(req.body, "image/jpeg");
  12039. });
  12040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12041. auto se = detail::scope_exit([&] {
  12042. svr.stop();
  12043. t.join();
  12044. ASSERT_FALSE(svr.is_running());
  12045. });
  12046. svr.wait_until_ready();
  12047. Client cli(HOST, PORT);
  12048. {
  12049. auto res = cli.Get("/image");
  12050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12051. EXPECT_EQ(StatusCode::OK_200, res->status);
  12052. EXPECT_EQ(body, res->body);
  12053. }
  12054. {
  12055. auto res = cli.Get("/identity");
  12056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12057. EXPECT_EQ(StatusCode::OK_200, res->status);
  12058. EXPECT_EQ(body, res->body);
  12059. }
  12060. {
  12061. // The same applies to a request body reaching the server.
  12062. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12063. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12065. EXPECT_EQ(StatusCode::OK_200, res->status);
  12066. EXPECT_EQ(body, res->body);
  12067. }
  12068. }
  12069. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12070. // gzip-encoded response even when the build has no zlib support.
  12071. static const char GZIPPED_HELLO_WORLD[] = {
  12072. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12073. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12074. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12075. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12076. // A content coding is a whole token, not something the field value merely
  12077. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12078. // as "fibre" look like Brotli, and turned a multi-coding value like
  12079. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12080. // it was never meant to see.
  12081. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12082. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12083. Server svr;
  12084. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12085. res.set_content(body, "image/jpeg");
  12086. res.set_header("Content-Encoding", "fibre");
  12087. });
  12088. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12089. res.set_content(body, "image/jpeg");
  12090. res.set_header("Content-Encoding", "gzip, br");
  12091. });
  12092. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12093. res.set_content(body, "image/jpeg");
  12094. res.set_header("Content-Encoding", "x-zstd-ish");
  12095. });
  12096. auto port = svr.bind_to_any_port(HOST);
  12097. thread t = thread([&]() { svr.listen_after_bind(); });
  12098. auto se = detail::scope_exit([&] {
  12099. svr.stop();
  12100. t.join();
  12101. ASSERT_FALSE(svr.is_running());
  12102. });
  12103. svr.wait_until_ready();
  12104. Client cli(HOST, port);
  12105. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12106. auto res = cli.Get(path);
  12107. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12108. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12109. // Not a coding we recognize, so the payload comes back untouched
  12110. EXPECT_EQ(body, res->body) << path;
  12111. }
  12112. }
  12113. // A content coding cpp-httplib recognizes but was not built with must be
  12114. // reported as such. Handing the still-compressed payload back to the caller
  12115. // would silently corrupt it.
  12116. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12117. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12118. Server svr;
  12119. // "image/jpeg" keeps the server from applying a content coding of its own,
  12120. // so the hand-crafted Content-Encoding below survives.
  12121. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12122. res.set_content(gzipped, "image/jpeg");
  12123. res.set_header("Content-Encoding", "gzip");
  12124. });
  12125. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12126. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12127. res.set_content(gzipped, "image/jpeg");
  12128. res.set_header("Content-Encoding", "GZIP");
  12129. });
  12130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12131. auto se = detail::scope_exit([&] {
  12132. svr.stop();
  12133. t.join();
  12134. ASSERT_FALSE(svr.is_running());
  12135. });
  12136. svr.wait_until_ready();
  12137. Client cli(HOST, PORT);
  12138. {
  12139. auto res = cli.Get("/gzipped");
  12140. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12142. EXPECT_EQ("Hello World!", res->body);
  12143. #else
  12144. ASSERT_FALSE(res);
  12145. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12146. #endif
  12147. }
  12148. {
  12149. // open_stream() must behave the same way.
  12150. auto handle = cli.open_stream("GET", "/gzipped");
  12151. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12152. ASSERT_TRUE(handle.is_valid());
  12153. std::string received;
  12154. char buf[256];
  12155. ssize_t n;
  12156. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12157. received.append(buf, static_cast<size_t>(n));
  12158. }
  12159. EXPECT_EQ("Hello World!", received);
  12160. #else
  12161. EXPECT_FALSE(handle.is_valid());
  12162. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12163. #endif
  12164. }
  12165. {
  12166. // A differently-cased coding must not be mistaken for an unknown one, or
  12167. // the body would be handed back still compressed.
  12168. auto res = cli.Get("/gzipped-uppercase");
  12169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12171. EXPECT_EQ("Hello World!", res->body);
  12172. #else
  12173. ASSERT_FALSE(res);
  12174. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12175. #endif
  12176. }
  12177. }
  12178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12179. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12180. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12181. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12182. // body a second time and appending a second Content-Encoding field line, so
  12183. // clients that decode one coding per listed value handed back raw gzip bytes.
  12184. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12185. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12186. Server svr;
  12187. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12188. // keeps the server from applying a coding of its own.
  12189. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12190. res.set_content(gzipped, "text/plain");
  12191. res.set_header("Content-Encoding", "gzip");
  12192. });
  12193. auto port = svr.bind_to_any_port(HOST);
  12194. thread t = thread([&]() { svr.listen_after_bind(); });
  12195. auto se = detail::scope_exit([&] {
  12196. svr.stop();
  12197. t.join();
  12198. ASSERT_FALSE(svr.is_running());
  12199. });
  12200. svr.wait_until_ready();
  12201. Client cli(HOST, port);
  12202. Headers headers = {{"Accept-Encoding", "gzip"}};
  12203. auto res = cli.Get("/pre-gzipped", headers);
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12205. EXPECT_EQ(StatusCode::OK_200, res->status);
  12206. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12207. EXPECT_EQ("Hello World!", res->body);
  12208. }
  12209. // A chunked provider settles its coding where the headers are written and
  12210. // reuses it at write time. Both ends of that have to hold: a handler's own
  12211. // Content-Encoding suppresses the coding, and a response without one is still
  12212. // compressed as it always was.
  12213. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12214. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12215. const std::string plain = "Hello World! Hello World! Hello World!";
  12216. Server svr;
  12217. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12218. res.set_header("Content-Encoding", "gzip");
  12219. res.set_chunked_content_provider(
  12220. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12221. sink.write(gzipped.data(), gzipped.size());
  12222. sink.done();
  12223. return true;
  12224. });
  12225. });
  12226. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12227. res.set_chunked_content_provider(
  12228. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12229. sink.write(plain.data(), plain.size());
  12230. sink.done();
  12231. return true;
  12232. });
  12233. });
  12234. auto port = svr.bind_to_any_port(HOST);
  12235. thread t = thread([&]() { svr.listen_after_bind(); });
  12236. auto se = detail::scope_exit([&] {
  12237. svr.stop();
  12238. t.join();
  12239. ASSERT_FALSE(svr.is_running());
  12240. });
  12241. svr.wait_until_ready();
  12242. Client cli(HOST, port);
  12243. Headers headers = {{"Accept-Encoding", "gzip"}};
  12244. {
  12245. auto res = cli.Get("/pre-gzipped", headers);
  12246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12247. EXPECT_EQ(StatusCode::OK_200, res->status);
  12248. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12249. EXPECT_EQ("Hello World!", res->body);
  12250. }
  12251. {
  12252. auto res = cli.Get("/negotiated", headers);
  12253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12254. EXPECT_EQ(StatusCode::OK_200, res->status);
  12255. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12256. EXPECT_EQ(plain, res->body);
  12257. }
  12258. }
  12259. #endif
  12260. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12261. // the same message as the comma-joined one, so both have to be read the same
  12262. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12263. // single gzip coding, and a body the sender says was encoded twice was handed
  12264. // back after one pass, still compressed but presented as decoded.
  12265. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12266. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12267. Server svr;
  12268. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12269. res.set_content(body, "image/jpeg");
  12270. res.headers.emplace("Content-Encoding", "gzip");
  12271. res.headers.emplace("Content-Encoding", "gzip");
  12272. });
  12273. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12274. res.set_content(body, "image/jpeg");
  12275. res.set_header("Content-Encoding", "gzip, gzip");
  12276. });
  12277. auto port = svr.bind_to_any_port(HOST);
  12278. thread t = thread([&]() { svr.listen_after_bind(); });
  12279. auto se = detail::scope_exit([&] {
  12280. svr.stop();
  12281. t.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. Client cli(HOST, port);
  12286. // Two codings is not something cpp-httplib decodes, so both representations
  12287. // take the pass-through path rather than one of them being gunzipped once.
  12288. for (const char *path : {"/split", "/joined"}) {
  12289. auto res = cli.Get(path);
  12290. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12291. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12292. EXPECT_EQ(body, res->body) << path;
  12293. }
  12294. }
  12295. // Regression test for DoS vulnerability: a malicious server sending a response
  12296. // without Content-Length header must not cause unbounded memory consumption on
  12297. // the client side. The client should stop reading after a reasonable limit,
  12298. // similar to the server-side set_payload_max_length protection.
  12299. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12300. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12301. #ifndef _WIN32
  12302. signal(SIGPIPE, SIG_IGN);
  12303. #endif
  12304. auto server_thread = std::thread([] {
  12305. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12306. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12307. default_socket_options(srv);
  12308. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12309. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12310. sockaddr_in addr{};
  12311. addr.sin_family = AF_INET;
  12312. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12313. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12314. int opt = 1;
  12315. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12316. #ifdef _WIN32
  12317. reinterpret_cast<const char *>(&opt),
  12318. #else
  12319. &opt,
  12320. #endif
  12321. sizeof(opt));
  12322. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12323. ::listen(srv, 1);
  12324. sockaddr_in cli_addr{};
  12325. socklen_t cli_len = sizeof(cli_addr);
  12326. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12327. if (cli != INVALID_SOCKET) {
  12328. char buf[4096];
  12329. ::recv(cli, buf, sizeof(buf), 0);
  12330. // Malicious response: no Content-Length, no chunked encoding
  12331. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12332. "Connection: close\r\n"
  12333. "\r\n";
  12334. ::send(cli,
  12335. #ifdef _WIN32
  12336. static_cast<const char *>(response_header.c_str()),
  12337. static_cast<int>(response_header.size()),
  12338. #else
  12339. response_header.c_str(), response_header.size(),
  12340. #endif
  12341. 0);
  12342. // Send 10MB of data
  12343. std::string chunk(64 * 1024, 'A');
  12344. size_t total_sent = 0;
  12345. while (total_sent < MALICIOUS_DATA_SIZE) {
  12346. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12347. auto sent = ::send(cli,
  12348. #ifdef _WIN32
  12349. static_cast<const char *>(chunk.c_str()),
  12350. static_cast<int>(to_send),
  12351. #else
  12352. chunk.c_str(), to_send,
  12353. #endif
  12354. 0);
  12355. if (sent <= 0) break;
  12356. total_sent += static_cast<size_t>(sent);
  12357. }
  12358. detail::close_socket(cli);
  12359. }
  12360. detail::close_socket(srv);
  12361. });
  12362. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12363. size_t total_read = 0;
  12364. {
  12365. Client cli("127.0.0.1", PORT + 2);
  12366. cli.set_read_timeout(5, 0);
  12367. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12368. auto stream = cli.open_stream("GET", "/malicious");
  12369. ASSERT_TRUE(stream.is_valid());
  12370. char buffer[64 * 1024];
  12371. ssize_t n;
  12372. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12373. total_read += static_cast<size_t>(n);
  12374. }
  12375. } // StreamHandle and Client destroyed here, closing the socket
  12376. server_thread.join();
  12377. // With set_payload_max_length, the client must stop reading before consuming
  12378. // all 10MB. The read loop should be cut off at or near the configured limit.
  12379. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12380. << "Client read " << total_read << " bytes, exceeding the configured "
  12381. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12382. }
  12383. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12384. // the entire response body without truncation.
  12385. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12386. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12387. #ifndef _WIN32
  12388. signal(SIGPIPE, SIG_IGN);
  12389. #endif
  12390. auto server_thread = std::thread([] {
  12391. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12392. default_socket_options(srv);
  12393. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12394. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12395. sockaddr_in addr{};
  12396. addr.sin_family = AF_INET;
  12397. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12398. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12399. int opt = 1;
  12400. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12401. #ifdef _WIN32
  12402. reinterpret_cast<const char *>(&opt),
  12403. #else
  12404. &opt,
  12405. #endif
  12406. sizeof(opt));
  12407. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12408. ::listen(srv, 1);
  12409. sockaddr_in cli_addr{};
  12410. socklen_t cli_len = sizeof(cli_addr);
  12411. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12412. if (cli != INVALID_SOCKET) {
  12413. char buf[4096];
  12414. ::recv(cli, buf, sizeof(buf), 0);
  12415. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12416. "Connection: close\r\n"
  12417. "\r\n";
  12418. ::send(cli,
  12419. #ifdef _WIN32
  12420. static_cast<const char *>(response_header.c_str()),
  12421. static_cast<int>(response_header.size()),
  12422. #else
  12423. response_header.c_str(), response_header.size(),
  12424. #endif
  12425. 0);
  12426. std::string chunk(64 * 1024, 'A');
  12427. size_t total_sent = 0;
  12428. while (total_sent < DATA_SIZE) {
  12429. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12430. auto sent = ::send(cli,
  12431. #ifdef _WIN32
  12432. static_cast<const char *>(chunk.c_str()),
  12433. static_cast<int>(to_send),
  12434. #else
  12435. chunk.c_str(), to_send,
  12436. #endif
  12437. 0);
  12438. if (sent <= 0) break;
  12439. total_sent += static_cast<size_t>(sent);
  12440. }
  12441. #ifdef _WIN32
  12442. ::shutdown(cli, SD_SEND);
  12443. #else
  12444. ::shutdown(cli, SHUT_WR);
  12445. #endif
  12446. // Drain until the client closes its end, ensuring all data is delivered
  12447. char drain[1024];
  12448. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12449. detail::close_socket(cli);
  12450. }
  12451. detail::close_socket(srv);
  12452. });
  12453. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12454. size_t total_read = 0;
  12455. {
  12456. Client cli("127.0.0.1", PORT + 2);
  12457. cli.set_read_timeout(5, 0);
  12458. cli.set_payload_max_length(0); // 0 means no limit
  12459. auto stream = cli.open_stream("GET", "/data");
  12460. ASSERT_TRUE(stream.is_valid());
  12461. char buffer[64 * 1024];
  12462. ssize_t n;
  12463. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12464. total_read += static_cast<size_t>(n);
  12465. }
  12466. }
  12467. server_thread.join();
  12468. EXPECT_EQ(total_read, DATA_SIZE)
  12469. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12470. << " bytes without truncation, but only read " << total_read << " bytes.";
  12471. }
  12472. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12473. // enormous Content-Length must not cause the client to pre-allocate a huge
  12474. // response body buffer. The reservation is capped at payload_max_length_, and
  12475. // the read itself fails when the body exceeds the limit.
  12476. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12477. #ifndef _WIN32
  12478. signal(SIGPIPE, SIG_IGN);
  12479. #endif
  12480. auto server_thread = std::thread([] {
  12481. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12482. default_socket_options(srv);
  12483. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12484. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12485. sockaddr_in addr{};
  12486. addr.sin_family = AF_INET;
  12487. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12488. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12489. int opt = 1;
  12490. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12491. #ifdef _WIN32
  12492. reinterpret_cast<const char *>(&opt),
  12493. #else
  12494. &opt,
  12495. #endif
  12496. sizeof(opt));
  12497. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12498. ::listen(srv, 1);
  12499. sockaddr_in cli_addr{};
  12500. socklen_t cli_len = sizeof(cli_addr);
  12501. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12502. if (cli != INVALID_SOCKET) {
  12503. char buf[4096];
  12504. ::recv(cli, buf, sizeof(buf), 0);
  12505. // Malicious response: claim a 20GB body but send only a tiny payload.
  12506. std::string response = "HTTP/1.1 200 OK\r\n"
  12507. "Content-Length: 20000000000\r\n"
  12508. "\r\n"
  12509. "abc";
  12510. ::send(cli,
  12511. #ifdef _WIN32
  12512. static_cast<const char *>(response.c_str()),
  12513. static_cast<int>(response.size()),
  12514. #else
  12515. response.c_str(), response.size(),
  12516. #endif
  12517. 0);
  12518. detail::close_socket(cli);
  12519. }
  12520. detail::close_socket(srv);
  12521. });
  12522. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12523. {
  12524. Client cli("127.0.0.1", PORT + 2);
  12525. cli.set_read_timeout(5, 0);
  12526. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12527. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12528. // (server claims more bytes than payload_max_length permits), but it must
  12529. // not exhaust memory before getting there.
  12530. auto res = cli.Get("/malicious");
  12531. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12532. }
  12533. server_thread.join();
  12534. }
  12535. // Verify that content_receiver bypasses the default payload_max_length,
  12536. // allowing streaming downloads larger than 100MB without requiring an explicit
  12537. // set_payload_max_length call.
  12538. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12539. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12540. #ifndef _WIN32
  12541. signal(SIGPIPE, SIG_IGN);
  12542. #endif
  12543. auto server_thread = std::thread([] {
  12544. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12545. default_socket_options(srv);
  12546. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12547. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12548. sockaddr_in addr{};
  12549. addr.sin_family = AF_INET;
  12550. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12551. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12552. int opt = 1;
  12553. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12554. #ifdef _WIN32
  12555. reinterpret_cast<const char *>(&opt),
  12556. #else
  12557. &opt,
  12558. #endif
  12559. sizeof(opt));
  12560. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12561. ::listen(srv, 1);
  12562. sockaddr_in cli_addr{};
  12563. socklen_t cli_len = sizeof(cli_addr);
  12564. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12565. if (cli != INVALID_SOCKET) {
  12566. char buf[4096];
  12567. ::recv(cli, buf, sizeof(buf), 0);
  12568. // Response with Content-Length larger than default 100MB limit
  12569. auto content_length = std::to_string(DATA_SIZE);
  12570. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12571. "Content-Length: " +
  12572. content_length +
  12573. "\r\n"
  12574. "Connection: close\r\n"
  12575. "\r\n";
  12576. ::send(cli,
  12577. #ifdef _WIN32
  12578. static_cast<const char *>(response_header.c_str()),
  12579. static_cast<int>(response_header.size()),
  12580. #else
  12581. response_header.c_str(), response_header.size(),
  12582. #endif
  12583. 0);
  12584. std::string chunk(64 * 1024, 'A');
  12585. size_t total_sent = 0;
  12586. while (total_sent < DATA_SIZE) {
  12587. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12588. auto sent = ::send(cli,
  12589. #ifdef _WIN32
  12590. static_cast<const char *>(chunk.c_str()),
  12591. static_cast<int>(to_send),
  12592. #else
  12593. chunk.c_str(), to_send,
  12594. #endif
  12595. 0);
  12596. if (sent <= 0) break;
  12597. total_sent += static_cast<size_t>(sent);
  12598. }
  12599. detail::close_socket(cli);
  12600. }
  12601. detail::close_socket(srv);
  12602. });
  12603. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12604. size_t total_received = 0;
  12605. {
  12606. Client cli("127.0.0.1", PORT + 2);
  12607. cli.set_read_timeout(10, 0);
  12608. // Do NOT call set_payload_max_length — use the default 100MB limit
  12609. auto res =
  12610. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12611. total_received += data_length;
  12612. return true;
  12613. });
  12614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12615. EXPECT_EQ(StatusCode::OK_200, res->status);
  12616. }
  12617. server_thread.join();
  12618. EXPECT_EQ(total_received, DATA_SIZE)
  12619. << "With content_receiver, the client should read all " << DATA_SIZE
  12620. << " bytes despite the default 100MB payload_max_length, but only read "
  12621. << total_received << " bytes.";
  12622. }
  12623. // Verify that an explicit set_payload_max_length smaller than the response is
  12624. // enforced even when a content_receiver is used.
  12625. TEST(ClientVulnerabilityTest,
  12626. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12627. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12628. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12629. #ifndef _WIN32
  12630. signal(SIGPIPE, SIG_IGN);
  12631. #endif
  12632. auto server_thread = std::thread([] {
  12633. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12634. default_socket_options(srv);
  12635. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12636. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12637. sockaddr_in addr{};
  12638. addr.sin_family = AF_INET;
  12639. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12640. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12641. int opt = 1;
  12642. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12643. #ifdef _WIN32
  12644. reinterpret_cast<const char *>(&opt),
  12645. #else
  12646. &opt,
  12647. #endif
  12648. sizeof(opt));
  12649. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12650. ::listen(srv, 1);
  12651. sockaddr_in cli_addr{};
  12652. socklen_t cli_len = sizeof(cli_addr);
  12653. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12654. if (cli != INVALID_SOCKET) {
  12655. char buf[4096];
  12656. ::recv(cli, buf, sizeof(buf), 0);
  12657. auto content_length = std::to_string(DATA_SIZE);
  12658. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12659. "Content-Length: " +
  12660. content_length +
  12661. "\r\n"
  12662. "Connection: close\r\n"
  12663. "\r\n";
  12664. ::send(cli,
  12665. #ifdef _WIN32
  12666. static_cast<const char *>(response_header.c_str()),
  12667. static_cast<int>(response_header.size()),
  12668. #else
  12669. response_header.c_str(), response_header.size(),
  12670. #endif
  12671. 0);
  12672. std::string chunk(64 * 1024, 'A');
  12673. size_t total_sent = 0;
  12674. while (total_sent < DATA_SIZE) {
  12675. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12676. auto sent = ::send(cli,
  12677. #ifdef _WIN32
  12678. static_cast<const char *>(chunk.c_str()),
  12679. static_cast<int>(to_send),
  12680. #else
  12681. chunk.c_str(), to_send,
  12682. #endif
  12683. 0);
  12684. if (sent <= 0) break;
  12685. total_sent += static_cast<size_t>(sent);
  12686. }
  12687. detail::close_socket(cli);
  12688. }
  12689. detail::close_socket(srv);
  12690. });
  12691. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12692. size_t total_received = 0;
  12693. {
  12694. Client cli("127.0.0.1", PORT + 2);
  12695. cli.set_read_timeout(10, 0);
  12696. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12697. auto res =
  12698. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12699. total_received += data_length;
  12700. return true;
  12701. });
  12702. // Should fail because 200MB exceeds the explicit 150MB limit
  12703. EXPECT_FALSE(res);
  12704. }
  12705. server_thread.join();
  12706. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12707. << "Client with content_receiver should respect the explicit "
  12708. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12709. << total_received << " bytes.";
  12710. }
  12711. // Verify that an explicit set_payload_max_length larger than the response
  12712. // allows the content_receiver to read all data successfully.
  12713. TEST(ClientVulnerabilityTest,
  12714. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12715. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12716. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12717. #ifndef _WIN32
  12718. signal(SIGPIPE, SIG_IGN);
  12719. #endif
  12720. auto server_thread = std::thread([] {
  12721. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12722. default_socket_options(srv);
  12723. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12724. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12725. sockaddr_in addr{};
  12726. addr.sin_family = AF_INET;
  12727. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12728. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12729. int opt = 1;
  12730. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12731. #ifdef _WIN32
  12732. reinterpret_cast<const char *>(&opt),
  12733. #else
  12734. &opt,
  12735. #endif
  12736. sizeof(opt));
  12737. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12738. ::listen(srv, 1);
  12739. sockaddr_in cli_addr{};
  12740. socklen_t cli_len = sizeof(cli_addr);
  12741. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12742. if (cli != INVALID_SOCKET) {
  12743. char buf[4096];
  12744. ::recv(cli, buf, sizeof(buf), 0);
  12745. auto content_length = std::to_string(DATA_SIZE);
  12746. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12747. "Content-Length: " +
  12748. content_length +
  12749. "\r\n"
  12750. "Connection: close\r\n"
  12751. "\r\n";
  12752. ::send(cli,
  12753. #ifdef _WIN32
  12754. static_cast<const char *>(response_header.c_str()),
  12755. static_cast<int>(response_header.size()),
  12756. #else
  12757. response_header.c_str(), response_header.size(),
  12758. #endif
  12759. 0);
  12760. std::string chunk(64 * 1024, 'A');
  12761. size_t total_sent = 0;
  12762. while (total_sent < DATA_SIZE) {
  12763. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12764. auto sent = ::send(cli,
  12765. #ifdef _WIN32
  12766. static_cast<const char *>(chunk.c_str()),
  12767. static_cast<int>(to_send),
  12768. #else
  12769. chunk.c_str(), to_send,
  12770. #endif
  12771. 0);
  12772. if (sent <= 0) break;
  12773. total_sent += static_cast<size_t>(sent);
  12774. }
  12775. #ifdef _WIN32
  12776. ::shutdown(cli, SD_SEND);
  12777. #else
  12778. ::shutdown(cli, SHUT_WR);
  12779. #endif
  12780. char drain[1024];
  12781. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12782. detail::close_socket(cli);
  12783. }
  12784. detail::close_socket(srv);
  12785. });
  12786. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12787. size_t total_received = 0;
  12788. {
  12789. Client cli("127.0.0.1", PORT + 2);
  12790. cli.set_read_timeout(10, 0);
  12791. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12792. auto res =
  12793. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12794. total_received += data_length;
  12795. return true;
  12796. });
  12797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12798. EXPECT_EQ(StatusCode::OK_200, res->status);
  12799. }
  12800. server_thread.join();
  12801. EXPECT_EQ(total_received, DATA_SIZE)
  12802. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12803. << " bytes (larger than " << DATA_SIZE
  12804. << " bytes response), content_receiver should read all data, but only "
  12805. "read "
  12806. << total_received << " bytes.";
  12807. }
  12808. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12809. // Regression test for "zip bomb" attack on the client side: a malicious server
  12810. // sends a small gzip-compressed response that decompresses to a huge payload.
  12811. // The client must enforce payload_max_length on the decompressed size.
  12812. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12813. constexpr size_t DECOMPRESSED_SIZE =
  12814. 10 * 1024 * 1024; // 10MB after decompression
  12815. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12816. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12817. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12818. std::string compressed;
  12819. {
  12820. httplib::detail::gzip_compressor compressor;
  12821. bool ok =
  12822. compressor.compress(uncompressed.data(), uncompressed.size(),
  12823. /*last=*/true, [&](const char *buf, size_t len) {
  12824. compressed.append(buf, len);
  12825. return true;
  12826. });
  12827. ASSERT_TRUE(ok);
  12828. }
  12829. // Sanity: compressed data should be much smaller than the decompressed size
  12830. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12831. #ifndef _WIN32
  12832. signal(SIGPIPE, SIG_IGN);
  12833. #endif
  12834. // Set up the listening socket in the main thread so the server is guaranteed
  12835. // to be ready before the client connects (eliminates race condition).
  12836. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12837. default_socket_options(srv);
  12838. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12840. sockaddr_in addr{};
  12841. addr.sin_family = AF_INET;
  12842. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12843. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12844. int opt = 1;
  12845. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12846. #ifdef _WIN32
  12847. reinterpret_cast<const char *>(&opt),
  12848. #else
  12849. &opt,
  12850. #endif
  12851. sizeof(opt));
  12852. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12853. ASSERT_EQ(0, ::listen(srv, 1));
  12854. auto server_thread = std::thread([&compressed, srv] {
  12855. sockaddr_in cli_addr{};
  12856. socklen_t cli_len = sizeof(cli_addr);
  12857. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12858. if (cli != INVALID_SOCKET) {
  12859. // Read the full HTTP request (until \r\n\r\n)
  12860. char buf[4096];
  12861. size_t total = 0;
  12862. while (total < sizeof(buf)) {
  12863. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12864. if (n <= 0) break;
  12865. total += static_cast<size_t>(n);
  12866. // Check for end of headers
  12867. if (total >= 4) {
  12868. std::string req(buf, total);
  12869. if (req.find("\r\n\r\n") != std::string::npos) break;
  12870. }
  12871. }
  12872. // Malicious response: gzip-compressed body, no Content-Length
  12873. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12874. "Content-Encoding: gzip\r\n"
  12875. "Connection: close\r\n"
  12876. "\r\n";
  12877. ::send(cli,
  12878. #ifdef _WIN32
  12879. static_cast<const char *>(response_header.c_str()),
  12880. static_cast<int>(response_header.size()),
  12881. #else
  12882. response_header.c_str(), response_header.size(),
  12883. #endif
  12884. 0);
  12885. // Send the compressed payload (small on the wire, huge when decompressed)
  12886. size_t total_sent = 0;
  12887. while (total_sent < compressed.size()) {
  12888. auto to_send = std::min(compressed.size() - total_sent,
  12889. static_cast<size_t>(64 * 1024));
  12890. auto sent =
  12891. ::send(cli,
  12892. #ifdef _WIN32
  12893. static_cast<const char *>(compressed.c_str() + total_sent),
  12894. static_cast<int>(to_send),
  12895. #else
  12896. compressed.c_str() + total_sent, to_send,
  12897. #endif
  12898. 0);
  12899. if (sent <= 0) break;
  12900. total_sent += static_cast<size_t>(sent);
  12901. }
  12902. detail::close_socket(cli);
  12903. }
  12904. });
  12905. auto se = detail::scope_exit([&] {
  12906. detail::close_socket(srv);
  12907. server_thread.join();
  12908. });
  12909. size_t total_decompressed = 0;
  12910. {
  12911. Client cli("127.0.0.1", PORT + 3);
  12912. cli.set_read_timeout(5, 0);
  12913. cli.set_decompress(true);
  12914. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12915. auto stream = cli.open_stream("GET", "/zipbomb");
  12916. ASSERT_TRUE(stream.is_valid());
  12917. char buffer[64 * 1024];
  12918. ssize_t n;
  12919. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12920. total_decompressed += static_cast<size_t>(n);
  12921. }
  12922. }
  12923. // The decompressed size must be capped by payload_max_length. Without
  12924. // protection, the client would decompress the full 10MB from a tiny
  12925. // compressed payload, enabling a zip bomb DoS attack.
  12926. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12927. << "Client decompressed " << total_decompressed
  12928. << " bytes from a gzip response. The decompressed size should be "
  12929. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12930. }
  12931. #endif
  12932. TEST(HostAndPortPropertiesTest, NoSSL) {
  12933. httplib::Client cli("www.google.com", 1234);
  12934. ASSERT_EQ("www.google.com", cli.host());
  12935. ASSERT_EQ(1234, cli.port());
  12936. }
  12937. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12938. httplib::Client cli("www.google.com:1234");
  12939. ASSERT_EQ("www.google.com", cli.host());
  12940. ASSERT_EQ(1234, cli.port());
  12941. }
  12942. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12943. // Port number that overflows int — should not crash, client becomes invalid
  12944. httplib::Client cli("http://www.google.com:99999999999999999999");
  12945. ASSERT_FALSE(cli.is_valid());
  12946. }
  12947. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12948. // Port 99999 exceeds valid range (1-65535) — should not crash
  12949. httplib::Client cli("http://www.google.com:99999");
  12950. ASSERT_FALSE(cli.is_valid());
  12951. auto res = cli.Get("/");
  12952. EXPECT_FALSE(res);
  12953. EXPECT_EQ(Error::Connection, res.error());
  12954. }
  12955. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12956. httplib::Client cli("http://user:pass@localhost:1234");
  12957. ASSERT_FALSE(cli.is_valid());
  12958. EXPECT_FALSE(cli.Get("/"));
  12959. }
  12960. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12961. httplib::Client cli("http://www.google.com:80abc");
  12962. ASSERT_FALSE(cli.is_valid());
  12963. }
  12964. #ifdef CPPHTTPLIB_SSL_ENABLED
  12965. TEST(HostAndPortPropertiesTest, SSL) {
  12966. httplib::SSLClient cli("www.google.com");
  12967. ASSERT_EQ("www.google.com", cli.host());
  12968. ASSERT_EQ(443, cli.port());
  12969. }
  12970. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12971. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12972. std::string cert;
  12973. read_file(CA_CERT_FILE, cert);
  12974. httplib::SSLClient httplib_client("www.google.com");
  12975. // Load CA store first time
  12976. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12977. // Load CA store second time (update)
  12978. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12979. // Verify client is still valid and can make connections
  12980. httplib_client.enable_server_certificate_verification(true);
  12981. auto res = httplib_client.Get("/");
  12982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12983. // Google may return 200 or 301 depending on various factors
  12984. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12985. res->status == StatusCode::MovedPermanently_301);
  12986. }
  12987. TEST(SSLClientTest, ServerNameIndication_Online) {
  12988. auto host = "httpbingo.org";
  12989. auto path = std::string{"/get"};
  12990. SSLClient cli(host, 443);
  12991. auto res = cli.Get(path);
  12992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12993. ASSERT_EQ(StatusCode::OK_200, res->status);
  12994. }
  12995. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12996. // Use a site that will cause SSL verification failure due to self-signed cert
  12997. SSLClient cli("self-signed.badssl.com", 443);
  12998. cli.enable_server_certificate_verification(true);
  12999. auto res = cli.Get("/");
  13000. ASSERT_TRUE(!res);
  13001. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13002. // Verify backend error is captured for SSLServerVerification
  13003. // This occurs when certificate verification fails
  13004. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13005. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13006. EXPECT_NE(0UL, res.ssl_backend_error());
  13007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13008. // For OpenSSL, ssl_error is 0 for verification errors
  13009. EXPECT_EQ(0, res.ssl_error());
  13010. #if !defined(_WIN32) || \
  13011. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13012. // On non-Windows or when Windows Schannel is disabled, the error comes
  13013. // from OpenSSL's verification
  13014. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13015. res.ssl_backend_error());
  13016. #endif
  13017. #endif
  13018. }
  13019. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13020. // Use a site where hostname doesn't match the certificate
  13021. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13022. SSLClient cli("wrong.host.badssl.com", 443);
  13023. cli.enable_server_certificate_verification(true);
  13024. cli.enable_server_hostname_verification(true);
  13025. auto res = cli.Get("/");
  13026. ASSERT_TRUE(!res);
  13027. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13028. // Verify backend error is captured for hostname verification failure
  13029. EXPECT_NE(0UL, res.ssl_backend_error());
  13030. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13031. // For OpenSSL, ssl_error is 0 for verification errors
  13032. EXPECT_EQ(0, res.ssl_error());
  13033. #if !defined(_WIN32) || \
  13034. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13035. // On non-Windows or when Windows Schannel is disabled, the error comes
  13036. // from OpenSSL's hostname verification
  13037. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13038. res.ssl_backend_error());
  13039. #endif
  13040. #endif
  13041. }
  13042. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13043. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13044. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13045. SSLClient cli("www.google.com", 443);
  13046. cli.enable_server_certificate_verification(true);
  13047. auto res = cli.Get("/");
  13048. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13049. }
  13050. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13051. SSLClient cli("www.google.com", 443);
  13052. cli.enable_server_certificate_verification(true);
  13053. cli.enable_windows_certificate_verification(false);
  13054. auto res = cli.Get("/");
  13055. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13056. }
  13057. // The server sends an intermediate cross-signed by a root Windows trusts,
  13058. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13059. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13060. SSLClient cli("accounts.spotify.com", 443);
  13061. auto res = cli.Get("/");
  13062. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13063. << " ssl_backend_error=" << res.ssl_backend_error();
  13064. }
  13065. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13066. // policy status, which no backend reports for a self-signed certificate.
  13067. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13068. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13069. ASSERT_TRUE(svr.is_valid());
  13070. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13071. auto se = detail::scope_exit([&] {
  13072. svr.stop();
  13073. t.join();
  13074. ASSERT_FALSE(svr.is_running());
  13075. });
  13076. svr.wait_until_ready();
  13077. SSLClient cli("127.0.0.1", PORT);
  13078. cli.set_connection_timeout(30);
  13079. auto res = cli.Get("/");
  13080. ASSERT_FALSE(res);
  13081. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13082. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13083. }
  13084. #endif
  13085. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13086. Client cli("https://google.com");
  13087. auto res = cli.Get("/");
  13088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13089. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13090. }
  13091. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13092. SSLClient cli("google.com");
  13093. cli.set_ca_cert_path(CA_CERT_FILE);
  13094. auto res = cli.Get("/");
  13095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13096. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13097. }
  13098. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13099. SSLClient cli("google.com");
  13100. cli.enable_server_certificate_verification(true);
  13101. cli.set_ca_cert_path("hello");
  13102. auto res = cli.Get("/");
  13103. ASSERT_TRUE(!res);
  13104. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13105. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13106. // should be set
  13107. EXPECT_EQ(0, res.ssl_error());
  13108. // Verify backend error is captured for SSLLoadingCerts
  13109. // This error occurs when loading CA certificates fails
  13110. EXPECT_NE(0UL, res.ssl_backend_error());
  13111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13112. // OpenSSL specific error codes:
  13113. // > openssl errstr 0x80000002
  13114. // error:80000002:system library::No such file or directory
  13115. // > openssl errstr 0xA000126
  13116. // error:0A000126:SSL routines::unexpected eof while reading
  13117. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13118. res.ssl_backend_error() == 0xA000126);
  13119. #endif
  13120. }
  13121. TEST(SSLClientTest, ServerCertificateVerification4) {
  13122. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13123. ASSERT_TRUE(svr.is_valid());
  13124. svr.Get("/test", [&](const Request &, Response &res) {
  13125. res.set_content("test", "text/plain");
  13126. svr.stop();
  13127. ASSERT_TRUE(true);
  13128. });
  13129. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13130. auto se = detail::scope_exit([&] {
  13131. t.join();
  13132. ASSERT_FALSE(svr.is_running());
  13133. });
  13134. svr.wait_until_ready();
  13135. SSLClient cli("127.0.0.1", PORT);
  13136. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13137. cli.enable_server_certificate_verification(true);
  13138. cli.set_connection_timeout(30);
  13139. auto res = cli.Get("/test");
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. ASSERT_EQ(StatusCode::OK_200, res->status);
  13142. }
  13143. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13144. std::string cert;
  13145. read_file(CA_CERT_FILE, cert);
  13146. SSLClient cli("google.com");
  13147. cli.load_ca_cert_store(cert.data(), cert.size());
  13148. const auto res = cli.Get("/");
  13149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13150. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13151. }
  13152. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13153. // clang-format off
  13154. static constexpr char cert[] =
  13155. "GlobalSign Root CA\n"
  13156. "==================\n"
  13157. "-----BEGIN CERTIFICATE-----\n"
  13158. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13159. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13160. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13161. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13162. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13163. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13164. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13165. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13166. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13167. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13168. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13169. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13170. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13171. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13172. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13173. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13174. "-----END CERTIFICATE-----\n";
  13175. // clang-format on
  13176. SSLClient cli("google.com");
  13177. cli.load_ca_cert_store(cert, sizeof(cert));
  13178. const auto res = cli.Get("/");
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13181. }
  13182. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13183. SSLClient cli("www.youtube.com");
  13184. cli.set_ca_cert_path(CA_CERT_FILE);
  13185. cli.enable_server_certificate_verification(true);
  13186. cli.set_follow_location(true);
  13187. auto res = cli.Get("/");
  13188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13189. ASSERT_EQ(StatusCode::OK_200, res->status);
  13190. }
  13191. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13192. SSLClient cli("wWw.YouTube.Com");
  13193. cli.set_ca_cert_path(CA_CERT_FILE);
  13194. cli.enable_server_certificate_verification(true);
  13195. cli.enable_server_hostname_verification(true);
  13196. cli.set_follow_location(true);
  13197. auto res = cli.Get("/");
  13198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13199. ASSERT_EQ(StatusCode::OK_200, res->status);
  13200. }
  13201. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13202. SSLClient cli("gOoGlE.COm");
  13203. cli.enable_server_certificate_verification(true);
  13204. cli.enable_server_hostname_verification(true);
  13205. cli.set_follow_location(true);
  13206. auto res = cli.Get("/");
  13207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13208. ASSERT_EQ(StatusCode::OK_200, res->status);
  13209. }
  13210. TEST(SSLClientTest, Issue2004_Online) {
  13211. Client client("https://google.com");
  13212. client.set_follow_location(true);
  13213. auto res = client.Get("/");
  13214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13215. ASSERT_EQ(StatusCode::OK_200, res->status);
  13216. auto body = res->body;
  13217. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13218. }
  13219. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13220. // Create SSLClient with invalid cert/key to make is_valid() return false
  13221. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13222. "nonexistent_key.pem");
  13223. // is_valid() should be false due to cert loading failure
  13224. ASSERT_FALSE(cli.is_valid());
  13225. auto res = cli.Get("/");
  13226. ASSERT_FALSE(res);
  13227. EXPECT_EQ(Error::SSLConnection, res.error());
  13228. }
  13229. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13230. // Test for Issue #2251: SSL error not properly reported when client cert
  13231. // and key paths are swapped or mismatched
  13232. // This simulates the scenario where user accidentally swaps the cert and key
  13233. // files
  13234. // Using client cert file as private key and vice versa (completely wrong)
  13235. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13236. // Should fail validation due to cert/key mismatch
  13237. ASSERT_FALSE(cli.is_valid());
  13238. // Attempt to make a request should fail with proper error
  13239. auto res = cli.Get("/");
  13240. ASSERT_FALSE(res);
  13241. EXPECT_EQ(Error::SSLConnection, res.error());
  13242. // SSL error should be recorded in the Result object (this is the key fix for
  13243. // Issue #2251)
  13244. auto backend_error = res.ssl_backend_error();
  13245. EXPECT_NE(0u, backend_error);
  13246. }
  13247. // Tests cert/key mismatch detection at the TLS context level
  13248. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13249. // Test that using mismatched cert/key causes connection failure.
  13250. // We verify this at the SSLClient level rather than through internal
  13251. // TLS API functions.
  13252. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13253. cli.enable_server_certificate_verification(false);
  13254. cli.set_connection_timeout(2);
  13255. // The mismatch should cause a connection or handshake error
  13256. auto res = cli.Get("/test");
  13257. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13258. // Either way, the request should fail
  13259. EXPECT_FALSE(res);
  13260. }
  13261. #endif
  13262. #if 0
  13263. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13264. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13265. ASSERT_TRUE(cli != nullptr);
  13266. cli->set_address_family(AF_INET6);
  13267. cli->set_interface("en0");
  13268. auto res = cli->Get("/get");
  13269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13270. ASSERT_EQ(StatusCode::OK_200, res->status);
  13271. }
  13272. #endif
  13273. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13274. #ifdef CPPHTTPLIB_SSL_ENABLED
  13275. void ClientCertPresent(
  13276. const std::string &client_cert_file,
  13277. const std::string &client_private_key_file,
  13278. const std::string &client_encrypted_private_key_pass = std::string()) {
  13279. using namespace httplib::tls;
  13280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13281. CLIENT_CA_CERT_DIR);
  13282. ASSERT_TRUE(svr.is_valid());
  13283. svr.Get("/test", [&](const Request &req, Response &res) {
  13284. res.set_content("test", "text/plain");
  13285. auto cert = req.peer_cert();
  13286. ASSERT_TRUE(static_cast<bool>(cert));
  13287. std::string common_name = cert.subject_cn();
  13288. EXPECT_EQ("Common Name", common_name);
  13289. });
  13290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13291. auto se = detail::scope_exit([&] {
  13292. svr.stop();
  13293. t.join();
  13294. ASSERT_FALSE(svr.is_running());
  13295. });
  13296. svr.wait_until_ready();
  13297. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13298. client_encrypted_private_key_pass);
  13299. cli.enable_server_certificate_verification(false);
  13300. cli.set_connection_timeout(30);
  13301. auto res = cli.Get("/test");
  13302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13303. ASSERT_EQ(StatusCode::OK_200, res->status);
  13304. }
  13305. TEST(SSLClientServerTest, ClientCertPresent) {
  13306. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13307. }
  13308. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13309. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13310. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13311. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13312. }
  13313. // PEM memory-based constructor tests (works with all TLS backends)
  13314. void PemMemoryClientCertPresent(
  13315. const std::string &client_cert_file,
  13316. const std::string &client_private_key_file,
  13317. const std::string &client_encrypted_private_key_pass = std::string()) {
  13318. // Read PEM files into memory
  13319. std::string server_cert_pem, server_key_pem;
  13320. std::string client_ca_pem;
  13321. std::string client_cert_pem, client_key_pem;
  13322. read_file(SERVER_CERT_FILE, server_cert_pem);
  13323. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13324. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13325. read_file(client_cert_file, client_cert_pem);
  13326. read_file(client_private_key_file, client_key_pem);
  13327. // Create server with PEM memory
  13328. SSLServer::PemMemory server_pem = {
  13329. server_cert_pem.c_str(),
  13330. server_cert_pem.size(),
  13331. server_key_pem.c_str(),
  13332. server_key_pem.size(),
  13333. client_ca_pem.c_str(),
  13334. client_ca_pem.size(),
  13335. nullptr // no password for server key
  13336. };
  13337. SSLServer svr(server_pem);
  13338. ASSERT_TRUE(svr.is_valid());
  13339. svr.Get("/test", [&](const Request &, Response &res) {
  13340. res.set_content("test", "text/plain");
  13341. });
  13342. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. // Create client with PEM memory
  13350. const char *password = client_encrypted_private_key_pass.empty()
  13351. ? nullptr
  13352. : client_encrypted_private_key_pass.c_str();
  13353. SSLClient::PemMemory client_pem = {
  13354. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13355. client_key_pem.size(), password};
  13356. SSLClient cli(HOST, PORT, client_pem);
  13357. cli.enable_server_certificate_verification(false);
  13358. cli.set_connection_timeout(30);
  13359. auto res = cli.Get("/test");
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. ASSERT_EQ(StatusCode::OK_200, res->status);
  13362. }
  13363. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13364. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13365. }
  13366. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13367. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13368. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13369. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13370. }
  13371. TEST(SSLClientServerTest, ClientCertMissing) {
  13372. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13373. CLIENT_CA_CERT_DIR);
  13374. ASSERT_TRUE(svr.is_valid());
  13375. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13376. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13377. auto se = detail::scope_exit([&] {
  13378. svr.stop();
  13379. t.join();
  13380. ASSERT_FALSE(svr.is_running());
  13381. });
  13382. svr.wait_until_ready();
  13383. SSLClient cli(HOST, PORT);
  13384. cli.set_connection_timeout(30);
  13385. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13386. // the chain check on Windows, so the result does not depend on the order.
  13387. cli.enable_server_hostname_verification(false);
  13388. auto res = cli.Get("/test");
  13389. ASSERT_TRUE(!res);
  13390. // When client cert is missing and server requires it, connection fails
  13391. // Error type depends on backend implementation
  13392. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13393. res.error() == Error::SSLConnection);
  13394. // Verify backend error is captured
  13395. // Note: This test may have different error codes depending on the exact
  13396. // verification failure
  13397. EXPECT_NE(0UL, res.ssl_backend_error());
  13398. }
  13399. TEST(SSLClientServerTest, TrustDirOptional) {
  13400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13401. ASSERT_TRUE(svr.is_valid());
  13402. svr.Get("/test", [&](const Request &, Response &res) {
  13403. res.set_content("test", "text/plain");
  13404. });
  13405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13413. cli.enable_server_certificate_verification(false);
  13414. cli.set_connection_timeout(30);
  13415. auto res = cli.Get("/test");
  13416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13417. ASSERT_EQ(StatusCode::OK_200, res->status);
  13418. }
  13419. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13420. class NoListenSSLServer : public SSLServer {
  13421. public:
  13422. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13423. const char *client_ca_cert_file_path,
  13424. const char *client_ca_cert_dir_path = nullptr)
  13425. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13426. client_ca_cert_dir_path),
  13427. stop_(false) {}
  13428. std::atomic_bool stop_;
  13429. private:
  13430. bool process_and_close_socket(socket_t /*sock*/) override {
  13431. // Don't create SSL context
  13432. while (!stop_.load()) {
  13433. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13434. }
  13435. return true;
  13436. }
  13437. };
  13438. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13439. CLIENT_CA_CERT_FILE);
  13440. ASSERT_TRUE(svr.is_valid());
  13441. svr.Get("/test", [&](const Request &, Response &res) {
  13442. res.set_content("test", "text/plain");
  13443. });
  13444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13445. auto se = detail::scope_exit([&] {
  13446. svr.stop_ = true;
  13447. svr.stop();
  13448. t.join();
  13449. ASSERT_FALSE(svr.is_running());
  13450. });
  13451. svr.wait_until_ready();
  13452. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13453. cli.enable_server_certificate_verification(false);
  13454. cli.set_connection_timeout(1);
  13455. auto res = cli.Get("/test");
  13456. ASSERT_TRUE(!res);
  13457. EXPECT_EQ(Error::SSLConnection, res.error());
  13458. // Timeout results in WantRead error code (maps to backend-specific value)
  13459. EXPECT_NE(0, res.ssl_error());
  13460. }
  13461. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13462. // Test SSLServer with client certificate verification using the standard
  13463. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13465. CLIENT_CA_CERT_DIR);
  13466. ASSERT_TRUE(svr.is_valid());
  13467. svr.Get("/test", [&](const Request &req, Response &res) {
  13468. res.set_content("test", "text/plain");
  13469. auto cert = req.peer_cert();
  13470. ASSERT_TRUE(static_cast<bool>(cert));
  13471. auto common_name = cert.subject_cn();
  13472. EXPECT_EQ("Common Name", common_name);
  13473. });
  13474. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13475. auto se = detail::scope_exit([&] {
  13476. svr.stop();
  13477. t.join();
  13478. ASSERT_FALSE(svr.is_running());
  13479. });
  13480. svr.wait_until_ready();
  13481. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13482. cli.enable_server_certificate_verification(false);
  13483. cli.set_connection_timeout(30);
  13484. auto res = cli.Get("/test");
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. ASSERT_EQ(StatusCode::OK_200, res->status);
  13487. }
  13488. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13489. // Verifies that wildcard matching and exact matching work consistently
  13490. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13491. using namespace httplib::tls;
  13492. // We need a running server to test against
  13493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13494. ASSERT_TRUE(svr.is_valid());
  13495. svr.Get("/test", [](const Request &, Response &res) {
  13496. res.set_content("ok", "text/plain");
  13497. });
  13498. thread t([&]() { svr.listen(HOST, PORT); });
  13499. auto se = detail::scope_exit([&] {
  13500. svr.stop();
  13501. t.join();
  13502. });
  13503. svr.wait_until_ready();
  13504. bool verify_callback_called = false;
  13505. bool verify_result_wrong = false;
  13506. SSLClient cli(HOST, PORT);
  13507. cli.enable_server_certificate_verification(true);
  13508. cli.set_ca_cert_path(CA_CERT_FILE);
  13509. cli.set_connection_timeout(5);
  13510. // Note: Test certificate has CN="Common Name", not "localhost"
  13511. bool verify_result_cn = false;
  13512. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13513. verify_callback_called = true;
  13514. if (!ctx.cert) return false;
  13515. // Test 1: "Common Name" should match (our test server cert CN)
  13516. verify_result_cn = ctx.check_hostname("Common Name");
  13517. // Test 2: wrong hostname should not match
  13518. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13519. return true; // Accept for the purpose of this test
  13520. });
  13521. auto res = cli.Get("/test");
  13522. // The request may succeed or fail depending on cert configuration
  13523. // but the callback should have been called
  13524. ASSERT_TRUE(verify_callback_called)
  13525. << "Verify callback should have been called";
  13526. // CN="Common Name" should match our test certificate
  13527. //
  13528. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13529. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13530. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13531. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13532. // <openssl/base.h>, which is included transitively when
  13533. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13534. #if defined(OPENSSL_IS_BORINGSSL)
  13535. EXPECT_FALSE(verify_result_cn)
  13536. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13537. #else
  13538. EXPECT_TRUE(verify_result_cn)
  13539. << "verify_hostname should match 'Common Name' (certificate CN)";
  13540. #endif
  13541. // Wrong hostname should not match
  13542. EXPECT_FALSE(verify_result_wrong)
  13543. << "verify_hostname should not match 'wronghost.example.com'";
  13544. }
  13545. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13546. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13547. // X509_check_ip behavior and must hold for every backend.
  13548. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13549. using namespace httplib::tls;
  13550. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13551. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13552. ASSERT_TRUE(svr.is_valid());
  13553. svr.Get("/test", [](const Request &, Response &res) {
  13554. res.set_content("ok", "text/plain");
  13555. });
  13556. thread t([&]() { svr.listen(HOST, PORT); });
  13557. auto se = detail::scope_exit([&] {
  13558. svr.stop();
  13559. t.join();
  13560. });
  13561. svr.wait_until_ready();
  13562. bool verify_callback_called = false;
  13563. bool ip_matched_via_cn = true;
  13564. SSLClient cli(HOST, PORT);
  13565. cli.enable_server_certificate_verification(true);
  13566. cli.set_ca_cert_path(CA_CERT_FILE);
  13567. cli.set_connection_timeout(5);
  13568. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13569. verify_callback_called = true;
  13570. if (!ctx.cert) return false;
  13571. // The IP appears only in the CN, so it must NOT be accepted.
  13572. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13573. return true; // Accept for the purpose of this test
  13574. });
  13575. cli.Get("/test");
  13576. ASSERT_TRUE(verify_callback_called)
  13577. << "Verify callback should have been called";
  13578. EXPECT_FALSE(ip_matched_via_cn)
  13579. << "An IP host must not be authenticated via the certificate CN";
  13580. }
  13581. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13582. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13583. using namespace httplib::tls;
  13584. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13585. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13586. ASSERT_TRUE(svr.is_valid());
  13587. svr.Get("/test", [](const Request &, Response &res) {
  13588. res.set_content("ok", "text/plain");
  13589. });
  13590. thread t([&]() { svr.listen(HOST, PORT); });
  13591. auto se = detail::scope_exit([&] {
  13592. svr.stop();
  13593. t.join();
  13594. });
  13595. svr.wait_until_ready();
  13596. bool verify_callback_called = false;
  13597. bool san_matched = false;
  13598. bool wrong_ipv6_matched = true;
  13599. bool cn_ipv6_matched = true;
  13600. SSLClient cli(HOST, PORT);
  13601. cli.enable_server_certificate_verification(true);
  13602. cli.set_ca_cert_path(CA_CERT_FILE);
  13603. cli.set_connection_timeout(5);
  13604. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13605. verify_callback_called = true;
  13606. if (!ctx.cert) return false;
  13607. // Matches the IPv6 iPAddress SAN.
  13608. san_matched = ctx.check_hostname("2001:db8::1");
  13609. // A different IPv6 address must not match.
  13610. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13611. // "::1" lives only in the CN, so it must not be accepted.
  13612. cn_ipv6_matched = ctx.check_hostname("::1");
  13613. return true; // Accept for the purpose of this test
  13614. });
  13615. cli.Get("/test");
  13616. ASSERT_TRUE(verify_callback_called)
  13617. << "Verify callback should have been called";
  13618. EXPECT_TRUE(san_matched)
  13619. << "verify_hostname should match an IPv6 iPAddress SAN";
  13620. EXPECT_FALSE(wrong_ipv6_matched)
  13621. << "verify_hostname should not match a non-matching IPv6 address";
  13622. EXPECT_FALSE(cn_ipv6_matched)
  13623. << "An IPv6 host must not be authenticated via the certificate CN";
  13624. }
  13625. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13626. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13627. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13628. using namespace httplib::tls;
  13629. // SANs: DNS:a.zz, IP:42.46.122.122
  13630. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13631. ASSERT_TRUE(svr.is_valid());
  13632. svr.Get("/test", [](const Request &, Response &res) {
  13633. res.set_content("ok", "text/plain");
  13634. });
  13635. auto port = svr.bind_to_any_port(HOST);
  13636. thread t([&]() { svr.listen_after_bind(); });
  13637. auto se = detail::scope_exit([&] {
  13638. svr.stop();
  13639. t.join();
  13640. });
  13641. svr.wait_until_ready();
  13642. bool verify_callback_called = false;
  13643. bool dns_san_matched = false;
  13644. bool ip_san_matched = false;
  13645. bool ip_matched_via_dns_san = true;
  13646. bool dns_matched_via_ip_san = true;
  13647. SSLClient cli(HOST, port);
  13648. cli.enable_server_certificate_verification(true);
  13649. cli.set_ca_cert_path(CA_CERT_FILE);
  13650. cli.set_connection_timeout(5);
  13651. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13652. verify_callback_called = true;
  13653. if (!ctx.cert) return false;
  13654. dns_san_matched = ctx.check_hostname("a.zz");
  13655. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13656. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13657. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13658. return true; // Accept for the purpose of this test
  13659. });
  13660. cli.Get("/test");
  13661. ASSERT_TRUE(verify_callback_called)
  13662. << "Verify callback should have been called";
  13663. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13664. EXPECT_TRUE(ip_san_matched)
  13665. << "verify_hostname should match an iPAddress SAN";
  13666. EXPECT_FALSE(ip_matched_via_dns_san)
  13667. << "An IP host must not be authenticated via a dNSName SAN";
  13668. EXPECT_FALSE(dns_matched_via_ip_san)
  13669. << "A DNS host must not be authenticated via an iPAddress SAN";
  13670. }
  13671. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13672. // "www.*.example.test" names one host and not every host under example.test.
  13673. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13674. using namespace httplib::tls;
  13675. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13676. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13677. ASSERT_TRUE(svr.is_valid());
  13678. svr.Get("/test", [](const Request &, Response &res) {
  13679. res.set_content("ok", "text/plain");
  13680. });
  13681. auto port = svr.bind_to_any_port(HOST);
  13682. thread t([&]() { svr.listen_after_bind(); });
  13683. auto se = detail::scope_exit([&] {
  13684. svr.stop();
  13685. t.join();
  13686. });
  13687. svr.wait_until_ready();
  13688. bool verify_callback_called = false;
  13689. bool leftmost_wildcard_matched = false;
  13690. bool wildcard_spanned_labels = true;
  13691. bool inner_wildcard_matched = true;
  13692. SSLClient cli(HOST, port);
  13693. cli.enable_server_certificate_verification(true);
  13694. cli.set_ca_cert_path(CA_CERT_FILE);
  13695. cli.set_connection_timeout(5);
  13696. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13697. verify_callback_called = true;
  13698. if (!ctx.cert) return false;
  13699. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13700. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13701. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13702. return true; // Accept for the purpose of this test
  13703. });
  13704. cli.Get("/test");
  13705. ASSERT_TRUE(verify_callback_called)
  13706. << "Verify callback should have been called";
  13707. EXPECT_TRUE(leftmost_wildcard_matched)
  13708. << "A leftmost wildcard should match a single label";
  13709. EXPECT_FALSE(wildcard_spanned_labels)
  13710. << "A wildcard label must not match more than one label";
  13711. EXPECT_FALSE(inner_wildcard_matched)
  13712. << "A wildcard outside the leftmost label must not be honoured";
  13713. }
  13714. // sans() must report each SAN entry under its own type.
  13715. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13716. using namespace httplib::tls;
  13717. // SANs: DNS:a.zz, IP:42.46.122.122
  13718. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13719. ASSERT_TRUE(svr.is_valid());
  13720. svr.Get("/test", [](const Request &, Response &res) {
  13721. res.set_content("ok", "text/plain");
  13722. });
  13723. auto port = svr.bind_to_any_port(HOST);
  13724. thread t([&]() { svr.listen_after_bind(); });
  13725. auto se = detail::scope_exit([&] {
  13726. svr.stop();
  13727. t.join();
  13728. });
  13729. svr.wait_until_ready();
  13730. bool verify_callback_called = false;
  13731. std::vector<SanEntry> sans;
  13732. SSLClient cli(HOST, port);
  13733. cli.enable_server_certificate_verification(true);
  13734. cli.set_ca_cert_path(CA_CERT_FILE);
  13735. cli.set_connection_timeout(5);
  13736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13737. verify_callback_called = true;
  13738. if (!ctx.cert) return false;
  13739. sans = ctx.sans();
  13740. return true; // Accept for the purpose of this test
  13741. });
  13742. cli.Get("/test");
  13743. ASSERT_TRUE(verify_callback_called)
  13744. << "Verify callback should have been called";
  13745. auto has_san = [&](SanType type, const std::string &value) {
  13746. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13747. return san.type == type && san.value == value;
  13748. });
  13749. };
  13750. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13751. << "sans() should report the dNSName SAN";
  13752. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13753. << "sans() should report the iPAddress SAN";
  13754. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13755. << "sans() must not report the dNSName SAN as an address";
  13756. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13757. << "sans() must not report the iPAddress SAN as a DNS name";
  13758. }
  13759. #endif
  13760. // mbedTLS-specific callback constructor test
  13761. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13762. #ifdef CPPHTTPLIB_SSL_ENABLED
  13763. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13765. ASSERT_TRUE(svr.is_valid());
  13766. // Set up a handler to verify client certificate is present
  13767. bool client_cert_verified = false;
  13768. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13769. // Verify that client certificate was provided
  13770. client_cert_verified = true;
  13771. res.set_content("success", "text/plain");
  13772. });
  13773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13774. auto se = detail::scope_exit([&] {
  13775. svr.stop();
  13776. t.join();
  13777. ASSERT_FALSE(svr.is_running());
  13778. });
  13779. svr.wait_until_ready();
  13780. // Client with certificate
  13781. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13782. cli.enable_server_certificate_verification(false);
  13783. cli.set_connection_timeout(30);
  13784. auto res = cli.Get("/test");
  13785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13786. ASSERT_EQ(StatusCode::OK_200, res->status);
  13787. ASSERT_TRUE(client_cert_verified);
  13788. EXPECT_EQ("success", res->body);
  13789. }
  13790. #endif
  13791. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13792. // backends
  13793. #ifdef CPPHTTPLIB_SSL_ENABLED
  13794. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13795. using namespace httplib::tls;
  13796. // Test that when client CA cert file is provided,
  13797. // the server properly requests and validates client certificates
  13798. // Create a server with client authentication
  13799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13800. ASSERT_TRUE(svr.is_valid());
  13801. bool handler_called = false;
  13802. svr.Get("/test", [&](const Request &req, Response &res) {
  13803. handler_called = true;
  13804. // Verify that a client certificate was provided
  13805. auto cert = req.peer_cert();
  13806. ASSERT_TRUE(static_cast<bool>(cert));
  13807. // Get the issuer name
  13808. std::string issuer_str = cert.issuer_name();
  13809. ASSERT_FALSE(issuer_str.empty());
  13810. // The client certificate should be issued by our test CA
  13811. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13812. res.set_content("authenticated", "text/plain");
  13813. });
  13814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13815. auto se = detail::scope_exit([&] {
  13816. svr.stop();
  13817. t.join();
  13818. ASSERT_FALSE(svr.is_running());
  13819. });
  13820. svr.wait_until_ready();
  13821. // Connect with a client certificate issued by the CA
  13822. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13823. cli.enable_server_certificate_verification(false);
  13824. cli.set_connection_timeout(30);
  13825. auto res = cli.Get("/test");
  13826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13827. ASSERT_EQ(StatusCode::OK_200, res->status);
  13828. ASSERT_TRUE(handler_called);
  13829. EXPECT_EQ("authenticated", res->body);
  13830. }
  13831. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13832. using namespace httplib::tls;
  13833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13834. ASSERT_TRUE(svr.is_valid());
  13835. svr.Get("/test", [](const Request &, Response &res) {
  13836. res.set_content("ok", "text/plain");
  13837. });
  13838. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13839. auto se = detail::scope_exit([&] {
  13840. svr.stop();
  13841. t.join();
  13842. });
  13843. svr.wait_until_ready();
  13844. SSLClient cli(HOST, PORT);
  13845. cli.enable_server_certificate_verification(false);
  13846. cli.set_connection_timeout(30);
  13847. bool cert_checked = false;
  13848. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13849. if (ctx.cert) {
  13850. auto sans = ctx.sans();
  13851. // Test certificate may or may not have SANs - just verify the API
  13852. // works If SANs exist, verify the types are valid
  13853. for (const auto &san : sans) {
  13854. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13855. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13856. san.type == SanType::OTHER);
  13857. EXPECT_FALSE(san.value.empty());
  13858. }
  13859. cert_checked = true;
  13860. }
  13861. return true;
  13862. });
  13863. auto res = cli.Get("/test");
  13864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13865. EXPECT_TRUE(cert_checked);
  13866. }
  13867. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13868. using namespace httplib::tls;
  13869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13870. ASSERT_TRUE(svr.is_valid());
  13871. svr.Get("/test", [](const Request &, Response &res) {
  13872. res.set_content("ok", "text/plain");
  13873. });
  13874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13875. auto se = detail::scope_exit([&] {
  13876. svr.stop();
  13877. t.join();
  13878. });
  13879. svr.wait_until_ready();
  13880. SSLClient cli(HOST, PORT);
  13881. cli.enable_server_certificate_verification(false);
  13882. cli.set_connection_timeout(30);
  13883. bool validity_checked = false;
  13884. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13885. if (ctx.cert) {
  13886. time_t not_before = 0, not_after = 0;
  13887. bool result = ctx.validity(not_before, not_after);
  13888. EXPECT_TRUE(result);
  13889. // Verify that not_before < now < not_after for a valid cert
  13890. time_t now = time(nullptr);
  13891. EXPECT_LT(not_before, now);
  13892. EXPECT_GT(not_after, now);
  13893. validity_checked = true;
  13894. }
  13895. return true;
  13896. });
  13897. auto res = cli.Get("/test");
  13898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13899. EXPECT_TRUE(validity_checked);
  13900. }
  13901. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13902. using namespace httplib::tls;
  13903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13904. ASSERT_TRUE(svr.is_valid());
  13905. svr.Get("/test", [](const Request &, Response &res) {
  13906. res.set_content("ok", "text/plain");
  13907. });
  13908. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13909. auto se = detail::scope_exit([&] {
  13910. svr.stop();
  13911. t.join();
  13912. });
  13913. svr.wait_until_ready();
  13914. SSLClient cli(HOST, PORT);
  13915. cli.enable_server_certificate_verification(false);
  13916. cli.set_connection_timeout(30);
  13917. bool serial_checked = false;
  13918. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13919. if (ctx.cert) {
  13920. std::string serial = ctx.serial();
  13921. EXPECT_FALSE(serial.empty());
  13922. // Serial should be a hex string
  13923. for (char c : serial) {
  13924. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13925. (c >= 'a' && c <= 'f'));
  13926. }
  13927. serial_checked = true;
  13928. }
  13929. return true;
  13930. });
  13931. auto res = cli.Get("/test");
  13932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13933. EXPECT_TRUE(serial_checked);
  13934. }
  13935. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13936. // Test 1: Valid CA file - no error should be recorded
  13937. {
  13938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13939. CLIENT_CA_CERT_FILE);
  13940. ASSERT_TRUE(svr.is_valid());
  13941. // With valid setup, last_ssl_error should be 0
  13942. EXPECT_EQ(0, svr.ssl_last_error());
  13943. }
  13944. // Test 2: Invalid CA file content
  13945. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13946. {
  13947. // Create a temporary file with completely invalid content
  13948. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13949. {
  13950. std::ofstream ofs(temp_invalid_ca);
  13951. ofs << "This is not a certificate file at all\n";
  13952. ofs << "Just plain text content\n";
  13953. }
  13954. // Create server with invalid CA file
  13955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13956. // Clean up temporary file
  13957. std::remove(temp_invalid_ca);
  13958. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13959. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13960. // Note: SSL_CTX_load_verify_locations typically fails first,
  13961. // but our error handling code path is still exercised
  13962. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13963. }
  13964. }
  13965. TEST(VerifyCallbackTest, VerifyContextFields) {
  13966. using namespace httplib::tls;
  13967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13968. ASSERT_TRUE(svr.is_valid());
  13969. svr.Get("/test", [](const Request &, Response &res) {
  13970. res.set_content("ok", "text/plain");
  13971. });
  13972. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13973. auto se = detail::scope_exit([&] {
  13974. svr.stop();
  13975. t.join();
  13976. });
  13977. svr.wait_until_ready();
  13978. SSLClient cli(HOST, PORT);
  13979. cli.enable_server_certificate_verification(false);
  13980. cli.set_connection_timeout(30);
  13981. int callback_count = 0;
  13982. bool saw_leaf_cert = false;
  13983. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13984. if (ctx.cert) {
  13985. callback_count++;
  13986. // We should see at least one certificate (the leaf)
  13987. std::string cn = ctx.subject_cn();
  13988. if (!cn.empty()) { saw_leaf_cert = true; }
  13989. // Verify context fields are populated
  13990. EXPECT_NE(ctx.session, nullptr);
  13991. EXPECT_GE(ctx.depth, 0);
  13992. }
  13993. return true;
  13994. });
  13995. auto res = cli.Get("/test");
  13996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13997. EXPECT_GT(callback_count, 0);
  13998. EXPECT_TRUE(saw_leaf_cert);
  13999. }
  14000. // A verifier belongs to the client that set it, not to the thread that set it.
  14001. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14002. using namespace httplib::tls;
  14003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14004. ASSERT_TRUE(svr.is_valid());
  14005. svr.Get("/test", [](const Request &, Response &res) {
  14006. res.set_content("ok", "text/plain");
  14007. });
  14008. auto port = svr.bind_to_any_port(HOST);
  14009. thread t([&]() { svr.listen_after_bind(); });
  14010. auto se = detail::scope_exit([&] {
  14011. svr.stop();
  14012. t.join();
  14013. });
  14014. svr.wait_until_ready();
  14015. auto rejecting_calls = 0;
  14016. SSLClient rejecting(HOST, port);
  14017. rejecting.enable_server_certificate_verification(false);
  14018. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14019. rejecting_calls++;
  14020. return false;
  14021. });
  14022. auto accepting_calls = 0;
  14023. SSLClient accepting(HOST, port);
  14024. accepting.enable_server_certificate_verification(false);
  14025. // Set on another thread than the requests below.
  14026. thread([&]() {
  14027. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14028. accepting_calls++;
  14029. return true;
  14030. });
  14031. }).join();
  14032. // Requested on another thread than the verifier was set on.
  14033. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14034. EXPECT_GT(rejecting_calls, 0);
  14035. auto res = accepting.Get("/test");
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. EXPECT_GT(accepting_calls, 0);
  14038. }
  14039. // VerifyContext::session is the same handle the other tls:: functions take.
  14040. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14041. using namespace httplib::tls;
  14042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14043. ASSERT_TRUE(svr.is_valid());
  14044. svr.Get("/test", [](const Request &, Response &res) {
  14045. res.set_content("ok", "text/plain");
  14046. });
  14047. auto port = svr.bind_to_any_port(HOST);
  14048. thread t([&]() { svr.listen_after_bind(); });
  14049. auto se = detail::scope_exit([&] {
  14050. svr.stop();
  14051. t.join();
  14052. });
  14053. svr.wait_until_ready();
  14054. SSLClient cli(HOST, port);
  14055. cli.enable_server_certificate_verification(false);
  14056. session_t verifier_session = nullptr;
  14057. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14058. verifier_session = ctx.session;
  14059. return true;
  14060. });
  14061. session_t session_verifier_session = nullptr;
  14062. cli.set_session_verifier([&](session_t session) {
  14063. session_verifier_session = session;
  14064. return SSLVerifierResponse::NoDecisionMade;
  14065. });
  14066. auto res = cli.Get("/test");
  14067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14068. EXPECT_NE(nullptr, verifier_session);
  14069. EXPECT_EQ(session_verifier_session, verifier_session);
  14070. }
  14071. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14072. using httplib::tls::TlsError;
  14073. // Test that verify_error_to_string returns empty for success
  14074. std::string success_str = TlsError::verify_error_to_string(0);
  14075. EXPECT_TRUE(success_str.empty());
  14076. // Test that verify_error_to_string returns non-empty for error codes
  14077. // Using a common error code (certificate expired)
  14078. std::string error_str =
  14079. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14080. EXPECT_FALSE(error_str.empty());
  14081. }
  14082. TEST(SessionVerifierTest, CertificateAccepted) {
  14083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14084. ASSERT_TRUE(svr.is_valid());
  14085. svr.Get("/test", [](const Request &, Response &res) {
  14086. res.set_content("ok", "text/plain");
  14087. });
  14088. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14089. auto se = detail::scope_exit([&] {
  14090. svr.stop();
  14091. t.join();
  14092. });
  14093. svr.wait_until_ready();
  14094. SSLClient cli(HOST, PORT);
  14095. cli.enable_server_certificate_verification(false);
  14096. cli.set_connection_timeout(30);
  14097. bool callback_called = false;
  14098. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14099. EXPECT_NE(session, nullptr);
  14100. callback_called = true;
  14101. return SSLVerifierResponse::CertificateAccepted;
  14102. });
  14103. auto res = cli.Get("/test");
  14104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14105. EXPECT_EQ(200, res->status);
  14106. EXPECT_TRUE(callback_called);
  14107. }
  14108. TEST(SessionVerifierTest, CertificateRejected) {
  14109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14110. ASSERT_TRUE(svr.is_valid());
  14111. svr.Get("/test", [](const Request &, Response &res) {
  14112. res.set_content("ok", "text/plain");
  14113. });
  14114. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14115. auto se = detail::scope_exit([&] {
  14116. svr.stop();
  14117. t.join();
  14118. });
  14119. svr.wait_until_ready();
  14120. SSLClient cli(HOST, PORT);
  14121. cli.enable_server_certificate_verification(false);
  14122. cli.set_connection_timeout(30);
  14123. bool callback_called = false;
  14124. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14125. EXPECT_NE(session, nullptr);
  14126. callback_called = true;
  14127. return SSLVerifierResponse::CertificateRejected;
  14128. });
  14129. auto res = cli.Get("/test");
  14130. EXPECT_FALSE(res);
  14131. EXPECT_TRUE(callback_called);
  14132. }
  14133. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14135. ASSERT_TRUE(svr.is_valid());
  14136. svr.Get("/test", [](const Request &, Response &res) {
  14137. res.set_content("ok", "text/plain");
  14138. });
  14139. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. });
  14144. svr.wait_until_ready();
  14145. // NoDecisionMade with verification disabled should succeed (no default check)
  14146. SSLClient cli(HOST, PORT);
  14147. cli.enable_server_certificate_verification(false);
  14148. cli.set_connection_timeout(30);
  14149. bool callback_called = false;
  14150. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14151. EXPECT_NE(session, nullptr);
  14152. callback_called = true;
  14153. return SSLVerifierResponse::NoDecisionMade;
  14154. });
  14155. auto res = cli.Get("/test");
  14156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14157. EXPECT_EQ(200, res->status);
  14158. EXPECT_TRUE(callback_called);
  14159. }
  14160. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14162. ASSERT_TRUE(svr.is_valid());
  14163. svr.Get("/test", [](const Request &, Response &res) {
  14164. res.set_content("ok", "text/plain");
  14165. });
  14166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14167. auto se = detail::scope_exit([&] {
  14168. svr.stop();
  14169. t.join();
  14170. });
  14171. svr.wait_until_ready();
  14172. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14173. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14174. // so we only check that the request fails, not whether the callback was
  14175. // called.
  14176. SSLClient cli(HOST, PORT);
  14177. cli.enable_server_certificate_verification(true);
  14178. cli.set_connection_timeout(30);
  14179. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14180. EXPECT_NE(session, nullptr);
  14181. return SSLVerifierResponse::NoDecisionMade;
  14182. });
  14183. auto res = cli.Get("/test");
  14184. EXPECT_FALSE(res);
  14185. }
  14186. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14187. // Test SSL server using PemMemory constructor with client CA certificates
  14188. // Read PEM files
  14189. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14190. read_file(SERVER_CERT_FILE, server_cert_pem);
  14191. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14192. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14193. // Create SSLServer with PemMemory constructor including client CA
  14194. SSLServer::PemMemory server_pem = {
  14195. server_cert_pem.c_str(),
  14196. server_cert_pem.size(),
  14197. server_key_pem.c_str(),
  14198. server_key_pem.size(),
  14199. client_ca_pem.c_str(),
  14200. client_ca_pem.size(),
  14201. nullptr // no password for server key
  14202. };
  14203. SSLServer svr(server_pem);
  14204. ASSERT_TRUE(svr.is_valid());
  14205. // No SSL error should be recorded for valid setup
  14206. EXPECT_EQ(0, svr.ssl_last_error());
  14207. // Set up server endpoints
  14208. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14209. res.set_content("ok", "text/plain");
  14210. });
  14211. // Start server in a thread
  14212. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14213. svr.wait_until_ready();
  14214. // Connect with client certificate (using constructor with paths)
  14215. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14216. cli.enable_server_certificate_verification(false);
  14217. auto res = cli.Get("/test-pem-ca");
  14218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14219. EXPECT_EQ(200, res->status);
  14220. EXPECT_EQ("ok", res->body);
  14221. svr.stop();
  14222. server_thread.join();
  14223. }
  14224. #endif
  14225. #ifdef _WIN32
  14226. TEST(CleanupTest, WSACleanup) {
  14227. int ret = WSACleanup();
  14228. ASSERT_EQ(0, ret);
  14229. }
  14230. #endif
  14231. #ifndef CPPHTTPLIB_SSL_ENABLED
  14232. TEST(NoSSLSupport, SimpleInterface) {
  14233. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14234. }
  14235. #endif
  14236. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14237. TEST(InvalidScheme, SimpleInterface) {
  14238. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14239. }
  14240. #endif
  14241. TEST(NoScheme, SimpleInterface) {
  14242. Client cli("yahoo.com:80");
  14243. ASSERT_TRUE(cli.is_valid());
  14244. }
  14245. TEST(SendAPI, SimpleInterface_Online) {
  14246. Client cli("http://yahoo.com");
  14247. Request req;
  14248. req.method = "GET";
  14249. req.path = "/";
  14250. auto res = cli.send(req);
  14251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14252. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14253. }
  14254. TEST(SendAPI, WithParamsInRequest) {
  14255. Server svr;
  14256. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14257. EXPECT_TRUE(req.has_param("test"));
  14258. EXPECT_EQ("test_value", req.get_param_value("test"));
  14259. });
  14260. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14261. auto se = detail::scope_exit([&] {
  14262. svr.stop();
  14263. t.join();
  14264. ASSERT_FALSE(svr.is_running());
  14265. });
  14266. svr.wait_until_ready();
  14267. Client cli(HOST, PORT);
  14268. {
  14269. Request req;
  14270. req.method = "GET";
  14271. req.path = "/";
  14272. req.params.emplace("test", "test_value");
  14273. auto res = cli.send(req);
  14274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14275. }
  14276. {
  14277. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14279. }
  14280. }
  14281. TEST(ClientImplMethods, GetSocketTest) {
  14282. httplib::Server svr;
  14283. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14284. res.status = StatusCode::OK_200;
  14285. });
  14286. auto port = svr.bind_to_any_port("127.0.0.1");
  14287. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14288. auto se = detail::scope_exit([&] {
  14289. svr.stop();
  14290. thread.join();
  14291. ASSERT_FALSE(svr.is_running());
  14292. });
  14293. svr.wait_until_ready();
  14294. {
  14295. httplib::Client cli("127.0.0.1", port);
  14296. cli.set_keep_alive(true);
  14297. // Use the behavior of cpp-httplib of opening the connection
  14298. // only when the first request happens. If that changes,
  14299. // this test would be obsolete.
  14300. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14301. // This also implicitly tests the server. But other tests would fail much
  14302. // earlier than this one to be considered.
  14303. auto res = cli.Get("/");
  14304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14305. EXPECT_EQ(StatusCode::OK_200, res->status);
  14306. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14307. }
  14308. }
  14309. #ifdef CPPHTTPLIB_SSL_ENABLED
  14310. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14311. Client cli("http://yahoo.com");
  14312. auto res = cli.Get("/");
  14313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14314. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14315. cli.set_follow_location(true);
  14316. res = cli.Get("/");
  14317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14318. EXPECT_EQ(StatusCode::OK_200, res->status);
  14319. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14320. }
  14321. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14322. Client cli("https://yahoo.com");
  14323. auto res = cli.Get("/");
  14324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14325. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14326. cli.set_follow_location(true);
  14327. res = cli.Get("/");
  14328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14329. EXPECT_EQ(StatusCode::OK_200, res->status);
  14330. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14331. }
  14332. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14333. Client cli("https://yahoo.com");
  14334. auto res = cli.Get("/");
  14335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14336. ASSERT_FALSE(!res);
  14337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14338. ASSERT_FALSE(res == nullptr);
  14339. ASSERT_TRUE(res != nullptr);
  14340. EXPECT_EQ(Error::Success, res.error());
  14341. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14342. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14343. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14344. cli.set_follow_location(true);
  14345. res = cli.Get("/");
  14346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14347. EXPECT_EQ(Error::Success, res.error());
  14348. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14349. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14350. EXPECT_EQ(StatusCode::OK_200, res->status);
  14351. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14352. }
  14353. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14354. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14355. Client cli("https://cdnjs.cloudflare.com");
  14356. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14357. Headers{{"Accept-Encoding", "br"}});
  14358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14359. EXPECT_EQ(StatusCode::OK_200, res->status);
  14360. EXPECT_EQ(287630U, res->body.size());
  14361. EXPECT_EQ("application/javascript; charset=utf-8",
  14362. res->get_header_value("Content-Type"));
  14363. }
  14364. #endif
  14365. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14366. #undef REDIR_HOST // Silence compiler warning
  14367. #define REDIR_HOST "https://httpbingo.org"
  14368. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14369. Client cli(REDIR_HOST);
  14370. cli.set_follow_location(true);
  14371. auto res =
  14372. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14374. EXPECT_EQ(StatusCode::OK_200, res->status);
  14375. }
  14376. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14377. Client cli(REDIR_HOST);
  14378. cli.set_follow_location(true);
  14379. Params params;
  14380. params.emplace("url", "http://example.com");
  14381. params.emplace("status_code", "302");
  14382. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14384. EXPECT_EQ(StatusCode::OK_200, res->status);
  14385. }
  14386. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14387. Client cli(REDIR_HOST);
  14388. cli.set_follow_location(true);
  14389. Params params;
  14390. params.emplace("url", "http://example.com");
  14391. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14393. EXPECT_EQ(StatusCode::OK_200, res->status);
  14394. }
  14395. TEST(HttpToHttpsRedirectTest, CertFile) {
  14396. auto ssl_port = PORT + 1;
  14397. Server svr;
  14398. ASSERT_TRUE(svr.is_valid());
  14399. svr.Get("/index", [&](const Request &, Response &res) {
  14400. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14401. "/index");
  14402. svr.stop();
  14403. });
  14404. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14405. ASSERT_TRUE(ssl_svr.is_valid());
  14406. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14407. res.set_content("test", "text/plain");
  14408. ssl_svr.stop();
  14409. });
  14410. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14411. thread t2 =
  14412. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14413. auto se = detail::scope_exit([&] {
  14414. t2.join();
  14415. t.join();
  14416. ASSERT_FALSE(svr.is_running());
  14417. });
  14418. svr.wait_until_ready();
  14419. ssl_svr.wait_until_ready();
  14420. Client cli("127.0.0.1", PORT);
  14421. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14422. cli.enable_server_certificate_verification(true);
  14423. cli.set_follow_location(true);
  14424. cli.set_connection_timeout(30);
  14425. auto res = cli.Get("/index");
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::OK_200, res->status);
  14428. }
  14429. TEST(SSLClientRedirectTest, CertFile) {
  14430. auto ssl_port = PORT + 1;
  14431. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14432. ASSERT_TRUE(ssl_svr1.is_valid());
  14433. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14434. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14435. "/index");
  14436. ssl_svr1.stop();
  14437. });
  14438. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14439. ASSERT_TRUE(ssl_svr2.is_valid());
  14440. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14441. res.set_content("test", "text/plain");
  14442. ssl_svr2.stop();
  14443. });
  14444. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14445. thread t2 =
  14446. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14447. auto se = detail::scope_exit([&] {
  14448. t2.join();
  14449. t.join();
  14450. ASSERT_FALSE(ssl_svr1.is_running());
  14451. });
  14452. ssl_svr1.wait_until_ready();
  14453. ssl_svr2.wait_until_ready();
  14454. SSLClient cli("127.0.0.1", PORT);
  14455. std::string cert;
  14456. read_file(SERVER_CERT2_FILE, cert);
  14457. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14458. cli.enable_server_certificate_verification(true);
  14459. cli.set_follow_location(true);
  14460. cli.set_connection_timeout(30);
  14461. auto res = cli.Get("/index");
  14462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14463. ASSERT_EQ(StatusCode::OK_200, res->status);
  14464. }
  14465. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14466. // another port, so the client follows it with a new client.
  14467. static Result GetThroughTlsRedirectToDifferentPort(
  14468. const std::function<void(SSLClient &)> &setup,
  14469. const char *target_cert = SERVER_CERT2_FILE) {
  14470. auto ssl_port = PORT + 1;
  14471. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14472. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14473. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14474. "/index");
  14475. });
  14476. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14477. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14478. res.set_content("test", "text/plain");
  14479. });
  14480. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14481. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14482. auto se = detail::scope_exit([&] {
  14483. ssl_svr2.stop();
  14484. ssl_svr1.stop();
  14485. t2.join();
  14486. t.join();
  14487. });
  14488. ssl_svr1.wait_until_ready();
  14489. ssl_svr2.wait_until_ready();
  14490. SSLClient cli("127.0.0.1", PORT);
  14491. cli.set_follow_location(true);
  14492. cli.set_connection_timeout(30);
  14493. setup(cli);
  14494. return cli.Get("/index");
  14495. }
  14496. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14497. auto calls = 0;
  14498. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14499. cli.enable_server_certificate_verification(false);
  14500. // Accept the first server only.
  14501. cli.set_session_verifier([&](tls::session_t) {
  14502. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14503. : SSLVerifierResponse::CertificateRejected;
  14504. });
  14505. });
  14506. EXPECT_FALSE(res);
  14507. EXPECT_EQ(2, calls);
  14508. }
  14509. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14510. std::string pinned;
  14511. auto res = GetThroughTlsRedirectToDifferentPort(
  14512. [&](SSLClient &cli) {
  14513. cli.enable_server_certificate_verification(false);
  14514. // Pin the first certificate seen.
  14515. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14516. if (pinned.empty()) { pinned = ctx.serial(); }
  14517. return ctx.serial() == pinned;
  14518. });
  14519. },
  14520. // A certificate other than the first server's.
  14521. SERVER_CERT_FILE);
  14522. EXPECT_FALSE(res);
  14523. EXPECT_FALSE(pinned.empty());
  14524. }
  14525. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14526. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14527. std::string cert;
  14528. read_file(SERVER_CERT2_FILE, cert);
  14529. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14530. });
  14531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14532. EXPECT_EQ(StatusCode::OK_200, res->status);
  14533. }
  14534. #endif
  14535. #ifdef CPPHTTPLIB_SSL_ENABLED
  14536. // Test that set_ca_cert_store() skips system certs (consistent with
  14537. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14538. // should be trusted - system certs should NOT be loaded.
  14539. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14540. // Load a specific cert that is NOT a system CA cert
  14541. std::string cert;
  14542. read_file(SERVER_CERT2_FILE, cert);
  14543. SSLClient cli("google.com");
  14544. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14545. cli.enable_server_certificate_verification(true);
  14546. // This should FAIL because:
  14547. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14548. // 2. System certs should NOT be loaded when custom store is set
  14549. // If system certs WERE loaded, this would succeed
  14550. auto res = cli.Get("/");
  14551. ASSERT_FALSE(res);
  14552. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14553. }
  14554. // Same as above, but through the native store handle path. Regression test:
  14555. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14556. // merged system certs into the user-provided store.
  14557. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14558. std::string cert;
  14559. read_file(SERVER_CERT2_FILE, cert);
  14560. SSLClient cli("google.com");
  14561. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14562. cli.enable_server_certificate_verification(true);
  14563. auto res = cli.Get("/");
  14564. ASSERT_FALSE(res);
  14565. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14566. }
  14567. // A custom store set via the native handle must still verify a server whose
  14568. // cert it does contain.
  14569. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14570. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14571. ASSERT_TRUE(svr.is_valid());
  14572. svr.Get("/test", [&](const Request &, Response &res) {
  14573. res.set_content("test", "text/plain");
  14574. });
  14575. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14576. auto se = detail::scope_exit([&] {
  14577. svr.stop();
  14578. t.join();
  14579. ASSERT_FALSE(svr.is_running());
  14580. });
  14581. svr.wait_until_ready();
  14582. SSLClient cli("127.0.0.1", PORT);
  14583. std::string cert;
  14584. read_file(SERVER_CERT2_FILE, cert);
  14585. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14586. cli.enable_server_certificate_verification(true);
  14587. cli.set_connection_timeout(30);
  14588. auto res = cli.Get("/test");
  14589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14590. ASSERT_EQ(StatusCode::OK_200, res->status);
  14591. }
  14592. // CA certs loaded through the universal Client must be transferred to the
  14593. // client created internally for following an HTTPS redirect. Regression test:
  14594. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14595. // the CA data for redirect transfer.
  14596. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14597. auto ssl_port = PORT + 1;
  14598. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14599. ASSERT_TRUE(ssl_svr1.is_valid());
  14600. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14601. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14602. "/index");
  14603. });
  14604. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14605. ASSERT_TRUE(ssl_svr2.is_valid());
  14606. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14607. res.set_content("test", "text/plain");
  14608. });
  14609. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14610. thread t2 =
  14611. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14612. auto se = detail::scope_exit([&] {
  14613. ssl_svr2.stop();
  14614. ssl_svr1.stop();
  14615. t2.join();
  14616. t.join();
  14617. ASSERT_FALSE(ssl_svr1.is_running());
  14618. });
  14619. ssl_svr1.wait_until_ready();
  14620. ssl_svr2.wait_until_ready();
  14621. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14622. std::string cert;
  14623. read_file(SERVER_CERT2_FILE, cert);
  14624. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14625. cli.enable_server_certificate_verification(true);
  14626. cli.set_follow_location(true);
  14627. cli.set_connection_timeout(30);
  14628. auto res = cli.Get("/index");
  14629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14630. ASSERT_EQ(StatusCode::OK_200, res->status);
  14631. }
  14632. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14633. // so a host signed by a system CA verifies even though a custom CA is set
  14634. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14635. std::string cert;
  14636. read_file(SERVER_CERT2_FILE, cert);
  14637. SSLClient cli("google.com");
  14638. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14639. cli.enable_system_ca(true);
  14640. cli.enable_server_certificate_verification(true);
  14641. auto res = cli.Get("/");
  14642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14643. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14644. }
  14645. // The custom CA remains effective when combined with the system CA
  14646. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14647. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14648. ASSERT_TRUE(svr.is_valid());
  14649. svr.Get("/test", [&](const Request &, Response &res) {
  14650. res.set_content("test", "text/plain");
  14651. });
  14652. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14653. auto se = detail::scope_exit([&] {
  14654. svr.stop();
  14655. t.join();
  14656. ASSERT_FALSE(svr.is_running());
  14657. });
  14658. svr.wait_until_ready();
  14659. SSLClient cli("127.0.0.1", PORT);
  14660. std::string cert;
  14661. read_file(SERVER_CERT2_FILE, cert);
  14662. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14663. cli.enable_system_ca(true);
  14664. cli.enable_server_certificate_verification(true);
  14665. cli.set_connection_timeout(30);
  14666. auto res = cli.Get("/test");
  14667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14668. ASSERT_EQ(StatusCode::OK_200, res->status);
  14669. }
  14670. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14671. // skip chain verification entirely (only the certificate identity was
  14672. // checked), so a server presenting an untrusted certificate with a matching
  14673. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14674. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14675. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14676. ASSERT_TRUE(svr.is_valid());
  14677. svr.Get("/test", [&](const Request &, Response &res) {
  14678. res.set_content("test", "text/plain");
  14679. });
  14680. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14681. auto se = detail::scope_exit([&] {
  14682. svr.stop();
  14683. t.join();
  14684. ASSERT_FALSE(svr.is_running());
  14685. });
  14686. svr.wait_until_ready();
  14687. SSLClient cli("127.0.0.1", PORT);
  14688. std::string cert;
  14689. // A trusted CA that did not sign the server certificate. The server cert
  14690. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14691. // this connection.
  14692. read_file(CLIENT_CA_CERT_FILE, cert);
  14693. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14694. cli.enable_server_certificate_verification(true);
  14695. cli.set_connection_timeout(30);
  14696. auto res = cli.Get("/test");
  14697. ASSERT_FALSE(res);
  14698. }
  14699. // enable_system_ca(false) prevents system CA loading entirely
  14700. TEST(SSLClientTest, DisableSystemCa_Online) {
  14701. SSLClient cli("google.com");
  14702. cli.enable_system_ca(false);
  14703. cli.enable_server_certificate_verification(true);
  14704. auto res = cli.Get("/");
  14705. ASSERT_FALSE(res);
  14706. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14707. // itself when the CA chain is empty
  14708. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14709. res.error() == Error::SSLConnection);
  14710. }
  14711. // The universal Client forwards enable_system_ca()
  14712. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14713. std::string cert;
  14714. read_file(SERVER_CERT2_FILE, cert);
  14715. Client cli("https://google.com");
  14716. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14717. cli.enable_system_ca(true);
  14718. cli.enable_server_certificate_verification(true);
  14719. auto res = cli.Get("/");
  14720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14721. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14722. }
  14723. // The system CA policy must carry over to the client created internally for
  14724. // following a cross-host HTTPS redirect
  14725. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14726. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14727. ASSERT_TRUE(svr.is_valid());
  14728. svr.Get("/index", [&](const Request &, Response &res) {
  14729. res.set_redirect("https://www.google.com/");
  14730. });
  14731. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14732. auto se = detail::scope_exit([&] {
  14733. svr.stop();
  14734. t.join();
  14735. ASSERT_FALSE(svr.is_running());
  14736. });
  14737. svr.wait_until_ready();
  14738. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14739. std::string cert;
  14740. read_file(SERVER_CERT2_FILE, cert);
  14741. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14742. cli.enable_system_ca(true);
  14743. cli.enable_server_certificate_verification(true);
  14744. cli.set_follow_location(true);
  14745. cli.set_connection_timeout(30);
  14746. // Receiving any response proves the redirect client completed the TLS
  14747. // handshake with a system-CA-signed host
  14748. auto res = cli.Get("/index");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. }
  14751. TEST(MultipartFormDataTest, LargeData) {
  14752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14753. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14754. const ContentReader &content_reader) {
  14755. if (req.is_multipart_form_data()) {
  14756. std::vector<FormData> items;
  14757. content_reader(
  14758. [&](const FormData &file) {
  14759. items.push_back(file);
  14760. return true;
  14761. },
  14762. [&](const char *data, size_t data_length) {
  14763. items.back().content.append(data, data_length);
  14764. return true;
  14765. });
  14766. EXPECT_TRUE(std::string(items[0].name) == "document");
  14767. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14768. EXPECT_TRUE(items[0].filename == "2MB_data");
  14769. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14770. EXPECT_TRUE(items[1].name == "hello");
  14771. EXPECT_TRUE(items[1].content == "world");
  14772. EXPECT_TRUE(items[1].filename == "");
  14773. EXPECT_TRUE(items[1].content_type == "");
  14774. } else {
  14775. std::string body;
  14776. content_reader([&](const char *data, size_t data_length) {
  14777. body.append(data, data_length);
  14778. return true;
  14779. });
  14780. }
  14781. });
  14782. auto port = svr.bind_to_any_port(HOST);
  14783. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14784. auto se = detail::scope_exit([&] {
  14785. svr.stop();
  14786. t.join();
  14787. ASSERT_FALSE(svr.is_running());
  14788. });
  14789. svr.wait_until_ready();
  14790. {
  14791. std::string data(1024 * 1024 * 2, '.');
  14792. std::stringstream buffer;
  14793. buffer << data;
  14794. SSLClient cli(HOST, port);
  14795. cli.enable_server_certificate_verification(false);
  14796. UploadFormDataItems items{
  14797. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14798. {"hello", "world", "", ""},
  14799. };
  14800. auto res = cli.Post("/post", items);
  14801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14802. ASSERT_EQ(StatusCode::OK_200, res->status);
  14803. }
  14804. }
  14805. TEST(MultipartFormDataTest, DataProviderItems) {
  14806. std::random_device seed_gen;
  14807. std::mt19937 random(seed_gen());
  14808. std::string rand1;
  14809. rand1.resize(1000);
  14810. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14811. std::string rand2;
  14812. rand2.resize(3000);
  14813. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14815. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14816. const ContentReader &content_reader) {
  14817. ASSERT_FALSE(req.is_multipart_form_data());
  14818. std::string body;
  14819. content_reader([&](const char *data, size_t data_length) {
  14820. body.append(data, data_length);
  14821. return true;
  14822. });
  14823. EXPECT_EQ(body, "");
  14824. });
  14825. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14826. const ContentReader &content_reader) {
  14827. ASSERT_TRUE(req.is_multipart_form_data());
  14828. std::vector<FormData> items;
  14829. content_reader(
  14830. [&](const FormData &file) {
  14831. items.push_back(file);
  14832. return true;
  14833. },
  14834. [&](const char *data, size_t data_length) {
  14835. items.back().content.append(data, data_length);
  14836. return true;
  14837. });
  14838. ASSERT_TRUE(items.size() == 2);
  14839. EXPECT_EQ(std::string(items[0].name), "name1");
  14840. EXPECT_EQ(items[0].content, "Testing123");
  14841. EXPECT_EQ(items[0].filename, "filename1");
  14842. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14843. EXPECT_EQ(items[1].name, "name2");
  14844. EXPECT_EQ(items[1].content, "Testing456");
  14845. EXPECT_EQ(items[1].filename, "");
  14846. EXPECT_EQ(items[1].content_type, "");
  14847. });
  14848. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14849. const ContentReader &content_reader) {
  14850. ASSERT_TRUE(req.is_multipart_form_data());
  14851. std::vector<FormData> items;
  14852. content_reader(
  14853. [&](const FormData &file) {
  14854. items.push_back(file);
  14855. return true;
  14856. },
  14857. [&](const char *data, size_t data_length) {
  14858. items.back().content.append(data, data_length);
  14859. return true;
  14860. });
  14861. ASSERT_TRUE(items.size() == 2);
  14862. EXPECT_EQ(items[0].name, "name3");
  14863. EXPECT_EQ(items[0].content, rand1);
  14864. EXPECT_EQ(items[0].filename, "filename3");
  14865. EXPECT_EQ(items[0].content_type, "");
  14866. EXPECT_EQ(items[1].name, "name4");
  14867. EXPECT_EQ(items[1].content, rand2);
  14868. EXPECT_EQ(items[1].filename, "filename4");
  14869. EXPECT_EQ(items[1].content_type, "");
  14870. });
  14871. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14872. const ContentReader &content_reader) {
  14873. ASSERT_TRUE(req.is_multipart_form_data());
  14874. std::vector<FormData> items;
  14875. content_reader(
  14876. [&](const FormData &file) {
  14877. items.push_back(file);
  14878. return true;
  14879. },
  14880. [&](const char *data, size_t data_length) {
  14881. items.back().content.append(data, data_length);
  14882. return true;
  14883. });
  14884. ASSERT_TRUE(items.size() == 4);
  14885. EXPECT_EQ(std::string(items[0].name), "name1");
  14886. EXPECT_EQ(items[0].content, "Testing123");
  14887. EXPECT_EQ(items[0].filename, "filename1");
  14888. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14889. EXPECT_EQ(items[1].name, "name2");
  14890. EXPECT_EQ(items[1].content, "Testing456");
  14891. EXPECT_EQ(items[1].filename, "");
  14892. EXPECT_EQ(items[1].content_type, "");
  14893. EXPECT_EQ(items[2].name, "name3");
  14894. EXPECT_EQ(items[2].content, rand1);
  14895. EXPECT_EQ(items[2].filename, "filename3");
  14896. EXPECT_EQ(items[2].content_type, "");
  14897. EXPECT_EQ(items[3].name, "name4");
  14898. EXPECT_EQ(items[3].content, rand2);
  14899. EXPECT_EQ(items[3].filename, "filename4");
  14900. EXPECT_EQ(items[3].content_type, "");
  14901. });
  14902. auto port = svr.bind_to_any_port("localhost");
  14903. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14904. auto se = detail::scope_exit([&] {
  14905. svr.stop();
  14906. t.join();
  14907. ASSERT_FALSE(svr.is_running());
  14908. });
  14909. svr.wait_until_ready();
  14910. {
  14911. SSLClient cli("localhost", port);
  14912. cli.enable_server_certificate_verification(false);
  14913. UploadFormDataItems items{
  14914. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14915. {"name2", "Testing456", "", ""}, // not a file
  14916. };
  14917. {
  14918. auto res = cli.Post("/post-none", {}, {}, {});
  14919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14920. ASSERT_EQ(StatusCode::OK_200, res->status);
  14921. }
  14922. FormDataProviderItems providers;
  14923. {
  14924. auto res =
  14925. cli.Post("/post-items", {}, items, providers); // empty providers
  14926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14927. ASSERT_EQ(StatusCode::OK_200, res->status);
  14928. }
  14929. providers.push_back({"name3",
  14930. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14931. // test the offset is given correctly at each step
  14932. if (!offset)
  14933. sink.os.write(rand1.data(), 30);
  14934. else if (offset == 30)
  14935. sink.os.write(rand1.data() + 30, 300);
  14936. else if (offset == 330)
  14937. sink.os.write(rand1.data() + 330, 670);
  14938. else if (offset == rand1.size())
  14939. sink.done();
  14940. return true;
  14941. },
  14942. "filename3",
  14943. {}});
  14944. providers.push_back({"name4",
  14945. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14946. // test the offset is given correctly at each step
  14947. if (!offset)
  14948. sink.os.write(rand2.data(), 2000);
  14949. else if (offset == 2000)
  14950. sink.os.write(rand2.data() + 2000, 1);
  14951. else if (offset == 2001)
  14952. sink.os.write(rand2.data() + 2001, 999);
  14953. else if (offset == rand2.size())
  14954. sink.done();
  14955. return true;
  14956. },
  14957. "filename4",
  14958. {}});
  14959. {
  14960. auto res = cli.Post("/post-providers", {}, {}, providers);
  14961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14962. ASSERT_EQ(StatusCode::OK_200, res->status);
  14963. }
  14964. {
  14965. auto res = cli.Post("/post-both", {}, items, providers);
  14966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14967. ASSERT_EQ(StatusCode::OK_200, res->status);
  14968. }
  14969. }
  14970. }
  14971. TEST(MultipartFormDataTest, BadHeader) {
  14972. Server svr;
  14973. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14974. res.set_content("ok", "text/plain");
  14975. });
  14976. thread t = thread([&] { svr.listen(HOST, PORT); });
  14977. auto se = detail::scope_exit([&] {
  14978. svr.stop();
  14979. t.join();
  14980. ASSERT_FALSE(svr.is_running());
  14981. });
  14982. svr.wait_until_ready();
  14983. const std::string body =
  14984. "This is the preamble. It is to be ignored, though it\r\n"
  14985. "is a handy place for composition agents to include an\r\n"
  14986. "explanatory note to non-MIME conformant readers.\r\n"
  14987. "\r\n"
  14988. "\r\n"
  14989. "--simple boundary\r\n"
  14990. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14991. ": BAD...\r\n"
  14992. "\r\n"
  14993. "value1\r\n"
  14994. "--simple boundary\r\n"
  14995. "Content-Disposition: form-data; name=\"field2\"; "
  14996. "filename=\"example.txt\"\r\n"
  14997. "\r\n"
  14998. "value2\r\n"
  14999. "--simple boundary--\r\n"
  15000. "This is the epilogue. It is also to be ignored.\r\n";
  15001. std::string content_type =
  15002. R"(multipart/form-data; boundary="simple boundary")";
  15003. Client cli(HOST, PORT);
  15004. auto res = cli.Post("/post", body, content_type.c_str());
  15005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15006. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15007. }
  15008. TEST(MultipartFormDataTest, WithPreamble) {
  15009. Server svr;
  15010. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15011. res.set_content("ok", "text/plain");
  15012. });
  15013. thread t = thread([&] { svr.listen(HOST, PORT); });
  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. const std::string body =
  15021. "This is the preamble. It is to be ignored, though it\r\n"
  15022. "is a handy place for composition agents to include an\r\n"
  15023. "explanatory note to non-MIME conformant readers.\r\n"
  15024. "\r\n"
  15025. "\r\n"
  15026. "--simple boundary\r\n"
  15027. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15028. "\r\n"
  15029. "value1\r\n"
  15030. "--simple boundary\r\n"
  15031. "Content-Disposition: form-data; name=\"field2\"; "
  15032. "filename=\"example.txt\"\r\n"
  15033. "\r\n"
  15034. "value2\r\n"
  15035. "--simple boundary--\r\n"
  15036. "This is the epilogue. It is also to be ignored.\r\n";
  15037. std::string content_type =
  15038. R"(multipart/form-data; boundary="simple boundary")";
  15039. Client cli(HOST, PORT);
  15040. auto res = cli.Post("/post", body, content_type.c_str());
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. EXPECT_EQ(StatusCode::OK_200, res->status);
  15043. }
  15044. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15046. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15047. const ContentReader &content_reader) {
  15048. if (req.is_multipart_form_data()) {
  15049. std::vector<FormData> items;
  15050. content_reader(
  15051. [&](const FormData &file) {
  15052. items.push_back(file);
  15053. return true;
  15054. },
  15055. [&](const char *data, size_t data_length) {
  15056. items.back().content.append(data, data_length);
  15057. return true;
  15058. });
  15059. EXPECT_TRUE(std::string(items[0].name) == "document");
  15060. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15061. EXPECT_TRUE(items[0].filename == "2MB_data");
  15062. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15063. EXPECT_TRUE(items[1].name == "hello");
  15064. EXPECT_TRUE(items[1].content == "world");
  15065. EXPECT_TRUE(items[1].filename == "");
  15066. EXPECT_TRUE(items[1].content_type == "");
  15067. } else {
  15068. std::string body;
  15069. content_reader([&](const char *data, size_t data_length) {
  15070. body.append(data, data_length);
  15071. return true;
  15072. });
  15073. }
  15074. });
  15075. auto port = svr.bind_to_any_port("localhost");
  15076. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15077. auto se = detail::scope_exit([&] {
  15078. svr.stop();
  15079. t.join();
  15080. ASSERT_FALSE(svr.is_running());
  15081. });
  15082. svr.wait_until_ready();
  15083. {
  15084. std::string data(1024 * 1024 * 2, '.');
  15085. std::stringstream buffer;
  15086. buffer << data;
  15087. SSLClient cli("localhost", port);
  15088. cli.enable_server_certificate_verification(false);
  15089. UploadFormDataItems items{
  15090. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15091. {"hello", "world", "", ""},
  15092. };
  15093. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15095. ASSERT_EQ(StatusCode::OK_200, res->status);
  15096. }
  15097. }
  15098. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15099. std::string data(1024 * 1024 * 2, '&');
  15100. std::stringstream buffer;
  15101. buffer << data;
  15102. Client cli("https://localhost:8080");
  15103. UploadFormDataItems items{
  15104. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15105. {"hello", "world", "", ""},
  15106. };
  15107. for (const char &c : " \t\r\n") {
  15108. auto res =
  15109. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15110. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15111. ASSERT_FALSE(res);
  15112. }
  15113. }
  15114. TEST(MultipartFormDataTest, PutFormData) {
  15115. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15116. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15117. const ContentReader &content_reader) {
  15118. if (req.is_multipart_form_data()) {
  15119. std::vector<FormData> items;
  15120. content_reader(
  15121. [&](const FormData &file) {
  15122. items.push_back(file);
  15123. return true;
  15124. },
  15125. [&](const char *data, size_t data_length) {
  15126. items.back().content.append(data, data_length);
  15127. return true;
  15128. });
  15129. EXPECT_TRUE(std::string(items[0].name) == "document");
  15130. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15131. EXPECT_TRUE(items[0].filename == "2MB_data");
  15132. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15133. EXPECT_TRUE(items[1].name == "hello");
  15134. EXPECT_TRUE(items[1].content == "world");
  15135. EXPECT_TRUE(items[1].filename == "");
  15136. EXPECT_TRUE(items[1].content_type == "");
  15137. } else {
  15138. std::string body;
  15139. content_reader([&](const char *data, size_t data_length) {
  15140. body.append(data, data_length);
  15141. return true;
  15142. });
  15143. }
  15144. });
  15145. auto port = svr.bind_to_any_port("localhost");
  15146. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15147. auto se = detail::scope_exit([&] {
  15148. svr.stop();
  15149. t.join();
  15150. ASSERT_FALSE(svr.is_running());
  15151. });
  15152. svr.wait_until_ready();
  15153. {
  15154. std::string data(1024 * 1024 * 2, '&');
  15155. std::stringstream buffer;
  15156. buffer << data;
  15157. SSLClient cli("localhost", port);
  15158. cli.enable_server_certificate_verification(false);
  15159. UploadFormDataItems items{
  15160. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15161. {"hello", "world", "", ""},
  15162. };
  15163. auto res = cli.Put("/put", items);
  15164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15165. ASSERT_EQ(StatusCode::OK_200, res->status);
  15166. }
  15167. }
  15168. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15170. svr.Put("/put_customboundary",
  15171. [&](const Request &req, const Response & /*res*/,
  15172. const ContentReader &content_reader) {
  15173. if (req.is_multipart_form_data()) {
  15174. std::vector<FormData> items;
  15175. content_reader(
  15176. [&](const FormData &file) {
  15177. items.push_back(file);
  15178. return true;
  15179. },
  15180. [&](const char *data, size_t data_length) {
  15181. items.back().content.append(data, data_length);
  15182. return true;
  15183. });
  15184. EXPECT_TRUE(std::string(items[0].name) == "document");
  15185. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15186. EXPECT_TRUE(items[0].filename == "2MB_data");
  15187. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15188. EXPECT_TRUE(items[1].name == "hello");
  15189. EXPECT_TRUE(items[1].content == "world");
  15190. EXPECT_TRUE(items[1].filename == "");
  15191. EXPECT_TRUE(items[1].content_type == "");
  15192. } else {
  15193. std::string body;
  15194. content_reader([&](const char *data, size_t data_length) {
  15195. body.append(data, data_length);
  15196. return true;
  15197. });
  15198. }
  15199. });
  15200. auto port = svr.bind_to_any_port("localhost");
  15201. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15202. auto se = detail::scope_exit([&] {
  15203. svr.stop();
  15204. t.join();
  15205. ASSERT_FALSE(svr.is_running());
  15206. });
  15207. svr.wait_until_ready();
  15208. {
  15209. std::string data(1024 * 1024 * 2, '&');
  15210. std::stringstream buffer;
  15211. buffer << data;
  15212. SSLClient cli("localhost", port);
  15213. cli.enable_server_certificate_verification(false);
  15214. UploadFormDataItems items{
  15215. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15216. {"hello", "world", "", ""},
  15217. };
  15218. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15220. ASSERT_EQ(StatusCode::OK_200, res->status);
  15221. }
  15222. }
  15223. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15224. std::string data(1024 * 1024 * 2, '&');
  15225. std::stringstream buffer;
  15226. buffer << data;
  15227. Client cli("https://localhost:8080");
  15228. cli.enable_server_certificate_verification(false);
  15229. UploadFormDataItems items{
  15230. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15231. {"hello", "world", "", ""},
  15232. };
  15233. for (const char &c : " \t\r\n") {
  15234. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15235. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15236. ASSERT_FALSE(res);
  15237. }
  15238. }
  15239. TEST(MultipartFormDataTest, AlternateFilename) {
  15240. auto handled = false;
  15241. Server svr;
  15242. svr.Post("/test", [&](const Request &req, Response &res) {
  15243. ASSERT_EQ(2u, req.form.files.size());
  15244. ASSERT_EQ(1u, req.form.fields.size());
  15245. // Test files
  15246. const auto &file1 = req.form.get_file("file1");
  15247. ASSERT_EQ("file1", file1.name);
  15248. ASSERT_EQ("A.txt", file1.filename);
  15249. ASSERT_EQ("text/plain", file1.content_type);
  15250. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15251. const auto &file2 = req.form.get_file("file2");
  15252. ASSERT_EQ("file2", file2.name);
  15253. ASSERT_EQ("a.html", file2.filename);
  15254. ASSERT_EQ("text/html", file2.content_type);
  15255. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15256. file2.content);
  15257. // Test text field
  15258. const auto &text = req.form.get_field("text");
  15259. ASSERT_EQ("text default", text);
  15260. res.set_content("ok", "text/plain");
  15261. handled = true;
  15262. });
  15263. thread t = thread([&] { svr.listen(HOST, PORT); });
  15264. auto se = detail::scope_exit([&] {
  15265. svr.stop();
  15266. t.join();
  15267. ASSERT_FALSE(svr.is_running());
  15268. ASSERT_TRUE(handled);
  15269. });
  15270. svr.wait_until_ready();
  15271. auto req = "POST /test HTTP/1.1\r\n"
  15272. "Host: localhost\r\n"
  15273. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15274. "Content-Length: 399\r\n"
  15275. "\r\n"
  15276. "----------\r\n"
  15277. "Content-Disposition: form-data; name=\"text\"\r\n"
  15278. "\r\n"
  15279. "text default\r\n"
  15280. "----------\r\n"
  15281. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15282. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15283. "Content-Type: text/plain\r\n"
  15284. "\r\n"
  15285. "Content of a.txt.\r\n"
  15286. "\r\n"
  15287. "----------\r\n"
  15288. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15289. "\"a.html\"\r\n"
  15290. "Content-Type: text/html\r\n"
  15291. "\r\n"
  15292. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15293. "\r\n"
  15294. "------------\r\n";
  15295. ASSERT_TRUE(send_request(1, req));
  15296. }
  15297. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15298. auto handled = false;
  15299. Server svr;
  15300. svr.Post("/test", [&](const Request &req, Response &res) {
  15301. // Case-insensitive "utf-8''" prefix with a long value
  15302. const auto &file = req.form.get_file("file1");
  15303. ASSERT_EQ("file1", file.name);
  15304. // 8000 chars exercises both the Content-Disposition parser and the
  15305. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15306. // Prior to the fix, std::regex_match on this header would cause O(N)
  15307. // stack recursion in libstdc++, leading to SIGSEGV.
  15308. std::string expected_filename(8000, 'A');
  15309. ASSERT_EQ(expected_filename, file.filename);
  15310. res.set_content("ok", "text/plain");
  15311. handled = true;
  15312. });
  15313. thread t = thread([&] { svr.listen(HOST, PORT); });
  15314. auto se = detail::scope_exit([&] {
  15315. svr.stop();
  15316. t.join();
  15317. ASSERT_FALSE(svr.is_running());
  15318. ASSERT_TRUE(handled);
  15319. });
  15320. svr.wait_until_ready();
  15321. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15322. // Regression test for GHSA-qq6v-r583-3h69
  15323. std::string long_filename(8000, 'A');
  15324. std::string body = "----------\r\n"
  15325. "Content-Disposition: form-data; name=\"file1\"; "
  15326. "filename*=\"Utf-8''" +
  15327. long_filename +
  15328. "\"\r\n"
  15329. "\r\n"
  15330. "hello\r\n"
  15331. "------------\r\n";
  15332. auto req = "POST /test HTTP/1.1\r\n"
  15333. "Host: localhost\r\n"
  15334. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15335. "Content-Length: " +
  15336. std::to_string(body.size()) + "\r\n\r\n" + body;
  15337. ASSERT_TRUE(send_request(1, req));
  15338. }
  15339. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15340. auto handled = false;
  15341. Server svr;
  15342. svr.Post("/test", [&](const Request &req, Response &) {
  15343. ASSERT_EQ(2u, req.form.fields.size());
  15344. const auto &text1 = req.form.get_field("text1");
  15345. ASSERT_EQ("text1", text1);
  15346. const auto &text2 = req.form.get_field("text2");
  15347. ASSERT_EQ("text2", text2);
  15348. handled = true;
  15349. });
  15350. thread t = thread([&] { svr.listen(HOST, PORT); });
  15351. auto se = detail::scope_exit([&] {
  15352. svr.stop();
  15353. t.join();
  15354. ASSERT_FALSE(svr.is_running());
  15355. ASSERT_TRUE(handled);
  15356. });
  15357. svr.wait_until_ready();
  15358. auto req = "POST /test HTTP/1.1\r\n"
  15359. "Host: localhost\r\n"
  15360. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15361. "Content-Length: 146\r\n"
  15362. "\r\n----------\r\n"
  15363. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15364. "\r\n"
  15365. "text1"
  15366. "\r\n----------\r\n"
  15367. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15368. "\r\n"
  15369. "text2"
  15370. "\r\n------------";
  15371. std::string response;
  15372. ASSERT_TRUE(send_request(1, req, &response));
  15373. ASSERT_EQ("200", response.substr(9, 3));
  15374. }
  15375. TEST(MultipartFormDataTest, ContentLength) {
  15376. auto handled = false;
  15377. Server svr;
  15378. svr.Post("/test", [&](const Request &req, Response &) {
  15379. ASSERT_EQ(2u, req.form.fields.size());
  15380. const auto &text1 = req.form.get_field("text1");
  15381. ASSERT_EQ("text1", text1);
  15382. const auto &text2 = req.form.get_field("text2");
  15383. ASSERT_EQ("text2", text2);
  15384. handled = true;
  15385. });
  15386. thread t = thread([&] { svr.listen(HOST, PORT); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. ASSERT_FALSE(svr.is_running());
  15391. ASSERT_TRUE(handled);
  15392. });
  15393. svr.wait_until_ready();
  15394. auto req = "POST /test HTTP/1.1\r\n"
  15395. "Host: localhost\r\n"
  15396. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15397. "Content-Length: 167\r\n"
  15398. "\r\n----------\r\n"
  15399. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15400. "Content-Length: 5\r\n"
  15401. "\r\n"
  15402. "text1"
  15403. "\r\n----------\r\n"
  15404. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15405. "\r\n"
  15406. "text2"
  15407. "\r\n------------\r\n";
  15408. std::string response;
  15409. ASSERT_TRUE(send_request(1, req, &response));
  15410. ASSERT_EQ("200", response.substr(9, 3));
  15411. }
  15412. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15413. auto handled = false;
  15414. Server svr;
  15415. svr.Post("/test", [&](const Request &req, Response &) {
  15416. ASSERT_EQ(2u, req.form.fields.size());
  15417. const auto &text1 = req.form.get_field("text1");
  15418. ASSERT_EQ("text1", text1);
  15419. // TODO: Add header access for text fields if needed
  15420. const auto &text2 = req.form.get_field("text2");
  15421. ASSERT_EQ("text2", text2);
  15422. // TODO: Header access for text fields needs to be implemented
  15423. // auto &headers = it->second.headers;
  15424. // ASSERT_EQ(3U, headers.size());
  15425. // auto custom_header = headers.find("x-whatever");
  15426. // ASSERT_TRUE(custom_header != headers.end());
  15427. // ASSERT_NE("customvalue", custom_header->second);
  15428. // ASSERT_EQ("CustomValue", custom_header->second);
  15429. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15430. handled = true;
  15431. });
  15432. thread t = thread([&] { svr.listen(HOST, PORT); });
  15433. auto se = detail::scope_exit([&] {
  15434. svr.stop();
  15435. t.join();
  15436. ASSERT_FALSE(svr.is_running());
  15437. ASSERT_TRUE(handled);
  15438. });
  15439. svr.wait_until_ready();
  15440. auto req = "POST /test HTTP/1.1\r\n"
  15441. "Host: localhost\r\n"
  15442. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15443. "Content-Length: 232\r\n"
  15444. "\r\n----------\r\n"
  15445. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15446. "Content-Length: 5\r\n"
  15447. "X-Test: 1\r\n"
  15448. "\r\n"
  15449. "text1"
  15450. "\r\n----------\r\n"
  15451. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15452. "Content-Type: text/plain\r\n"
  15453. "X-Whatever: CustomValue\r\n"
  15454. "\r\n"
  15455. "text2"
  15456. "\r\n------------\r\n"
  15457. "That should be disregarded. Not even read";
  15458. std::string response;
  15459. ASSERT_TRUE(send_request(1, req, &response));
  15460. ASSERT_EQ("200", response.substr(9, 3));
  15461. }
  15462. TEST(MultipartFormDataTest, LargeHeader) {
  15463. auto handled = false;
  15464. Server svr;
  15465. svr.Post("/test", [&](const Request &req, Response &) {
  15466. ASSERT_EQ(1u, req.form.fields.size());
  15467. const auto &text = req.form.get_field("name1");
  15468. ASSERT_EQ("text1", text);
  15469. handled = true;
  15470. });
  15471. thread t = thread([&] { svr.listen(HOST, PORT); });
  15472. auto se = detail::scope_exit([&] {
  15473. svr.stop();
  15474. t.join();
  15475. ASSERT_FALSE(svr.is_running());
  15476. ASSERT_TRUE(handled);
  15477. });
  15478. svr.wait_until_ready();
  15479. auto boundary = std::string("cpp-httplib-multipart-data");
  15480. std::string content = "--" + boundary +
  15481. "\r\n"
  15482. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15483. "\r\n"
  15484. "text1\r\n"
  15485. "--" +
  15486. boundary + "--\r\n";
  15487. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15488. "Host: localhost\r\n"
  15489. "Content-Type: multipart/form-data;boundary=" +
  15490. boundary +
  15491. "\r\n"
  15492. "Content-Length: " +
  15493. std::to_string(content.size()) +
  15494. "\r\n"
  15495. "Dummy-Header: ";
  15496. std::string header_suffix = "\r\n"
  15497. "\r\n";
  15498. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15499. size_t header_dummy_size =
  15500. read_buff_size -
  15501. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15502. auto header_dummy = std::string(header_dummy_size, '@');
  15503. auto req = header_prefix + header_dummy + header_suffix + content;
  15504. std::string response;
  15505. ASSERT_TRUE(send_request(1, req, &response));
  15506. ASSERT_EQ("200", response.substr(9, 3));
  15507. }
  15508. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15509. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15510. // (not chunked Transfer-Encoding) after the streaming refactor.
  15511. auto handled = false;
  15512. Server svr;
  15513. svr.Post("/upload", [&](const Request &req, Response &res) {
  15514. auto cl_it = req.headers.find("Content-Length");
  15515. EXPECT_TRUE(cl_it != req.headers.end());
  15516. auto te_it = req.headers.find("Transfer-Encoding");
  15517. EXPECT_TRUE(te_it == req.headers.end());
  15518. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15519. res.set_content("ok", "text/plain");
  15520. handled = true;
  15521. });
  15522. auto port = svr.bind_to_any_port(HOST);
  15523. auto t = thread([&] { svr.listen_after_bind(); });
  15524. auto se = detail::scope_exit([&] {
  15525. svr.stop();
  15526. t.join();
  15527. ASSERT_FALSE(svr.is_running());
  15528. ASSERT_TRUE(handled);
  15529. });
  15530. svr.wait_until_ready();
  15531. UploadFormDataItems items = {
  15532. {"field1", "hello", "", "text/plain"},
  15533. {"file1", "world", "test.txt", "application/octet-stream"},
  15534. };
  15535. Client cli(HOST, port);
  15536. auto res = cli.Post("/upload", {}, items);
  15537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15538. EXPECT_EQ(StatusCode::OK_200, res->status);
  15539. }
  15540. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15541. // Verify that make_multipart_content_provider coalesces many small segments
  15542. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15543. constexpr size_t kItemCount = 1000;
  15544. UploadFormDataItems items;
  15545. items.reserve(kItemCount);
  15546. for (size_t i = 0; i < kItemCount; i++) {
  15547. items.push_back(
  15548. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15549. }
  15550. const std::string boundary = "----test-boundary";
  15551. auto content_length = detail::get_multipart_content_length(items, boundary);
  15552. auto provider = detail::make_multipart_content_provider(items, boundary);
  15553. // Drive the provider the same way write_content_with_progress does
  15554. size_t write_count = 0;
  15555. size_t total_bytes = 0;
  15556. DataSink sink;
  15557. size_t offset = 0;
  15558. sink.write = [&](const char *d, size_t l) -> bool {
  15559. (void)d;
  15560. write_count++;
  15561. total_bytes += l;
  15562. offset += l;
  15563. return true;
  15564. };
  15565. sink.is_writable = []() -> bool { return true; };
  15566. while (offset < content_length) {
  15567. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15568. }
  15569. EXPECT_EQ(content_length, total_bytes);
  15570. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15571. // With buffering into 64KB blocks, write_count should be much smaller.
  15572. auto segment_count = 3 * kItemCount + 1;
  15573. EXPECT_LT(write_count, segment_count / 10);
  15574. }
  15575. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15576. // Integration test: send many UploadFormDataItems and verify the server
  15577. // receives all of them correctly (#2410).
  15578. constexpr size_t kItemCount = 500;
  15579. auto handled = false;
  15580. Server svr;
  15581. svr.Post("/upload", [&](const Request &req, Response &res) {
  15582. EXPECT_EQ(kItemCount, req.form.fields.size());
  15583. for (size_t i = 0; i < kItemCount; i++) {
  15584. auto key = "field" + std::to_string(i);
  15585. auto val = "value" + std::to_string(i);
  15586. auto it = req.form.fields.find(key);
  15587. if (it != req.form.fields.end()) {
  15588. EXPECT_EQ(val, it->second.content);
  15589. } else {
  15590. ADD_FAILURE() << "Missing field: " << key;
  15591. }
  15592. }
  15593. res.set_content("ok", "text/plain");
  15594. handled = true;
  15595. });
  15596. auto port = svr.bind_to_any_port(HOST);
  15597. auto t = thread([&] { svr.listen_after_bind(); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. t.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. ASSERT_TRUE(handled);
  15603. });
  15604. svr.wait_until_ready();
  15605. UploadFormDataItems items;
  15606. items.reserve(kItemCount);
  15607. for (size_t i = 0; i < kItemCount; i++) {
  15608. items.push_back(
  15609. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15610. }
  15611. Client cli(HOST, port);
  15612. auto res = cli.Post("/upload", items);
  15613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15614. EXPECT_EQ(StatusCode::OK_200, res->status);
  15615. }
  15616. TEST(MultipartFormDataTest, MakeFileProvider) {
  15617. // Verify make_file_provider sends a file's contents correctly.
  15618. const std::string file_content(4096, 'Z');
  15619. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15620. {
  15621. std::ofstream ofs(tmp_path, std::ios::binary);
  15622. ofs.write(file_content.data(),
  15623. static_cast<std::streamsize>(file_content.size()));
  15624. }
  15625. auto handled = false;
  15626. Server svr;
  15627. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15628. const ContentReader &content_reader) {
  15629. ASSERT_TRUE(req.is_multipart_form_data());
  15630. std::vector<FormData> items;
  15631. content_reader(
  15632. [&](const FormData &file) {
  15633. items.push_back(file);
  15634. return true;
  15635. },
  15636. [&](const char *data, size_t data_length) {
  15637. items.back().content.append(data, data_length);
  15638. return true;
  15639. });
  15640. ASSERT_EQ(1u, items.size());
  15641. EXPECT_EQ("myfile", items[0].name);
  15642. EXPECT_EQ("data.bin", items[0].filename);
  15643. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15644. EXPECT_EQ(file_content, items[0].content);
  15645. handled = true;
  15646. });
  15647. auto port = svr.bind_to_any_port(HOST);
  15648. auto t = thread([&] { svr.listen_after_bind(); });
  15649. auto se = detail::scope_exit([&] {
  15650. svr.stop();
  15651. t.join();
  15652. ASSERT_FALSE(svr.is_running());
  15653. ASSERT_TRUE(handled);
  15654. std::remove(tmp_path.c_str());
  15655. });
  15656. svr.wait_until_ready();
  15657. FormDataProviderItems providers;
  15658. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15659. "application/octet-stream"));
  15660. Client cli(HOST, port);
  15661. auto res = cli.Post("/upload", {}, {}, providers);
  15662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15663. EXPECT_EQ(StatusCode::OK_200, res->status);
  15664. }
  15665. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15666. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15667. // (100) headers is rejected with a 400 Bad Request response.
  15668. Server svr;
  15669. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15670. res.set_content("ok", "text/plain");
  15671. });
  15672. thread t = thread([&] { svr.listen(HOST, PORT); });
  15673. auto se = detail::scope_exit([&] {
  15674. svr.stop();
  15675. t.join();
  15676. ASSERT_FALSE(svr.is_running());
  15677. });
  15678. svr.wait_until_ready();
  15679. // Build a multipart part with 101 custom headers (exceeding
  15680. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15681. std::stringstream body;
  15682. body << "--simpleboundary\r\n"
  15683. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15684. for (int i = 0; i < 101; i++) {
  15685. body << "X-Custom-Header-" << i << ": value\r\n";
  15686. }
  15687. body << "\r\n"
  15688. << "value1\r\n"
  15689. << "--simpleboundary--\r\n";
  15690. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15691. Client cli(HOST, PORT);
  15692. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15694. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15695. }
  15696. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15697. // A body that never contains the declared boundary must not be accumulated
  15698. // while the parser waits for it. Buffering it would also make every read
  15699. // rescan everything seen so far, which is quadratic in the body size.
  15700. Server svr;
  15701. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15702. res.set_content("ok", "text/plain");
  15703. });
  15704. auto port = svr.bind_to_any_port(HOST);
  15705. thread t = thread([&] { svr.listen_after_bind(); });
  15706. auto se = detail::scope_exit([&] {
  15707. svr.stop();
  15708. t.join();
  15709. ASSERT_FALSE(svr.is_running());
  15710. });
  15711. svr.wait_until_ready();
  15712. Client cli(HOST, port);
  15713. cli.set_read_timeout(60, 0);
  15714. cli.set_write_timeout(60, 0);
  15715. // '-' is the worst case: it matches the first character of the boundary, so
  15716. // every position has to be checked against it.
  15717. auto post_dashes = [&](size_t size) {
  15718. const std::string body(size, '-');
  15719. auto start = std::chrono::steady_clock::now();
  15720. auto res =
  15721. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15722. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15723. std::chrono::steady_clock::now() - start)
  15724. .count();
  15725. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15726. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15727. return ms;
  15728. };
  15729. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15730. // Windows.
  15731. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15732. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15733. // Comparing the two sizes rather than checking an absolute duration keeps
  15734. // this meaningful across build types and CI load, both of which move the
  15735. // absolute numbers by more than an order of magnitude. Four times the bytes
  15736. // costs about four times the time when parsing is linear, and about sixteen
  15737. // times when the body is buffered and rescanned.
  15738. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15739. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15740. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15741. << "ms, which suggests the body is being buffered and rescanned";
  15742. }
  15743. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15744. // A boundary can only be followed by CRLF or by "--", so anything else is
  15745. // malformed no matter what comes next. The parser must say so right away
  15746. // instead of buffering the rest of the declared body.
  15747. Server svr;
  15748. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15749. res.set_content("ok", "text/plain");
  15750. });
  15751. auto port = svr.bind_to_any_port(HOST);
  15752. thread t = thread([&] { svr.listen_after_bind(); });
  15753. auto se = detail::scope_exit([&] {
  15754. svr.stop();
  15755. t.join();
  15756. ASSERT_FALSE(svr.is_running());
  15757. });
  15758. svr.wait_until_ready();
  15759. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15760. // buffers instead of failing would still be waiting for the remaining bytes.
  15761. const std::string body = "--zzzz\r\n"
  15762. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15763. "\r\n"
  15764. "text1"
  15765. "\r\n--zzzzXX";
  15766. const std::string req = "POST /post HTTP/1.1\r\n"
  15767. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15768. "Content-Length: 1048576\r\n"
  15769. "\r\n" +
  15770. body;
  15771. std::string response;
  15772. ASSERT_TRUE(send_request(3, req, &response, port));
  15773. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15774. EXPECT_EQ("400", response.substr(9, 3));
  15775. }
  15776. // Posts a multipart body split into two writes, so that the server sees the
  15777. // split at whatever offset the caller chose, and expects the single "text1"
  15778. // field to come through.
  15779. static void expect_split_multipart_ok(const std::string &body1,
  15780. const std::string &body2) {
  15781. auto handled = false;
  15782. Server svr;
  15783. svr.Post("/post", [&](const Request &req, Response &) {
  15784. EXPECT_EQ(1u, req.form.fields.size());
  15785. EXPECT_EQ("text1", req.form.get_field("text1"));
  15786. handled = true;
  15787. });
  15788. auto port = svr.bind_to_any_port(HOST);
  15789. thread t = thread([&] { svr.listen_after_bind(); });
  15790. auto se = detail::scope_exit([&] {
  15791. svr.stop();
  15792. t.join();
  15793. ASSERT_FALSE(svr.is_running());
  15794. ASSERT_TRUE(handled);
  15795. });
  15796. svr.wait_until_ready();
  15797. // "Connection: close" makes the server close once it has answered, so the
  15798. // response drain ends immediately instead of idling until the read timeout.
  15799. const std::string head =
  15800. "POST /post HTTP/1.1\r\n"
  15801. "Host: localhost\r\n"
  15802. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15803. "Connection: close\r\n"
  15804. "Content-Length: " +
  15805. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15806. std::string response;
  15807. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15808. ASSERT_GE(response.size(), 12u) << "no response";
  15809. EXPECT_EQ("200", response.substr(9, 3));
  15810. }
  15811. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15812. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15813. // ignored, including when it does not arrive in the same read as the
  15814. // close-delimiter itself.
  15815. expect_split_multipart_ok("--zzzz\r\n"
  15816. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15817. "\r\n"
  15818. "text1"
  15819. "\r\n--zzzz--",
  15820. "\r\nthis epilogue must be ignored\r\n");
  15821. }
  15822. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15823. // The initial boundary may be preceded by a preamble of any length and may
  15824. // straddle a read boundary. Discarding data while waiting for it must not
  15825. // throw away a partial boundary sitting at the end of the buffer.
  15826. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15827. "zz\r\n"
  15828. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15829. "\r\n"
  15830. "text1"
  15831. "\r\n--zzzz--\r\n");
  15832. }
  15833. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15834. // The received boundary was only checked for being non-empty, so it could be
  15835. // as long as a header is allowed to be. The parser scans the body for
  15836. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15837. // costs a nearly full comparison at nearly every position, making the
  15838. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15839. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15840. Server svr;
  15841. svr.Post("/post", [](const Request &req, Response &res) {
  15842. EXPECT_EQ(1u, req.form.fields.size());
  15843. EXPECT_EQ("text1", req.form.get_field("text1"));
  15844. res.set_content("ok", "text/plain");
  15845. });
  15846. auto port = svr.bind_to_any_port(HOST);
  15847. thread t = thread([&] { svr.listen_after_bind(); });
  15848. auto se = detail::scope_exit([&] {
  15849. svr.stop();
  15850. t.join();
  15851. ASSERT_FALSE(svr.is_running());
  15852. });
  15853. svr.wait_until_ready();
  15854. Client cli(HOST, port);
  15855. auto post_with_boundary_of_length = [&](size_t len) {
  15856. const std::string boundary(len, 'a');
  15857. const std::string body =
  15858. "--" + boundary +
  15859. "\r\n"
  15860. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15861. "\r\n"
  15862. "text1"
  15863. "\r\n--" +
  15864. boundary + "--\r\n";
  15865. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15866. };
  15867. auto res = post_with_boundary_of_length(70);
  15868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15869. EXPECT_EQ(StatusCode::OK_200, res->status);
  15870. res = post_with_boundary_of_length(71);
  15871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15872. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15873. }
  15874. TEST(MakeFileBodyTest, Basic) {
  15875. const std::string file_content(4096, 'Z');
  15876. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15877. {
  15878. std::ofstream ofs(tmp_path, std::ios::binary);
  15879. ofs.write(file_content.data(),
  15880. static_cast<std::streamsize>(file_content.size()));
  15881. }
  15882. auto handled = false;
  15883. Server svr;
  15884. svr.Post("/upload", [&](const Request &req, Response &res) {
  15885. EXPECT_EQ(file_content, req.body);
  15886. handled = true;
  15887. res.status = StatusCode::OK_200;
  15888. });
  15889. auto port = svr.bind_to_any_port(HOST);
  15890. auto t = thread([&] { svr.listen_after_bind(); });
  15891. auto se = detail::scope_exit([&] {
  15892. svr.stop();
  15893. t.join();
  15894. ASSERT_FALSE(svr.is_running());
  15895. ASSERT_TRUE(handled);
  15896. std::remove(tmp_path.c_str());
  15897. });
  15898. svr.wait_until_ready();
  15899. auto fb = make_file_body(tmp_path);
  15900. ASSERT_GT(fb.first, 0u);
  15901. Client cli(HOST, port);
  15902. auto res =
  15903. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15905. EXPECT_EQ(StatusCode::OK_200, res->status);
  15906. }
  15907. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15908. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15909. {
  15910. std::ofstream ofs(path, std::ios::binary);
  15911. const std::string content(100, 'A');
  15912. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15913. }
  15914. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15915. auto body = make_file_body(path);
  15916. ASSERT_EQ(100u, body.first);
  15917. ASSERT_TRUE(static_cast<bool>(body.second));
  15918. // Rewritten shorter after its length was measured - and, on a server, after
  15919. // that length has already gone out as Content-Length.
  15920. {
  15921. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15922. const std::string content(10, 'A');
  15923. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15924. }
  15925. std::string written;
  15926. DataSink sink;
  15927. sink.write = [&](const char *d, size_t l) {
  15928. written.append(d, l);
  15929. return true;
  15930. };
  15931. // The provider has to report failure. write_content_with_progress() advances
  15932. // its offset only by what was written, so a provider that returns true
  15933. // without completing the length it promised is called again straight away,
  15934. // and again.
  15935. EXPECT_FALSE(body.second(0, body.first, sink));
  15936. EXPECT_EQ(std::string(10, 'A'), written);
  15937. }
  15938. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15939. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15940. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15941. {
  15942. std::ofstream ofs(path, std::ios::binary);
  15943. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15944. }
  15945. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15946. auto body = make_file_body(path);
  15947. ASSERT_EQ(content.size(), body.first);
  15948. ASSERT_TRUE(static_cast<bool>(body.second));
  15949. std::string written;
  15950. DataSink sink;
  15951. sink.write = [&](const char *d, size_t l) {
  15952. written.append(d, l);
  15953. return true;
  15954. };
  15955. EXPECT_TRUE(body.second(0, body.first, sink));
  15956. EXPECT_EQ(content, written);
  15957. }
  15958. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15959. static constexpr unsigned int number_of_tasks{1000000};
  15960. std::atomic_uint count{0};
  15961. std::unique_ptr<TaskQueue> task_queue{
  15962. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15963. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15964. auto queued = task_queue->enqueue(
  15965. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15966. EXPECT_TRUE(queued);
  15967. }
  15968. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15969. task_queue->shutdown();
  15970. #else
  15971. EXPECT_NO_THROW(task_queue->shutdown());
  15972. #endif
  15973. EXPECT_EQ(number_of_tasks, count.load());
  15974. }
  15975. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15976. static constexpr unsigned int number_of_tasks{1000000};
  15977. static constexpr unsigned int qlimit{2};
  15978. unsigned int queued_count{0};
  15979. std::atomic_uint count{0};
  15980. std::unique_ptr<TaskQueue> task_queue{
  15981. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15982. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15983. if (task_queue->enqueue(
  15984. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15985. queued_count++;
  15986. }
  15987. }
  15988. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15989. task_queue->shutdown();
  15990. #else
  15991. EXPECT_NO_THROW(task_queue->shutdown());
  15992. #endif
  15993. EXPECT_EQ(queued_count, count.load());
  15994. EXPECT_TRUE(queued_count <= number_of_tasks);
  15995. EXPECT_TRUE(queued_count >= qlimit);
  15996. }
  15997. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15998. // Use a short idle timeout so a dynamic thread spawns, times out and
  15999. // exits during the test, and the pool keeps working afterwards.
  16000. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16001. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16002. /*idle_timeout_sec=*/1}};
  16003. std::atomic_uint count{0};
  16004. std::condition_variable cv;
  16005. std::mutex mtx;
  16006. bool release = false;
  16007. // Block the base thread so the second task spawns a dynamic thread.
  16008. EXPECT_TRUE(task_queue->enqueue([&] {
  16009. std::unique_lock<std::mutex> lock(mtx);
  16010. while (!release) {
  16011. cv.wait(lock);
  16012. }
  16013. count++;
  16014. }));
  16015. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16016. // Let the dynamic thread finish its task and exceed the idle timeout.
  16017. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16018. {
  16019. std::unique_lock<std::mutex> lock(mtx);
  16020. release = true;
  16021. }
  16022. cv.notify_all();
  16023. // The pool must still accept and run tasks after the dynamic thread exited.
  16024. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16025. task_queue->shutdown();
  16026. EXPECT_EQ(3u, count.load());
  16027. }
  16028. TEST(TaskQueueTest, MaxQueuedRequests) {
  16029. static constexpr unsigned int qlimit{3};
  16030. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16031. std::condition_variable sem_cv;
  16032. std::mutex sem_mtx;
  16033. int credits = 0;
  16034. bool queued;
  16035. /* Fill up the queue with tasks that will block until we give them credits to
  16036. * complete. */
  16037. for (unsigned int n = 0; n <= qlimit;) {
  16038. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16039. std::unique_lock<std::mutex> lock(sem_mtx);
  16040. while (credits <= 0) {
  16041. sem_cv.wait(lock);
  16042. }
  16043. /* Consume the credit and signal the test code if they are all gone. */
  16044. if (--credits == 0) { sem_cv.notify_one(); }
  16045. });
  16046. if (n < qlimit) {
  16047. /* The first qlimit enqueues must succeed. */
  16048. EXPECT_TRUE(queued);
  16049. } else {
  16050. /* The last one will succeed only when the worker thread
  16051. * starts and dequeues the first blocking task. Although
  16052. * not necessary for the correctness of this test, we sleep for
  16053. * a short while to avoid busy waiting. */
  16054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16055. }
  16056. if (queued) { n++; }
  16057. }
  16058. /* Further enqueues must fail since the queue is full. */
  16059. for (auto i = 0; i < 4; i++) {
  16060. queued = task_queue->enqueue([] {});
  16061. EXPECT_FALSE(queued);
  16062. }
  16063. /* Give the credits to allow the previous tasks to complete. */
  16064. {
  16065. std::unique_lock<std::mutex> lock(sem_mtx);
  16066. credits += qlimit + 1;
  16067. }
  16068. sem_cv.notify_all();
  16069. /* Wait for all the credits to be consumed. */
  16070. {
  16071. std::unique_lock<std::mutex> lock(sem_mtx);
  16072. while (credits > 0) {
  16073. sem_cv.wait(lock);
  16074. }
  16075. }
  16076. /* Check that we are able again to enqueue at least qlimit tasks. */
  16077. for (unsigned int i = 0; i < qlimit; i++) {
  16078. queued = task_queue->enqueue([] {});
  16079. EXPECT_TRUE(queued);
  16080. }
  16081. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16082. task_queue->shutdown();
  16083. #else
  16084. EXPECT_NO_THROW(task_queue->shutdown());
  16085. #endif
  16086. }
  16087. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16088. Server svr;
  16089. std::string method;
  16090. std::string body;
  16091. auto has_content_length = false;
  16092. auto has_transfer_encoding = false;
  16093. std::atomic<int> bad_requests{0};
  16094. // Leftover body bytes get parsed as a malformed request and answered with
  16095. // 400
  16096. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16097. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16098. });
  16099. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16100. res.set_redirect("/down", StatusCode::SeeOther_303);
  16101. });
  16102. svr.Get("/down", [&](const Request &req, Response &res) {
  16103. method = req.method;
  16104. body = req.body;
  16105. has_content_length = req.has_header("Content-Length");
  16106. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16107. res.set_content("ok", "text/plain");
  16108. });
  16109. auto port = svr.bind_to_any_port(HOST);
  16110. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16111. auto se = detail::scope_exit([&] {
  16112. svr.stop();
  16113. thread.join();
  16114. ASSERT_FALSE(svr.is_running());
  16115. });
  16116. svr.wait_until_ready();
  16117. const std::string payload = "SECRET-BODY";
  16118. auto check = [&](Client &cli, const Result &res) {
  16119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16120. EXPECT_EQ(StatusCode::OK_200, res->status);
  16121. EXPECT_EQ("ok", res->body);
  16122. EXPECT_EQ("GET", method);
  16123. EXPECT_TRUE(body.empty());
  16124. EXPECT_FALSE(has_content_length);
  16125. EXPECT_FALSE(has_transfer_encoding);
  16126. // Nothing of the original body may be left on the connection
  16127. auto res2 = cli.Get("/down");
  16128. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16129. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16130. EXPECT_EQ("ok", res2->body);
  16131. EXPECT_EQ(0, bad_requests);
  16132. };
  16133. // With content length
  16134. {
  16135. Client cli(HOST, port);
  16136. cli.set_keep_alive(true);
  16137. cli.set_follow_location(true);
  16138. auto res = cli.Post(
  16139. "/up", payload.size(),
  16140. [&](size_t offset, size_t length, DataSink &sink) {
  16141. return sink.write(payload.data() + offset, length);
  16142. },
  16143. "text/plain");
  16144. check(cli, res);
  16145. }
  16146. // Without content length (chunked)
  16147. {
  16148. Client cli(HOST, port);
  16149. cli.set_keep_alive(true);
  16150. cli.set_follow_location(true);
  16151. auto res = cli.Post(
  16152. "/up",
  16153. [&](size_t /*offset*/, DataSink &sink) {
  16154. sink.write(payload.data(), payload.size());
  16155. sink.done();
  16156. return true;
  16157. },
  16158. "text/plain");
  16159. check(cli, res);
  16160. }
  16161. }
  16162. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16163. Server svr;
  16164. std::string target;
  16165. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16166. // Echo the still-encoded name back in the Location
  16167. const std::string prefix = "/start/";
  16168. res.status = StatusCode::Found_302;
  16169. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16170. });
  16171. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16172. target = req.target;
  16173. res.set_content("ok", "text/plain");
  16174. });
  16175. auto port = svr.bind_to_any_port(HOST);
  16176. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16177. auto se = detail::scope_exit([&] {
  16178. svr.stop();
  16179. thread.join();
  16180. ASSERT_FALSE(svr.is_running());
  16181. });
  16182. svr.wait_until_ready();
  16183. // Decoding the Location path would turn the first four into a path
  16184. // separator, a query delimiter, a fragment delimiter and a different
  16185. // percent-encoded octet. The rest must keep reaching the server as they are.
  16186. const std::vector<std::string> names = {
  16187. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16188. };
  16189. for (auto path_encode : {true, false}) {
  16190. Client cli(HOST, port);
  16191. cli.set_follow_location(true);
  16192. cli.set_path_encode(path_encode);
  16193. for (const auto &name : names) {
  16194. target.clear();
  16195. auto res = cli.Get("/start/" + name);
  16196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16197. EXPECT_EQ(StatusCode::OK_200, res->status);
  16198. EXPECT_EQ("/dest/" + name, target);
  16199. }
  16200. }
  16201. }
  16202. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16203. Server svr;
  16204. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16205. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16206. });
  16207. svr.Get("/hello", [](const Request &req, Response &res) {
  16208. res.set_content(req.get_param_value("key"), "text/plain");
  16209. });
  16210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16211. auto se = detail::scope_exit([&] {
  16212. svr.stop();
  16213. thread.join();
  16214. ASSERT_FALSE(svr.is_running());
  16215. });
  16216. svr.wait_until_ready();
  16217. {
  16218. Client cli(HOST, PORT);
  16219. cli.set_follow_location(true);
  16220. auto res = cli.Get("/");
  16221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16222. EXPECT_EQ(StatusCode::OK_200, res->status);
  16223. EXPECT_EQ("val&key2=val2", res->body);
  16224. }
  16225. }
  16226. #endif
  16227. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16228. Server svr;
  16229. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16230. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16231. });
  16232. svr.Get("/hello", [](const Request &req, Response &res) {
  16233. res.set_content(req.get_param_value("key"), "text/plain");
  16234. });
  16235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16236. auto se = detail::scope_exit([&] {
  16237. svr.stop();
  16238. thread.join();
  16239. ASSERT_FALSE(svr.is_running());
  16240. });
  16241. svr.wait_until_ready();
  16242. {
  16243. Client cli(HOST, PORT);
  16244. cli.set_follow_location(true);
  16245. auto res = cli.Get("/");
  16246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16247. EXPECT_EQ(StatusCode::OK_200, res->status);
  16248. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16249. }
  16250. }
  16251. TEST(RedirectTest, RedirectWithPlusInPath) {
  16252. Server svr;
  16253. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16254. res.set_redirect("/a+b");
  16255. });
  16256. // Route pattern uses regex; escape + as \\+
  16257. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16258. res.set_content(req.path, "text/plain");
  16259. });
  16260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16261. auto se = detail::scope_exit([&] {
  16262. svr.stop();
  16263. thread.join();
  16264. ASSERT_FALSE(svr.is_running());
  16265. });
  16266. svr.wait_until_ready();
  16267. {
  16268. Client cli(HOST, PORT);
  16269. cli.set_follow_location(true);
  16270. auto res = cli.Get("/");
  16271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16272. EXPECT_EQ(StatusCode::OK_200, res->status);
  16273. EXPECT_EQ("/a+b", res->body);
  16274. }
  16275. }
  16276. TEST(RedirectTest, ResolveRelativeLocation) {
  16277. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16278. const std::vector<std::pair<std::string, std::string>> cases = {
  16279. {"g", "/b/c/g"},
  16280. {"./g", "/b/c/g"},
  16281. {"g/", "/b/c/g/"},
  16282. {"?y", "/b/c/d;p?y"},
  16283. {"g?y", "/b/c/g?y"},
  16284. {"#s", "/b/c/d;p?q#s"},
  16285. {"g#s", "/b/c/g#s"},
  16286. {"g?y#s", "/b/c/g?y#s"},
  16287. {";x", "/b/c/;x"},
  16288. {"g;x", "/b/c/g;x"},
  16289. {".", "/b/c/"},
  16290. {"./", "/b/c/"},
  16291. {"..", "/b/"},
  16292. {"../", "/b/"},
  16293. {"../g", "/b/g"},
  16294. {"../..", "/"},
  16295. {"../../", "/"},
  16296. {"../../g", "/g"},
  16297. {"../../../g", "/g"},
  16298. {"g.", "/b/c/g."},
  16299. {".g", "/b/c/.g"},
  16300. {"g..", "/b/c/g.."},
  16301. {"..g", "/b/c/..g"},
  16302. {"./../g", "/b/g"},
  16303. {"./g/.", "/b/c/g/"},
  16304. {"g/./h", "/b/c/g/h"},
  16305. {"g/../h", "/b/c/h"},
  16306. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16307. {"g;x=1/../y", "/b/c/y"},
  16308. {"g?y/./x", "/b/c/g?y/./x"},
  16309. {"g#s/../x", "/b/c/g#s/../x"},
  16310. // Not relative-path references, so left for parse_url.
  16311. {"/g", "/g"},
  16312. {"//g", "//g"},
  16313. {"http://g/x", "http://g/x"},
  16314. {"g:h", "g:h"},
  16315. };
  16316. for (const auto &c : cases) {
  16317. EXPECT_EQ(c.second,
  16318. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16319. << c.first;
  16320. }
  16321. }
  16322. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16323. Server svr;
  16324. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16325. res.set_redirect(req.get_param_value("to"));
  16326. });
  16327. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16328. res.set_content(req.target, "text/plain");
  16329. });
  16330. svr.Get("/other", [](const Request &req, Response &res) {
  16331. res.set_content(req.target, "text/plain");
  16332. });
  16333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16334. auto se = detail::scope_exit([&] {
  16335. svr.stop();
  16336. thread.join();
  16337. ASSERT_FALSE(svr.is_running());
  16338. });
  16339. svr.wait_until_ready();
  16340. const std::vector<std::pair<std::string, std::string>> cases = {
  16341. {"next", "/dir/next"},
  16342. {"./next?x=1", "/dir/next?x=1"},
  16343. {"../other", "/other"},
  16344. };
  16345. for (const auto &c : cases) {
  16346. Client cli(HOST, PORT);
  16347. cli.set_follow_location(true);
  16348. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16349. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16350. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16351. EXPECT_EQ(c.second, res->body) << c.first;
  16352. }
  16353. }
  16354. #ifdef CPPHTTPLIB_SSL_ENABLED
  16355. TEST(RedirectTest, Issue2185_Online) {
  16356. SSLClient client("github.com");
  16357. client.set_follow_location(true);
  16358. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16359. "Coollab-Windows.zip");
  16360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16361. EXPECT_EQ(StatusCode::OK_200, res->status);
  16362. EXPECT_EQ(9920427U, res->body.size());
  16363. }
  16364. #endif
  16365. TEST(VulnerabilityTest, CRLFInjection) {
  16366. Server svr;
  16367. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16368. res.set_content("Hello 1", "text/plain");
  16369. });
  16370. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16371. res.set_content("Hello 2", "text/plain");
  16372. });
  16373. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16374. res.set_content("Hello 3", "text/plain");
  16375. });
  16376. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16377. res.set_content("Hello 4", "text/plain");
  16378. });
  16379. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16380. for (const auto &x : req.headers) {
  16381. auto key = x.first;
  16382. EXPECT_STRNE("evil", key.c_str());
  16383. }
  16384. });
  16385. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16386. auto se = detail::scope_exit([&] {
  16387. svr.stop();
  16388. thread.join();
  16389. ASSERT_FALSE(svr.is_running());
  16390. });
  16391. svr.wait_until_ready();
  16392. {
  16393. Client cli(HOST, PORT);
  16394. cli.Post("/test1", "A=B",
  16395. "application/x-www-form-urlencoded\r\nevil: hello1");
  16396. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16397. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16398. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16399. }
  16400. }
  16401. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16402. auto server_thread = std::thread([] {
  16403. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16404. default_socket_options(srv);
  16405. sockaddr_in addr{};
  16406. addr.sin_family = AF_INET;
  16407. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16408. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16409. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16410. ::listen(srv, 1);
  16411. sockaddr_in cli_addr{};
  16412. socklen_t cli_len = sizeof(cli_addr);
  16413. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16414. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16415. std::string buf_all;
  16416. char buf[2048];
  16417. ssize_t n;
  16418. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16419. buf_all.append(buf, static_cast<size_t>(n));
  16420. size_t pos;
  16421. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16422. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16423. auto e = request_block.find("\r\n");
  16424. if (e != std::string::npos) {
  16425. auto request_line = request_block.substr(0, e);
  16426. std::string msg =
  16427. "CRLF injection detected in request line: '" + request_line + "'";
  16428. EXPECT_FALSE(true) << msg;
  16429. }
  16430. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16431. ::send(cli,
  16432. #ifdef _WIN32
  16433. static_cast<const char *>(resp.c_str()),
  16434. static_cast<int>(resp.size()),
  16435. #else
  16436. resp.c_str(), resp.size(),
  16437. #endif
  16438. 0);
  16439. buf_all.erase(0, pos + 4);
  16440. }
  16441. }
  16442. detail::close_socket(cli);
  16443. detail::close_socket(srv);
  16444. });
  16445. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16446. auto cli = Client("127.0.0.1", PORT + 1);
  16447. auto headers = Headers{
  16448. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16449. {"Connection", "keep-alive"}};
  16450. auto res = cli.Get("/hi", headers);
  16451. EXPECT_FALSE(res);
  16452. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16453. server_thread.join();
  16454. }
  16455. // A request rejected before any byte reaches the socket must fail right away
  16456. // instead of waiting for a response the server will never send.
  16457. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16458. // The kernel completes the TCP handshake from the listen backlog, so the
  16459. // client connects, but nothing ever reads, responds or closes.
  16460. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16461. default_socket_options(srv);
  16462. sockaddr_in addr{};
  16463. addr.sin_family = AF_INET;
  16464. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16465. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16466. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16467. ASSERT_EQ(0, ::listen(srv, 8));
  16468. auto cli = Client("127.0.0.1", PORT + 1);
  16469. cli.set_read_timeout(10, 0);
  16470. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16471. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16472. std::chrono::steady_clock::now() - start)
  16473. .count();
  16474. };
  16475. {
  16476. Request req;
  16477. req.method = "GE T";
  16478. req.path = "/";
  16479. auto start = std::chrono::steady_clock::now();
  16480. auto res = cli.send(req);
  16481. EXPECT_FALSE(res);
  16482. EXPECT_EQ(Error::Write, res.error());
  16483. EXPECT_LT(elapsed_ms(start), 1000);
  16484. }
  16485. {
  16486. auto start = std::chrono::steady_clock::now();
  16487. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16488. EXPECT_FALSE(res);
  16489. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16490. EXPECT_LT(elapsed_ms(start), 1000);
  16491. }
  16492. EXPECT_FALSE(cli.is_socket_open());
  16493. detail::close_socket(srv);
  16494. }
  16495. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16496. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16497. default_socket_options(srv);
  16498. sockaddr_in addr{};
  16499. addr.sin_family = AF_INET;
  16500. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16501. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16502. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16503. ASSERT_EQ(0, ::listen(srv, 1));
  16504. std::string received;
  16505. auto server_thread = std::thread([&] {
  16506. auto sock = ::accept(srv, nullptr, nullptr);
  16507. if (sock == INVALID_SOCKET) { return; }
  16508. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16509. char buf[2048];
  16510. ssize_t n;
  16511. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16512. received.append(buf, static_cast<size_t>(n));
  16513. }
  16514. detail::close_socket(sock);
  16515. });
  16516. {
  16517. auto cli = Client("127.0.0.1", PORT + 1);
  16518. // "Z" sorts after the default headers, so writing straight to the socket
  16519. // would have sent the request line and those headers before the rejection.
  16520. auto handle =
  16521. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16522. EXPECT_FALSE(handle.is_valid());
  16523. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16524. }
  16525. server_thread.join();
  16526. detail::close_socket(srv);
  16527. EXPECT_TRUE(received.empty()) << received;
  16528. }
  16529. TEST(PathParamsTest, StaticMatch) {
  16530. const auto pattern = "/users/all";
  16531. detail::PathParamsMatcher matcher(pattern);
  16532. Request request;
  16533. request.path = "/users/all";
  16534. ASSERT_TRUE(matcher.match(request));
  16535. std::unordered_map<std::string, std::string> expected_params = {};
  16536. EXPECT_EQ(request.path_params, expected_params);
  16537. }
  16538. TEST(PathParamsTest, StaticMismatch) {
  16539. const auto pattern = "/users/all";
  16540. detail::PathParamsMatcher matcher(pattern);
  16541. Request request;
  16542. request.path = "/users/1";
  16543. ASSERT_FALSE(matcher.match(request));
  16544. }
  16545. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16546. const auto pattern = "/users/:id/subscriptions";
  16547. detail::PathParamsMatcher matcher(pattern);
  16548. Request request;
  16549. request.path = "/users/42/subscriptions";
  16550. ASSERT_TRUE(matcher.match(request));
  16551. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16552. EXPECT_EQ(request.path_params, expected_params);
  16553. }
  16554. TEST(PathParamsTest, SingleParamInTheEnd) {
  16555. const auto pattern = "/users/:id";
  16556. detail::PathParamsMatcher matcher(pattern);
  16557. Request request;
  16558. request.path = "/users/24";
  16559. ASSERT_TRUE(matcher.match(request));
  16560. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16561. EXPECT_EQ(request.path_params, expected_params);
  16562. }
  16563. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16564. const auto pattern = "/users/:id/";
  16565. detail::PathParamsMatcher matcher(pattern);
  16566. Request request;
  16567. request.path = "/users/42/";
  16568. ASSERT_TRUE(matcher.match(request));
  16569. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16570. EXPECT_EQ(request.path_params, expected_params);
  16571. }
  16572. TEST(PathParamsTest, EmptyParam) {
  16573. const auto pattern = "/users/:id/";
  16574. detail::PathParamsMatcher matcher(pattern);
  16575. Request request;
  16576. request.path = "/users//";
  16577. ASSERT_TRUE(matcher.match(request));
  16578. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16579. EXPECT_EQ(request.path_params, expected_params);
  16580. }
  16581. TEST(PathParamsTest, FragmentMismatch) {
  16582. const auto pattern = "/users/:id/";
  16583. detail::PathParamsMatcher matcher(pattern);
  16584. Request request;
  16585. request.path = "/admins/24/";
  16586. ASSERT_FALSE(matcher.match(request));
  16587. }
  16588. TEST(PathParamsTest, ExtraFragments) {
  16589. const auto pattern = "/users/:id";
  16590. detail::PathParamsMatcher matcher(pattern);
  16591. Request request;
  16592. request.path = "/users/42/subscriptions";
  16593. ASSERT_FALSE(matcher.match(request));
  16594. }
  16595. TEST(PathParamsTest, MissingTrailingParam) {
  16596. const auto pattern = "/users/:id";
  16597. detail::PathParamsMatcher matcher(pattern);
  16598. Request request;
  16599. request.path = "/users";
  16600. ASSERT_FALSE(matcher.match(request));
  16601. }
  16602. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16603. const auto pattern = "/users/:id/subscriptions";
  16604. detail::PathParamsMatcher matcher(pattern);
  16605. Request request;
  16606. request.path = "/users/subscriptions";
  16607. ASSERT_FALSE(matcher.match(request));
  16608. }
  16609. TEST(PathParamsTest, MultipleParams) {
  16610. const auto pattern = "/users/:userid/subscriptions/:subid";
  16611. detail::PathParamsMatcher matcher(pattern);
  16612. Request request;
  16613. request.path = "/users/42/subscriptions/2";
  16614. ASSERT_TRUE(matcher.match(request));
  16615. std::unordered_map<std::string, std::string> expected_params = {
  16616. {"userid", "42"}, {"subid", "2"}};
  16617. EXPECT_EQ(request.path_params, expected_params);
  16618. }
  16619. TEST(PathParamsTest, SequenceOfParams) {
  16620. const auto pattern = "/values/:x/:y/:z";
  16621. detail::PathParamsMatcher matcher(pattern);
  16622. Request request;
  16623. request.path = "/values/1/2/3";
  16624. ASSERT_TRUE(matcher.match(request));
  16625. std::unordered_map<std::string, std::string> expected_params = {
  16626. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16627. EXPECT_EQ(request.path_params, expected_params);
  16628. }
  16629. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16630. const auto pattern = "/prefix:suffix";
  16631. detail::PathParamsMatcher matcher(pattern);
  16632. Request request;
  16633. request.path = "/prefix:suffix";
  16634. ASSERT_TRUE(matcher.match(request));
  16635. const std::unordered_map<std::string, std::string> expected_params = {};
  16636. EXPECT_EQ(request.path_params, expected_params);
  16637. }
  16638. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16639. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16640. // calling thread's stack on a long enough path for a quantified pattern;
  16641. // RegexMatcher must refuse to run regex matching on paths beyond
  16642. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16643. detail::RegexMatcher matcher("/files/(.*)");
  16644. Request within_limit;
  16645. within_limit.path = "/files/" + std::string(10, 'A');
  16646. EXPECT_TRUE(matcher.match(within_limit));
  16647. Request over_limit;
  16648. over_limit.path =
  16649. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16650. EXPECT_FALSE(matcher.match(over_limit));
  16651. }
  16652. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16653. Server svr;
  16654. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16655. res.set_content("ok", "text/plain");
  16656. });
  16657. auto port = svr.bind_to_any_port(HOST);
  16658. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16659. auto se = detail::scope_exit([&] {
  16660. svr.stop();
  16661. thread.join();
  16662. ASSERT_FALSE(svr.is_running());
  16663. });
  16664. svr.wait_until_ready();
  16665. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16666. // request URI limit; this used to be able to crash the process.
  16667. std::string path =
  16668. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16669. std::string req = "GET " + path +
  16670. " HTTP/1.1\r\n"
  16671. "Host: " +
  16672. std::string(HOST) + ":" + std::to_string(port) +
  16673. "\r\n"
  16674. "Connection: close\r\n"
  16675. "\r\n";
  16676. std::string response;
  16677. ASSERT_TRUE(send_request(5, req, &response, port));
  16678. EXPECT_NE(std::string::npos, response.find("404"));
  16679. }
  16680. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16681. Server svr;
  16682. auto handler = [](const Request & /*req*/, Response &res) {
  16683. res.set_content("hit", "text/plain");
  16684. };
  16685. // No regex metacharacter, so this one is compared literally
  16686. svr.Get("/literal/route", handler);
  16687. // '.' is a regex metacharacter, so this one must keep regex semantics
  16688. svr.Get("/a.c", handler);
  16689. auto port = svr.bind_to_any_port(HOST);
  16690. std::thread t([&]() { svr.listen_after_bind(); });
  16691. auto se = detail::scope_exit([&] {
  16692. svr.stop();
  16693. t.join();
  16694. ASSERT_FALSE(svr.is_running());
  16695. });
  16696. svr.wait_until_ready();
  16697. Client cli(HOST, port);
  16698. struct {
  16699. const char *path;
  16700. int status;
  16701. } cases[] = {
  16702. {"/literal/route", StatusCode::OK_200},
  16703. {"/literal/routes", StatusCode::NotFound_404},
  16704. {"/literal/rout", StatusCode::NotFound_404},
  16705. {"/abc", StatusCode::OK_200},
  16706. {"/a.c", StatusCode::OK_200},
  16707. };
  16708. for (const auto &x : cases) {
  16709. auto res = cli.Get(x.path);
  16710. ASSERT_TRUE(res) << x.path;
  16711. EXPECT_EQ(x.status, res->status) << x.path;
  16712. }
  16713. }
  16714. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16715. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16716. // from exhausting the stack, so it must only constrain routes that actually
  16717. // run a regular expression. A literal route is matched by comparison and
  16718. // stays usable at any length.
  16719. Server svr;
  16720. const std::string pattern =
  16721. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16722. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16723. res.set_content("hit", "text/plain");
  16724. });
  16725. auto port = svr.bind_to_any_port(HOST);
  16726. std::thread t([&]() { svr.listen_after_bind(); });
  16727. auto se = detail::scope_exit([&] {
  16728. svr.stop();
  16729. t.join();
  16730. ASSERT_FALSE(svr.is_running());
  16731. });
  16732. svr.wait_until_ready();
  16733. Client cli(HOST, port);
  16734. auto res = cli.Get(pattern);
  16735. ASSERT_TRUE(res);
  16736. EXPECT_EQ(StatusCode::OK_200, res->status);
  16737. }
  16738. TEST(ParseUrlTest, VariousPatterns) {
  16739. {
  16740. detail::UrlComponents uc;
  16741. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16742. EXPECT_EQ("http", uc.scheme);
  16743. EXPECT_EQ("example.com", uc.host);
  16744. EXPECT_EQ("8080", uc.port);
  16745. EXPECT_EQ("/path", uc.path);
  16746. EXPECT_EQ("?q=1", uc.query);
  16747. }
  16748. {
  16749. detail::UrlComponents uc;
  16750. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16751. EXPECT_EQ("https", uc.scheme);
  16752. EXPECT_EQ("example.com", uc.host);
  16753. EXPECT_TRUE(uc.port.empty());
  16754. EXPECT_EQ("/path", uc.path);
  16755. }
  16756. {
  16757. detail::UrlComponents uc;
  16758. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16759. EXPECT_EQ("::1", uc.host);
  16760. EXPECT_EQ("8080", uc.port);
  16761. EXPECT_EQ("/path", uc.path);
  16762. }
  16763. {
  16764. detail::UrlComponents uc;
  16765. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16766. }
  16767. {
  16768. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16769. // the path while the connection still targets the bracketed host.
  16770. detail::UrlComponents uc;
  16771. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16772. }
  16773. {
  16774. detail::UrlComponents uc;
  16775. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16776. }
  16777. {
  16778. detail::UrlComponents uc;
  16779. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16780. EXPECT_EQ("::1", uc.host);
  16781. EXPECT_TRUE(uc.port.empty());
  16782. EXPECT_EQ("/path", uc.path);
  16783. }
  16784. {
  16785. detail::UrlComponents uc;
  16786. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16787. EXPECT_TRUE(uc.scheme.empty());
  16788. EXPECT_EQ("example.com", uc.host);
  16789. EXPECT_EQ("/path", uc.path);
  16790. EXPECT_EQ("?q=1", uc.query);
  16791. }
  16792. {
  16793. detail::UrlComponents uc;
  16794. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16795. EXPECT_TRUE(uc.host.empty());
  16796. EXPECT_EQ("/path", uc.path);
  16797. EXPECT_EQ("?q=1", uc.query);
  16798. }
  16799. {
  16800. detail::UrlComponents uc;
  16801. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16802. EXPECT_EQ("example.com", uc.host);
  16803. EXPECT_EQ("8080", uc.port);
  16804. }
  16805. {
  16806. // Unix socket path — must not be parsed as host
  16807. detail::UrlComponents uc;
  16808. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16809. EXPECT_TRUE(uc.host.empty());
  16810. }
  16811. {
  16812. detail::UrlComponents uc;
  16813. ASSERT_TRUE(detail::parse_url("", uc));
  16814. EXPECT_TRUE(uc.host.empty());
  16815. EXPECT_TRUE(uc.path.empty());
  16816. }
  16817. {
  16818. detail::UrlComponents uc;
  16819. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16820. }
  16821. {
  16822. detail::UrlComponents uc;
  16823. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16824. }
  16825. {
  16826. // Accepted by parse_url; callers restrict to http/https
  16827. detail::UrlComponents uc;
  16828. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16829. EXPECT_EQ("ftp", uc.scheme);
  16830. }
  16831. {
  16832. detail::UrlComponents uc;
  16833. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16834. }
  16835. {
  16836. detail::UrlComponents uc;
  16837. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16838. }
  16839. }
  16840. TEST(ParseUrlTest, FragmentHandling) {
  16841. {
  16842. detail::UrlComponents uc;
  16843. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16844. EXPECT_EQ("/path", uc.path);
  16845. EXPECT_TRUE(uc.query.empty());
  16846. }
  16847. {
  16848. detail::UrlComponents uc;
  16849. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16850. EXPECT_TRUE(uc.path.empty());
  16851. EXPECT_TRUE(uc.query.empty());
  16852. }
  16853. }
  16854. TEST(ParseUrlTest, UserinfoHandling) {
  16855. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16856. // parsers would see evil.com as the host.
  16857. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16858. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16859. for (auto url : urls) {
  16860. detail::UrlComponents uc;
  16861. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16862. }
  16863. }
  16864. TEST(ParseUrlTest, IPv6EdgeCases) {
  16865. {
  16866. detail::UrlComponents uc;
  16867. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16868. EXPECT_TRUE(uc.scheme.empty());
  16869. EXPECT_EQ("::1", uc.host);
  16870. EXPECT_EQ("8080", uc.port);
  16871. }
  16872. {
  16873. // Zone ID '%25' is not in [a-fA-F0-9:]
  16874. detail::UrlComponents uc;
  16875. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16876. }
  16877. }
  16878. TEST(ParseUrlTest, SchemeEdgeCases) {
  16879. {
  16880. detail::UrlComponents uc;
  16881. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16882. }
  16883. {
  16884. detail::UrlComponents uc;
  16885. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16886. }
  16887. {
  16888. detail::UrlComponents uc;
  16889. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16890. }
  16891. }
  16892. TEST(ParseUrlTest, PortEdgeCases) {
  16893. {
  16894. detail::UrlComponents uc;
  16895. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16896. EXPECT_TRUE(uc.port.empty());
  16897. EXPECT_EQ("/path", uc.path);
  16898. }
  16899. {
  16900. // parse_url accepts any port string; validation is done by parse_port
  16901. detail::UrlComponents uc;
  16902. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16903. EXPECT_EQ("abc", uc.port);
  16904. }
  16905. }
  16906. TEST(ParseUrlTest, WebSocketPatterns) {
  16907. {
  16908. detail::UrlComponents uc;
  16909. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16910. EXPECT_EQ("ws", uc.scheme);
  16911. EXPECT_EQ("echo.example.com", uc.host);
  16912. EXPECT_EQ("8080", uc.port);
  16913. EXPECT_EQ("/ws", uc.path);
  16914. }
  16915. {
  16916. detail::UrlComponents uc;
  16917. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16918. EXPECT_EQ("wss", uc.scheme);
  16919. EXPECT_EQ("echo.example.com", uc.host);
  16920. EXPECT_TRUE(uc.port.empty());
  16921. EXPECT_EQ("/ws", uc.path);
  16922. }
  16923. }
  16924. TEST(ParseUrlTest, QueryOnly) {
  16925. detail::UrlComponents uc;
  16926. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16927. EXPECT_TRUE(uc.host.empty());
  16928. EXPECT_TRUE(uc.path.empty());
  16929. EXPECT_EQ("?q=1&r=2", uc.query);
  16930. }
  16931. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16932. detail::UrlComponents uc;
  16933. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16934. EXPECT_TRUE(uc.scheme.empty());
  16935. EXPECT_EQ("example.com", uc.host);
  16936. EXPECT_EQ("443", uc.port);
  16937. EXPECT_EQ("/path", uc.path);
  16938. }
  16939. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16940. // If ipv6 regex working, regex match codepath is taken.
  16941. // else port will default to 80 in Client impl
  16942. int clientImplMagicPort = 80;
  16943. int port = 4321;
  16944. // above ports must be different to avoid false negative
  16945. EXPECT_NE(clientImplMagicPort, port);
  16946. std::string ipV6TestURL = "http://[ff06::c3]";
  16947. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16948. CLIENT_PRIVATE_KEY_FILE);
  16949. EXPECT_EQ(cli.port(), port);
  16950. }
  16951. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16952. auto file_path = "./www/dir/index.html";
  16953. auto dir_path = "./www/dir";
  16954. detail::FileStat stat_file(file_path);
  16955. EXPECT_TRUE(stat_file.is_file());
  16956. EXPECT_FALSE(stat_file.is_dir());
  16957. detail::FileStat stat_dir(dir_path);
  16958. EXPECT_FALSE(stat_dir.is_file());
  16959. EXPECT_TRUE(stat_dir.is_dir());
  16960. }
  16961. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16962. // IPv4 with default HTTP port (80)
  16963. EXPECT_EQ("example.com",
  16964. detail::make_host_and_port_string("example.com", 80, false));
  16965. // IPv4 with default HTTPS port (443)
  16966. EXPECT_EQ("example.com",
  16967. detail::make_host_and_port_string("example.com", 443, true));
  16968. // IPv4 with non-default HTTP port
  16969. EXPECT_EQ("example.com:8080",
  16970. detail::make_host_and_port_string("example.com", 8080, false));
  16971. // IPv4 with non-default HTTPS port
  16972. EXPECT_EQ("example.com:8443",
  16973. detail::make_host_and_port_string("example.com", 8443, true));
  16974. // IPv6 with default HTTP port (80)
  16975. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16976. // IPv6 with default HTTPS port (443)
  16977. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16978. // IPv6 with non-default HTTP port
  16979. EXPECT_EQ("[::1]:8080",
  16980. detail::make_host_and_port_string("::1", 8080, false));
  16981. // IPv6 with non-default HTTPS port
  16982. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16983. // IPv6 full address with default port
  16984. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16985. detail::make_host_and_port_string(
  16986. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16987. // IPv6 full address with non-default port
  16988. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16989. detail::make_host_and_port_string(
  16990. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16991. // IPv6 localhost with non-default port
  16992. EXPECT_EQ("[::1]:3000",
  16993. detail::make_host_and_port_string("::1", 3000, false));
  16994. // IPv6 with zone ID (link-local address) with default port
  16995. EXPECT_EQ("[fe80::1%eth0]",
  16996. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16997. // IPv6 with zone ID (link-local address) with non-default port
  16998. EXPECT_EQ("[fe80::1%eth0]:8080",
  16999. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17000. // Edge case: Port 443 with is_ssl=false (should add port)
  17001. EXPECT_EQ("example.com:443",
  17002. detail::make_host_and_port_string("example.com", 443, false));
  17003. // Edge case: Port 80 with is_ssl=true (should add port)
  17004. EXPECT_EQ("example.com:80",
  17005. detail::make_host_and_port_string("example.com", 80, true));
  17006. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17007. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17008. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17009. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17010. // Security fix: Already bracketed IPv6 should not get double brackets
  17011. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17012. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17013. EXPECT_EQ("[::1]:8080",
  17014. detail::make_host_and_port_string("[::1]", 8080, false));
  17015. EXPECT_EQ("[2001:db8::1]:8080",
  17016. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17017. EXPECT_EQ("[fe80::1%eth0]",
  17018. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17019. EXPECT_EQ("[fe80::1%eth0]:8080",
  17020. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17021. // Edge case: Empty host (should return as-is)
  17022. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17023. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17024. // This is a known limitation but shouldn't crash
  17025. EXPECT_EQ("[host:name]",
  17026. detail::make_host_and_port_string("host:name", 80, false));
  17027. // Port number edge cases (no validation, but should not crash)
  17028. EXPECT_EQ("example.com:0",
  17029. detail::make_host_and_port_string("example.com", 0, false));
  17030. EXPECT_EQ("example.com:-1",
  17031. detail::make_host_and_port_string("example.com", -1, false));
  17032. EXPECT_EQ("example.com:65535",
  17033. detail::make_host_and_port_string("example.com", 65535, false));
  17034. EXPECT_EQ("example.com:65536",
  17035. detail::make_host_and_port_string("example.com", 65536, false));
  17036. }
  17037. #ifdef CPPHTTPLIB_SSL_ENABLED
  17038. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17039. httplib::SSLClient cli("roblox.com", 443);
  17040. cli.set_follow_location(true);
  17041. auto res = cli.Get("/");
  17042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17043. EXPECT_EQ(StatusCode::OK_200, res->status);
  17044. }
  17045. #endif
  17046. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17047. Server svr;
  17048. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17049. EXPECT_EQ(res.status, 400);
  17050. });
  17051. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17052. auto se = detail::scope_exit([&] {
  17053. svr.stop();
  17054. thread.join();
  17055. ASSERT_FALSE(svr.is_running());
  17056. });
  17057. svr.wait_until_ready();
  17058. Client cli(HOST, PORT);
  17059. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17060. }
  17061. TEST(InvalidHeaderCharsTest, is_field_name) {
  17062. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17063. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17064. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17065. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17066. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17067. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17068. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17069. EXPECT_FALSE(detail::fields::is_field_name(""));
  17070. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17071. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17072. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17073. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17074. }
  17075. TEST(InvalidHeaderCharsTest, is_field_value) {
  17076. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17077. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17078. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17079. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17080. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17081. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17082. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17083. EXPECT_TRUE(detail::fields::is_field_value(""));
  17084. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17085. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17086. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17087. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17088. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17089. }
  17090. TEST(InvalidHeaderCharsTest, OnServer) {
  17091. Server svr;
  17092. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17093. std::string header = "Not Set";
  17094. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17095. res.set_header(header, "value");
  17096. res.set_content("Page Content Page Content", "text/plain");
  17097. });
  17098. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17099. std::string header = "Not Set";
  17100. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17101. res.set_header("X-Test", header);
  17102. res.set_content("Page Content Page Content", "text/plain");
  17103. });
  17104. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17105. auto se = detail::scope_exit([&] {
  17106. svr.stop();
  17107. thread.join();
  17108. ASSERT_FALSE(svr.is_running());
  17109. });
  17110. svr.wait_until_ready();
  17111. Client cli(HOST, PORT);
  17112. {
  17113. auto res = cli.Get(
  17114. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17116. EXPECT_EQ("Page Content Page Content", res->body);
  17117. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17118. }
  17119. {
  17120. auto res = cli.Get(
  17121. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17123. EXPECT_EQ("Page Content Page Content", res->body);
  17124. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17125. }
  17126. }
  17127. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17128. auto handled = false;
  17129. Server svr;
  17130. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17131. thread t = thread([&] { svr.listen(HOST, PORT); });
  17132. auto se = detail::scope_exit([&] {
  17133. svr.stop();
  17134. t.join();
  17135. ASSERT_FALSE(svr.is_running());
  17136. ASSERT_FALSE(handled);
  17137. });
  17138. svr.wait_until_ready();
  17139. auto req = "POST /test HTTP/1.1\r\n"
  17140. "Content-Length: x\r\n"
  17141. "\r\n";
  17142. std::string response;
  17143. ASSERT_TRUE(send_request(1, req, &response));
  17144. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17145. response.substr(0, response.find("\r\n")));
  17146. }
  17147. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17148. // case-insensitive, and a server that receives a 100-continue expectation in
  17149. // an HTTP/1.0 request MUST ignore it.
  17150. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17151. std::string response;
  17152. ASSERT_TRUE(send_request(1, req, &response, port));
  17153. *got_100 = response.find("100 Continue") != std::string::npos;
  17154. }
  17155. class ExpectTokenTest : public ::testing::Test {
  17156. protected:
  17157. void SetUp() override {
  17158. svr_.Post("/p", [](const Request &, Response &res) {
  17159. res.set_content("ok", "text/plain");
  17160. });
  17161. port_ = svr_.bind_to_any_port(HOST);
  17162. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17163. svr_.wait_until_ready();
  17164. }
  17165. void TearDown() override {
  17166. svr_.stop();
  17167. if (thread_.joinable()) { thread_.join(); }
  17168. }
  17169. std::string request(const char *version, const char *expect_value) const {
  17170. return std::string("POST /p ") + version +
  17171. "\r\n"
  17172. "Host: localhost\r\n"
  17173. "Content-Length: 2\r\n"
  17174. "Connection: close\r\n"
  17175. "Expect: " +
  17176. expect_value +
  17177. "\r\n"
  17178. "\r\n"
  17179. "hi";
  17180. }
  17181. Server svr_;
  17182. int port_ = 0;
  17183. thread thread_;
  17184. };
  17185. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17186. bool got_100 = false;
  17187. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17188. EXPECT_TRUE(got_100);
  17189. }
  17190. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17191. bool got_100 = true;
  17192. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17193. EXPECT_FALSE(got_100);
  17194. }
  17195. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17196. bool got_100 = false;
  17197. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17198. EXPECT_TRUE(got_100);
  17199. }
  17200. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17201. bool got_100 = false;
  17202. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17203. EXPECT_TRUE(got_100);
  17204. }
  17205. // `100 Continue` is sent only when the server starts reading the body, so a
  17206. // request rejected before that never invites the client to send it. The
  17207. // requests below carry the expectation but withhold the body, as a client
  17208. // waiting for `100 Continue` would.
  17209. // A POST that expects `100 Continue` and withholds its two-byte body.
  17210. static std::string expect_headers_only(const std::string &path) {
  17211. return "POST " + path +
  17212. " HTTP/1.1\r\n"
  17213. "Host: localhost\r\n"
  17214. "Content-Length: 2\r\n"
  17215. "Expect: 100-continue\r\n"
  17216. "\r\n";
  17217. }
  17218. class ExpectLazyContinueTest : public ::testing::Test {
  17219. protected:
  17220. void SetUp() override {
  17221. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17222. if (req.path == "/pre-routing") {
  17223. res.status = StatusCode::Unauthorized_401;
  17224. return Server::HandlerResponse::Handled;
  17225. }
  17226. return Server::HandlerResponse::Unhandled;
  17227. });
  17228. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17229. if (req.matched_route == "/pre-request") {
  17230. res.status = StatusCode::Forbidden_403;
  17231. return Server::HandlerResponse::Handled;
  17232. }
  17233. return Server::HandlerResponse::Unhandled;
  17234. });
  17235. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17236. res.set_content("ok", "text/plain");
  17237. });
  17238. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17239. res.set_content("ok", "text/plain");
  17240. });
  17241. svr_.Post("/reader-used", [](const Request &, Response &res,
  17242. const ContentReader &content_reader) {
  17243. std::string body;
  17244. content_reader([&](const char *data, size_t len) {
  17245. body.append(data, len);
  17246. return true;
  17247. });
  17248. res.set_content(body, "text/plain");
  17249. });
  17250. svr_.Post("/reader-unused",
  17251. [](const Request &, Response &res, const ContentReader &) {
  17252. res.set_content("ignored", "text/plain");
  17253. });
  17254. port_ = svr_.bind_to_any_port(HOST);
  17255. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17256. svr_.wait_until_ready();
  17257. }
  17258. void TearDown() override {
  17259. svr_.stop();
  17260. if (thread_.joinable()) { thread_.join(); }
  17261. }
  17262. // Sends `req` and reads until the server closes the connection. Returns
  17263. // false if the read had to wait for the client-side timeout instead.
  17264. bool send_until_closed(const std::string &req, std::string *resp) const {
  17265. auto start = std::chrono::steady_clock::now();
  17266. if (!send_request(3, req, resp, port_)) { return false; }
  17267. auto elapsed = std::chrono::steady_clock::now() - start;
  17268. return elapsed < std::chrono::seconds(2);
  17269. }
  17270. // The final response comes without `100 Continue`, and the server closes
  17271. // the connection since the body may or may not follow.
  17272. void expect_final_without_interim(const std::string &path,
  17273. const char *status_line) const {
  17274. std::string resp;
  17275. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17276. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17277. EXPECT_EQ(0u, resp.find(status_line));
  17278. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17279. }
  17280. Server svr_;
  17281. int port_ = 0;
  17282. thread thread_;
  17283. };
  17284. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17285. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17286. }
  17287. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17288. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17289. }
  17290. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17291. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17292. }
  17293. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17294. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17295. }
  17296. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17297. // The body follows once `100 Continue` has had time to arrive.
  17298. auto req = expect_headers_only("/reader-used");
  17299. req.insert(req.size() - 2, "Connection: close\r\n");
  17300. std::string resp;
  17301. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17302. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17303. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17304. EXPECT_NE(std::string::npos, resp.find("hi"));
  17305. }
  17306. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17307. // Large enough for the client to add `Expect: 100-continue` itself.
  17308. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17309. std::atomic<bool> body_sent{false};
  17310. Client cli(HOST, port_);
  17311. auto res = cli.Post(
  17312. "/pre-request", length,
  17313. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17314. body_sent = true;
  17315. std::string chunk(len, 'x');
  17316. sink.write(chunk.data(), chunk.size());
  17317. return true;
  17318. },
  17319. "application/octet-stream");
  17320. ASSERT_TRUE(res);
  17321. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17322. EXPECT_FALSE(body_sent);
  17323. }
  17324. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17325. Server svr;
  17326. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17327. return StatusCode::ExpectationFailed_417;
  17328. });
  17329. svr.Post("/p", [](const Request &, Response &res) {
  17330. res.set_content("ok", "text/plain");
  17331. });
  17332. auto port = svr.bind_to_any_port(HOST);
  17333. thread t = thread([&] { svr.listen_after_bind(); });
  17334. auto se = detail::scope_exit([&] {
  17335. svr.stop();
  17336. t.join();
  17337. });
  17338. svr.wait_until_ready();
  17339. std::string resp;
  17340. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17341. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17342. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17343. // Exactly one response: the route handler must not run after the 417.
  17344. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17345. }
  17346. #ifndef _WIN32
  17347. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17348. static constexpr char reject[] = "Unauthorized";
  17349. static constexpr char accept[] = "Upload accepted";
  17350. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17351. Server svr;
  17352. svr.set_expect_100_continue_handler(
  17353. [](const Request & /*req*/, Response &res) {
  17354. res.status = StatusCode::Unauthorized_401;
  17355. res.set_content(reject, "text/plain");
  17356. return res.status;
  17357. });
  17358. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17359. res.set_content(accept, "text/plain");
  17360. });
  17361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17362. auto se = detail::scope_exit([&] {
  17363. svr.stop();
  17364. thread.join();
  17365. ASSERT_FALSE(svr.is_running());
  17366. });
  17367. svr.wait_until_ready();
  17368. {
  17369. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17370. curl_easy_init(), &curl_easy_cleanup};
  17371. ASSERT_NE(curl, nullptr);
  17372. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17373. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17374. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17375. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17376. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17377. &curl_slist_free_all};
  17378. ASSERT_NE(list, nullptr);
  17379. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17380. struct read_data {
  17381. size_t read_size;
  17382. size_t total_size;
  17383. } data = {0, total_size};
  17384. using read_callback_t =
  17385. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17386. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17387. void *userdata) -> size_t {
  17388. read_data *d = (read_data *)userdata;
  17389. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17390. std::fill_n(ptr, size * nmemb, 'A');
  17391. d->read_size += size * nmemb;
  17392. return size * nmemb;
  17393. };
  17394. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17395. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17396. std::vector<char> buffer;
  17397. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17398. using write_callback_t =
  17399. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17400. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17401. void *userdata) -> size_t {
  17402. std::vector<char> *buf = (std::vector<char> *)userdata;
  17403. buf->reserve(buf->size() + size * nmemb + 1);
  17404. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17405. return size * nmemb;
  17406. };
  17407. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17408. {
  17409. const auto res = curl_easy_perform(curl.get());
  17410. ASSERT_EQ(res, CURLE_OK);
  17411. }
  17412. {
  17413. auto response_code = long{};
  17414. const auto res =
  17415. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17416. ASSERT_EQ(res, CURLE_OK);
  17417. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17418. }
  17419. {
  17420. auto dl = curl_off_t{};
  17421. const auto res =
  17422. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17423. ASSERT_EQ(res, CURLE_OK);
  17424. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17425. }
  17426. {
  17427. buffer.push_back('\0');
  17428. ASSERT_STRCASEEQ(buffer.data(), reject);
  17429. }
  17430. }
  17431. }
  17432. #endif
  17433. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17434. // Regression test for #2458.
  17435. //
  17436. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17437. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17438. // ticket can make the client socket spuriously readable during the
  17439. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17440. // the client withholds the body and then blocks reading a response that never
  17441. // comes, failing with `Failed to read connection`.
  17442. //
  17443. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17444. // within the timeout. This raw OpenSSL server deliberately never sends
  17445. // `100 Continue`; the client must still deliver the body and receive 200.
  17446. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17447. signal(SIGPIPE, SIG_IGN);
  17448. const auto port = PORT + 4;
  17449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17450. ASSERT_NE(srv, INVALID_SOCKET);
  17451. int opt = 1;
  17452. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17453. sockaddr_in addr{};
  17454. addr.sin_family = AF_INET;
  17455. addr.sin_port = htons(static_cast<uint16_t>(port));
  17456. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17457. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17458. ASSERT_EQ(0, ::listen(srv, 1));
  17459. std::atomic<size_t> server_body_bytes{0};
  17460. auto server_thread = std::thread([&] {
  17461. sockaddr_in cli_addr{};
  17462. socklen_t cli_len = sizeof(cli_addr);
  17463. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17464. if (cli == INVALID_SOCKET) { return; }
  17465. // Bound the lifetime of the server side so a buggy client (which never
  17466. // sends the body) cannot make this thread block forever on join.
  17467. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17468. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17469. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17470. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17471. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17472. SSL *ssl = SSL_new(ctx);
  17473. SSL_set_fd(ssl, static_cast<int>(cli));
  17474. if (SSL_accept(ssl) > 0) {
  17475. // Read the request headers. Reading here also flushes the TLS 1.3
  17476. // session tickets to the client. Deliberately do NOT send
  17477. // `100 Continue`.
  17478. std::string buf;
  17479. char tmp[1024];
  17480. while (buf.find("\r\n\r\n") == std::string::npos) {
  17481. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17482. if (n <= 0) { break; }
  17483. buf.append(tmp, static_cast<size_t>(n));
  17484. }
  17485. // A correct client sends the body now; count what arrives.
  17486. auto pos = buf.find("\r\n\r\n");
  17487. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17488. while (body < 4096) {
  17489. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17490. if (n <= 0) { break; }
  17491. body += static_cast<size_t>(n);
  17492. }
  17493. server_body_bytes = body;
  17494. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17495. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17496. SSL_shutdown(ssl);
  17497. }
  17498. SSL_free(ssl);
  17499. detail::close_socket(cli);
  17500. SSL_CTX_free(ctx);
  17501. });
  17502. auto se = detail::scope_exit([&] {
  17503. server_thread.join();
  17504. detail::close_socket(srv);
  17505. });
  17506. SSLClient cli("127.0.0.1", port);
  17507. cli.enable_server_certificate_verification(false);
  17508. cli.set_connection_timeout(5, 0);
  17509. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17510. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17511. std::string body(4096, 'A');
  17512. auto res = cli.Put("/api/test", body, "application/json");
  17513. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17514. EXPECT_EQ(StatusCode::OK_200, res->status);
  17515. EXPECT_EQ(body.size(), server_body_bytes.load());
  17516. }
  17517. #endif
  17518. template <typename S, typename C>
  17519. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17520. svr.Get("/stream", [&](const Request &, Response &res) {
  17521. auto data = new std::string("01234567890123456789");
  17522. res.set_content_provider(
  17523. data->size(), "text/plain",
  17524. [&, data](size_t offset, size_t length, DataSink &sink) {
  17525. const size_t DATA_CHUNK_SIZE = 4;
  17526. const auto &d = *data;
  17527. std::this_thread::sleep_for(std::chrono::seconds(1));
  17528. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17529. return true;
  17530. },
  17531. [data](bool success) {
  17532. EXPECT_FALSE(success);
  17533. delete data;
  17534. });
  17535. });
  17536. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17537. auto i = new size_t(0);
  17538. res.set_content_provider(
  17539. "text/plain",
  17540. [i](size_t, DataSink &sink) {
  17541. if (*i < 5) {
  17542. std::this_thread::sleep_for(std::chrono::seconds(1));
  17543. sink.write("abcd", 4);
  17544. (*i)++;
  17545. } else {
  17546. sink.done();
  17547. }
  17548. return true;
  17549. },
  17550. [i](bool success) {
  17551. EXPECT_FALSE(success);
  17552. delete i;
  17553. });
  17554. });
  17555. svr.Get("/chunked", [&](const Request &, Response &res) {
  17556. auto i = new size_t(0);
  17557. res.set_chunked_content_provider(
  17558. "text/plain",
  17559. [i](size_t, DataSink &sink) {
  17560. if (*i < 5) {
  17561. std::this_thread::sleep_for(std::chrono::seconds(1));
  17562. sink.os << "abcd";
  17563. (*i)++;
  17564. } else {
  17565. sink.done();
  17566. }
  17567. return true;
  17568. },
  17569. [i](bool success) {
  17570. EXPECT_FALSE(success);
  17571. delete i;
  17572. });
  17573. });
  17574. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17575. auto se = detail::scope_exit([&] {
  17576. svr.stop();
  17577. listen_thread.join();
  17578. ASSERT_FALSE(svr.is_running());
  17579. });
  17580. svr.wait_until_ready();
  17581. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17582. {
  17583. auto start = std::chrono::steady_clock::now();
  17584. auto res = cli.Get("/stream");
  17585. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17586. std::chrono::steady_clock::now() - start)
  17587. .count();
  17588. ASSERT_FALSE(res);
  17589. EXPECT_EQ(Error::Read, res.error());
  17590. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17591. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17592. }
  17593. {
  17594. auto start = std::chrono::steady_clock::now();
  17595. auto res = cli.Get("/stream_without_length");
  17596. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17597. std::chrono::steady_clock::now() - start)
  17598. .count();
  17599. ASSERT_FALSE(res);
  17600. EXPECT_EQ(Error::Read, res.error());
  17601. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17602. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17603. }
  17604. {
  17605. auto start = std::chrono::steady_clock::now();
  17606. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17607. EXPECT_EQ("abcd", string(data, data_length));
  17608. return true;
  17609. });
  17610. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17611. std::chrono::steady_clock::now() - start)
  17612. .count();
  17613. ASSERT_FALSE(res);
  17614. EXPECT_EQ(Error::Read, res.error());
  17615. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17616. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17617. }
  17618. }
  17619. TEST(MaxTimeoutTest, ContentStream) {
  17620. time_t timeout = 2000;
  17621. time_t threshold = 200;
  17622. Server svr;
  17623. Client cli("localhost", PORT);
  17624. max_timeout_test(svr, cli, timeout, threshold);
  17625. }
  17626. #ifdef CPPHTTPLIB_SSL_ENABLED
  17627. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17628. time_t timeout = 2000;
  17629. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17631. SSLClient cli("localhost", PORT);
  17632. cli.enable_server_certificate_verification(false);
  17633. max_timeout_test(svr, cli, timeout, threshold);
  17634. }
  17635. #endif
  17636. class EventDispatcher {
  17637. public:
  17638. EventDispatcher() {}
  17639. bool wait_event(DataSink *sink) {
  17640. unique_lock<mutex> lk(m_);
  17641. int id = id_;
  17642. // Wait with timeout to prevent hanging if client disconnects
  17643. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17644. [&] { return cid_ == id; })) {
  17645. return false; // Timeout occurred
  17646. }
  17647. sink->write(message_.data(), message_.size());
  17648. return true;
  17649. }
  17650. void send_event(const string &message) {
  17651. lock_guard<mutex> lk(m_);
  17652. cid_ = id_++;
  17653. message_ = message;
  17654. cv_.notify_all();
  17655. }
  17656. private:
  17657. mutex m_;
  17658. condition_variable cv_;
  17659. atomic_int id_{0};
  17660. atomic_int cid_{-1};
  17661. string message_;
  17662. };
  17663. TEST(ClientInThreadTest, Issue2068) {
  17664. EventDispatcher ed;
  17665. Server svr;
  17666. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17667. res.set_chunked_content_provider("text/event-stream",
  17668. [&](size_t /*offset*/, DataSink &sink) {
  17669. return ed.wait_event(&sink);
  17670. });
  17671. });
  17672. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17673. svr.wait_until_ready();
  17674. thread event_thread([&] {
  17675. int id = 0;
  17676. while (svr.is_running()) {
  17677. this_thread::sleep_for(chrono::milliseconds(500));
  17678. std::stringstream ss;
  17679. ss << "data: " << id << "\n\n";
  17680. ed.send_event(ss.str());
  17681. id++;
  17682. }
  17683. });
  17684. auto se = detail::scope_exit([&] {
  17685. svr.stop();
  17686. listen_thread.join();
  17687. event_thread.join();
  17688. ASSERT_FALSE(svr.is_running());
  17689. });
  17690. {
  17691. auto client = detail::make_unique<Client>(HOST, PORT);
  17692. client->set_read_timeout(std::chrono::minutes(10));
  17693. std::atomic<bool> stop{false};
  17694. std::thread t([&] {
  17695. client->Get("/event1",
  17696. [&](const char *, size_t) -> bool { return !stop; });
  17697. });
  17698. std::this_thread::sleep_for(std::chrono::seconds(2));
  17699. stop = true;
  17700. client->stop();
  17701. t.join();
  17702. // Reset client after thread has finished
  17703. client.reset();
  17704. }
  17705. }
  17706. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17707. auto handled = false;
  17708. Server svr;
  17709. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17710. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17711. auto se = detail::scope_exit([&] {
  17712. svr.stop();
  17713. t.join();
  17714. ASSERT_FALSE(svr.is_running());
  17715. ASSERT_FALSE(handled);
  17716. });
  17717. svr.wait_until_ready();
  17718. // Two Content-Length headers with different values — must be rejected
  17719. auto req = "POST /test HTTP/1.1\r\n"
  17720. "Content-Length: 5\r\n"
  17721. "Content-Length: 10\r\n"
  17722. "\r\n"
  17723. "hello";
  17724. std::string response;
  17725. ASSERT_TRUE(send_request(1, req, &response));
  17726. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17727. response.substr(0, response.find("\r\n")));
  17728. }
  17729. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17730. auto handled = false;
  17731. Server svr;
  17732. svr.Post("/test", [&](const Request &, Response &res) {
  17733. handled = true;
  17734. res.set_content("ok", "text/plain");
  17735. });
  17736. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17737. auto se = detail::scope_exit([&] {
  17738. svr.stop();
  17739. t.join();
  17740. ASSERT_FALSE(svr.is_running());
  17741. ASSERT_TRUE(handled);
  17742. });
  17743. svr.wait_until_ready();
  17744. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17745. auto req = "POST /test HTTP/1.1\r\n"
  17746. "Host: localhost\r\n"
  17747. "Content-Length: 5\r\n"
  17748. "Content-Length: 5\r\n"
  17749. "\r\n"
  17750. "hello";
  17751. std::string response;
  17752. ASSERT_TRUE(send_request(1, req, &response));
  17753. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17754. }
  17755. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17756. Server svr;
  17757. svr.Get("/test", [](const Request &, Response &res) {
  17758. res.set_content("ok", "text/plain");
  17759. });
  17760. auto port = svr.bind_to_any_port(HOST);
  17761. thread t = thread([&] { svr.listen_after_bind(); });
  17762. auto se = detail::scope_exit([&] {
  17763. svr.stop();
  17764. t.join();
  17765. ASSERT_FALSE(svr.is_running());
  17766. });
  17767. svr.wait_until_ready();
  17768. auto status_line = [&](const std::string &host_lines) {
  17769. std::string res;
  17770. send_request(
  17771. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17772. &res, port);
  17773. return res.substr(0, res.find("\r\n"));
  17774. };
  17775. const char *accepted[] = {
  17776. "Host: localhost\r\n",
  17777. "Host: a.example:8080\r\n",
  17778. "Host: my_service\r\n",
  17779. "Host: [::1]:8080\r\n",
  17780. "Host: [fe80::1%25eth0]\r\n",
  17781. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17782. };
  17783. for (auto host_lines : accepted) {
  17784. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17785. }
  17786. const char *rejected[] = {
  17787. "Host: a.example\r\nHost: b.example\r\n",
  17788. "Host: a.example\r\nHost: a.example\r\n",
  17789. "Host: a@b.example\r\n",
  17790. "Host: a.example/b\r\n",
  17791. "Host: a.example\\b\r\n",
  17792. "Host: a.example?b\r\n",
  17793. "Host: a.example#b\r\n",
  17794. "Host: a.example b.example\r\n",
  17795. };
  17796. for (auto host_lines : rejected) {
  17797. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17798. << host_lines;
  17799. }
  17800. }
  17801. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17802. Server svr;
  17803. svr.Get("/", [](const Request &req, Response &res) {
  17804. EXPECT_EQ(2U, req.trailers.size());
  17805. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17806. // Denied
  17807. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17808. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17809. // Accepted
  17810. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17811. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17812. EXPECT_TRUE(req.has_trailer("X-World"));
  17813. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17814. res.set_content("ok", "text/plain");
  17815. });
  17816. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17817. auto se = detail::scope_exit([&] {
  17818. svr.stop();
  17819. t.join();
  17820. ASSERT_FALSE(svr.is_running());
  17821. });
  17822. svr.wait_until_ready();
  17823. const std::string req = "GET / HTTP/1.1\r\n"
  17824. "Transfer-Encoding: chunked\r\n"
  17825. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17826. "\r\n"
  17827. "0\r\n"
  17828. "Content-Length: 10\r\n"
  17829. "Host: internal.local\r\n"
  17830. "Content-Type: malicious/content\r\n"
  17831. "Cookie: any\r\n"
  17832. "Set-Cookie: any\r\n"
  17833. "X-Forwarded-For: attacker.com\r\n"
  17834. "X-Real-Ip: 1.1.1.1\r\n"
  17835. "X-Hello: hello\r\n"
  17836. "X-World: world\r\n"
  17837. "\r\n";
  17838. std::string res;
  17839. ASSERT_TRUE(send_request(1, req, &res));
  17840. }
  17841. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17842. // several field lines, and the combined value is what has to be parsed. A
  17843. // Trailer field split across lines therefore declares every name it lists;
  17844. // reading only the first line silently drops the trailers the later lines
  17845. // declare. The prohibited-trailer filter still applies to every line.
  17846. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17847. Server svr;
  17848. size_t observed_trailer_count = 0;
  17849. std::string observed_hello;
  17850. std::string observed_world;
  17851. bool observed_content_length = true;
  17852. svr.Get("/", [&](const Request &req, Response &res) {
  17853. observed_trailer_count = req.trailers.size();
  17854. observed_hello = req.get_trailer_value("X-Hello");
  17855. observed_world = req.get_trailer_value("X-World");
  17856. observed_content_length = req.has_trailer("Content-Length");
  17857. res.set_content("ok", "text/plain");
  17858. });
  17859. auto port = svr.bind_to_any_port(HOST);
  17860. thread t = thread([&]() { svr.listen_after_bind(); });
  17861. auto se = detail::scope_exit([&] {
  17862. svr.stop();
  17863. t.join();
  17864. ASSERT_FALSE(svr.is_running());
  17865. });
  17866. svr.wait_until_ready();
  17867. const std::string req = "GET / HTTP/1.1\r\n"
  17868. "Host: localhost\r\n"
  17869. "Transfer-Encoding: chunked\r\n"
  17870. "Trailer: X-Hello\r\n"
  17871. "Trailer: X-World, Content-Length\r\n"
  17872. "\r\n"
  17873. "0\r\n"
  17874. "X-Hello: hello\r\n"
  17875. "X-World: world\r\n"
  17876. "Content-Length: 10\r\n"
  17877. "\r\n";
  17878. std::string res;
  17879. ASSERT_TRUE(send_request(1, req, &res, port));
  17880. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17881. // Accepted: both field lines contribute to the declared set
  17882. EXPECT_EQ(2U, observed_trailer_count);
  17883. EXPECT_EQ(observed_hello, "hello");
  17884. EXPECT_EQ(observed_world, "world");
  17885. // Denied: a prohibited name stays prohibited on a later field line
  17886. EXPECT_FALSE(observed_content_length);
  17887. }
  17888. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17889. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17890. // unbounded run of fields that are never declared, because the counter would
  17891. // only advance for declared fields.
  17892. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17893. Server svr;
  17894. bool handler_called = false;
  17895. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17896. handler_called = true;
  17897. res.set_content("ok", "text/plain");
  17898. });
  17899. auto port = svr.bind_to_any_port(HOST);
  17900. thread t = thread([&]() { svr.listen_after_bind(); });
  17901. auto se = detail::scope_exit([&] {
  17902. svr.stop();
  17903. t.join();
  17904. ASSERT_FALSE(svr.is_running());
  17905. });
  17906. svr.wait_until_ready();
  17907. // Declare nothing, then send far more undeclared trailer fields than the
  17908. // header-count limit. Parsing must stop and reject the request rather than
  17909. // read every line.
  17910. std::string req = "GET / HTTP/1.1\r\n"
  17911. "Transfer-Encoding: chunked\r\n"
  17912. "\r\n"
  17913. "0\r\n";
  17914. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17915. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17916. }
  17917. req += "\r\n";
  17918. std::string res;
  17919. ASSERT_TRUE(send_request(1, req, &res, port));
  17920. // The request is rejected before the handler runs.
  17921. EXPECT_FALSE(handler_called);
  17922. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17923. }
  17924. // The set of declared trailer names is capped so a peer cannot grow it without
  17925. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17926. // declared past the cap is not honored, even if the field is actually sent.
  17927. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17928. Server svr;
  17929. // One name inside the cap and one past it, so the test tracks the cap rather
  17930. // than a fixed count.
  17931. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17932. const std::string within_cap_name = "X-T-0";
  17933. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17934. bool observed_within_cap = false;
  17935. bool observed_past_cap = false;
  17936. svr.Get("/", [&](const Request &req, Response &res) {
  17937. observed_within_cap = req.has_trailer(within_cap_name);
  17938. observed_past_cap = req.has_trailer(past_cap_name);
  17939. res.set_content("ok", "text/plain");
  17940. });
  17941. auto port = svr.bind_to_any_port(HOST);
  17942. thread t = thread([&]() { svr.listen_after_bind(); });
  17943. auto se = detail::scope_exit([&] {
  17944. svr.stop();
  17945. t.join();
  17946. ASSERT_FALSE(svr.is_running());
  17947. });
  17948. svr.wait_until_ready();
  17949. // Declare more trailer names than the cap in a single Trailer field, then
  17950. // actually send the first (within the cap) and the last (past it).
  17951. std::string trailer_decl = "Trailer: ";
  17952. for (int i = 0; i < declared_count; i++) {
  17953. if (i != 0) { trailer_decl += ", "; }
  17954. trailer_decl += "X-T-" + std::to_string(i);
  17955. }
  17956. trailer_decl += "\r\n";
  17957. const std::string req = "GET / HTTP/1.1\r\n"
  17958. "Host: localhost\r\n"
  17959. "Transfer-Encoding: chunked\r\n" +
  17960. trailer_decl +
  17961. "\r\n"
  17962. "0\r\n" +
  17963. within_cap_name + ": a\r\n" + past_cap_name +
  17964. ": b\r\n"
  17965. "\r\n";
  17966. std::string res;
  17967. ASSERT_TRUE(send_request(1, req, &res, port));
  17968. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17969. // A name within the cap is honored; one declared past the cap is dropped.
  17970. EXPECT_TRUE(observed_within_cap);
  17971. EXPECT_FALSE(observed_past_cap);
  17972. }
  17973. // A direct client that is not listed in trusted_proxies must not be able to
  17974. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17975. // the peer address on the actual TCP connection determines whether the
  17976. // header is honored.
  17977. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17978. Server svr;
  17979. // Deliberately does NOT include the loopback address the test client
  17980. // actually connects from, so the direct connection is not a trusted proxy.
  17981. svr.set_trusted_proxies({"203.0.113.66"});
  17982. std::string observed_remote_addr;
  17983. svr.Get("/ip", [&](const Request &req, Response &res) {
  17984. observed_remote_addr = req.remote_addr;
  17985. res.set_content("ok", "text/plain");
  17986. });
  17987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17988. auto se = detail::scope_exit([&] {
  17989. svr.stop();
  17990. t.join();
  17991. ASSERT_FALSE(svr.is_running());
  17992. });
  17993. svr.wait_until_ready();
  17994. Client cli(HOST, PORT);
  17995. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17997. EXPECT_EQ(StatusCode::OK_200, res->status);
  17998. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17999. // ignored entirely and the real connection-level address retained.
  18000. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18001. observed_remote_addr == "127.0.0.1");
  18002. }
  18003. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18004. Server svr;
  18005. std::string observed_remote_addr;
  18006. std::string observed_xff;
  18007. svr.Get("/ip", [&](const Request &req, Response &res) {
  18008. observed_remote_addr = req.remote_addr;
  18009. observed_xff = req.get_header_value("X-Forwarded-For");
  18010. res.set_content("ok", "text/plain");
  18011. });
  18012. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18013. auto se = detail::scope_exit([&] {
  18014. svr.stop();
  18015. t.join();
  18016. ASSERT_FALSE(svr.is_running());
  18017. });
  18018. svr.wait_until_ready();
  18019. Client cli(HOST, PORT);
  18020. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18022. EXPECT_EQ(StatusCode::OK_200, res->status);
  18023. EXPECT_EQ(observed_xff, "203.0.113.66");
  18024. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18025. observed_remote_addr == "127.0.0.1");
  18026. }
  18027. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18028. Server svr;
  18029. svr.set_trusted_proxies({"203.0.113.66"});
  18030. std::string observed_remote_addr;
  18031. std::string observed_xff;
  18032. svr.Get("/ip", [&](const Request &req, Response &res) {
  18033. observed_remote_addr = req.remote_addr;
  18034. observed_xff = req.get_header_value("X-Forwarded-For");
  18035. res.set_content("ok", "text/plain");
  18036. });
  18037. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18038. auto se = detail::scope_exit([&] {
  18039. svr.stop();
  18040. t.join();
  18041. ASSERT_FALSE(svr.is_running());
  18042. });
  18043. svr.wait_until_ready();
  18044. Client cli(HOST, PORT);
  18045. auto res = cli.Get("/ip");
  18046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18047. EXPECT_EQ(StatusCode::OK_200, res->status);
  18048. EXPECT_EQ(observed_xff, "");
  18049. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18050. observed_remote_addr == "127.0.0.1");
  18051. }
  18052. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18053. Server svr;
  18054. // Include the loopback address the test client actually connects from, so
  18055. // the direct connection itself is recognized as the trusted proxy hop.
  18056. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18057. std::string observed_remote_addr;
  18058. std::string observed_xff;
  18059. svr.Get("/ip", [&](const Request &req, Response &res) {
  18060. observed_remote_addr = req.remote_addr;
  18061. observed_xff = req.get_header_value("X-Forwarded-For");
  18062. res.set_content("ok", "text/plain");
  18063. });
  18064. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18065. auto se = detail::scope_exit([&] {
  18066. svr.stop();
  18067. t.join();
  18068. ASSERT_FALSE(svr.is_running());
  18069. });
  18070. svr.wait_until_ready();
  18071. Client cli(HOST, PORT);
  18072. auto res = cli.Get(
  18073. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18075. EXPECT_EQ(StatusCode::OK_200, res->status);
  18076. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18077. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18078. }
  18079. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18080. Server svr;
  18081. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18082. std::string observed_remote_addr;
  18083. std::string observed_xff;
  18084. svr.Get("/ip", [&](const Request &req, Response &res) {
  18085. observed_remote_addr = req.remote_addr;
  18086. observed_xff = req.get_header_value("X-Forwarded-For");
  18087. res.set_content("ok", "text/plain");
  18088. });
  18089. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18090. auto se = detail::scope_exit([&] {
  18091. svr.stop();
  18092. t.join();
  18093. ASSERT_FALSE(svr.is_running());
  18094. });
  18095. svr.wait_until_ready();
  18096. Client cli(HOST, PORT);
  18097. auto res = cli.Get(
  18098. "/ip",
  18099. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18101. EXPECT_EQ(StatusCode::OK_200, res->status);
  18102. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18103. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18104. }
  18105. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18106. Server svr;
  18107. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18108. std::string observed_remote_addr;
  18109. std::string observed_xff;
  18110. svr.Get("/ip", [&](const Request &req, Response &res) {
  18111. observed_remote_addr = req.remote_addr;
  18112. observed_xff = req.get_header_value("X-Forwarded-For");
  18113. res.set_content("ok", "text/plain");
  18114. });
  18115. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18116. auto se = detail::scope_exit([&] {
  18117. svr.stop();
  18118. t.join();
  18119. ASSERT_FALSE(svr.is_running());
  18120. });
  18121. svr.wait_until_ready();
  18122. Client cli(HOST, PORT);
  18123. auto res = cli.Get(
  18124. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18126. EXPECT_EQ(StatusCode::OK_200, res->status);
  18127. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18128. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18129. // and must not be selected.
  18130. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18131. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18132. }
  18133. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18134. Server svr;
  18135. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18136. std::string observed_remote_addr;
  18137. svr.Get("/ip", [&](const Request &req, Response &res) {
  18138. observed_remote_addr = req.remote_addr;
  18139. res.set_content("ok", "text/plain");
  18140. });
  18141. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18142. auto se = detail::scope_exit([&] {
  18143. svr.stop();
  18144. t.join();
  18145. ASSERT_FALSE(svr.is_running());
  18146. });
  18147. svr.wait_until_ready();
  18148. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18149. // a forged address and the trusted proxy's own address; the forged value must
  18150. // not win over the address the trusted proxy actually recorded.
  18151. Client cli(HOST, PORT);
  18152. auto res = cli.Get(
  18153. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18155. EXPECT_EQ(StatusCode::OK_200, res->status);
  18156. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18157. }
  18158. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18159. Server svr;
  18160. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18161. std::string observed_remote_addr;
  18162. std::string observed_xff;
  18163. svr.Get("/ip", [&](const Request &req, Response &res) {
  18164. observed_remote_addr = req.remote_addr;
  18165. observed_xff = req.get_header_value("X-Forwarded-For");
  18166. res.set_content("ok", "text/plain");
  18167. });
  18168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18169. auto se = detail::scope_exit([&] {
  18170. svr.stop();
  18171. t.join();
  18172. ASSERT_FALSE(svr.is_running());
  18173. });
  18174. svr.wait_until_ready();
  18175. Client cli(HOST, PORT);
  18176. auto res = cli.Get(
  18177. "/ip",
  18178. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18180. EXPECT_EQ(StatusCode::OK_200, res->status);
  18181. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18182. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18183. }
  18184. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18185. Server svr;
  18186. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18187. std::string observed_remote_addr;
  18188. std::string observed_xff;
  18189. svr.Get("/ip", [&](const Request &req, Response &res) {
  18190. observed_remote_addr = req.remote_addr;
  18191. observed_xff = req.get_header_value("X-Forwarded-For");
  18192. res.set_content("ok", "text/plain");
  18193. });
  18194. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18195. auto se = detail::scope_exit([&] {
  18196. svr.stop();
  18197. t.join();
  18198. ASSERT_FALSE(svr.is_running());
  18199. });
  18200. svr.wait_until_ready();
  18201. std::string raw_req =
  18202. "GET /ip HTTP/1.1\r\n"
  18203. "Host: localhost\r\n"
  18204. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18205. "Connection: close\r\n"
  18206. "\r\n";
  18207. std::string out;
  18208. ASSERT_TRUE(send_request(5, raw_req, &out));
  18209. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18210. // Header parser trims surrounding whitespace of the header value
  18211. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18212. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18213. }
  18214. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18215. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18216. // their own X-Forwarded-For as a separate field line rather than extending the
  18217. // one the client sent, so every occurrence has to be taken into account.
  18218. // Reading only the first one hands back the address the client chose.
  18219. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18220. Server svr;
  18221. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18222. std::string observed_remote_addr;
  18223. size_t observed_xff_count = 0;
  18224. svr.Get("/ip", [&](const Request &req, Response &res) {
  18225. observed_remote_addr = req.remote_addr;
  18226. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18227. res.set_content("ok", "text/plain");
  18228. });
  18229. auto port = svr.bind_to_any_port(HOST);
  18230. thread t = thread([&]() { svr.listen_after_bind(); });
  18231. auto se = detail::scope_exit([&] {
  18232. svr.stop();
  18233. t.join();
  18234. ASSERT_FALSE(svr.is_running());
  18235. });
  18236. svr.wait_until_ready();
  18237. // The client supplies the first field line; the trusted proxy appends the
  18238. // address it observed as a second one.
  18239. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18240. "Host: localhost\r\n"
  18241. "X-Forwarded-For: 1.2.3.4\r\n"
  18242. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18243. "Connection: close\r\n"
  18244. "\r\n";
  18245. std::string out;
  18246. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18247. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18248. EXPECT_EQ(observed_xff_count, 2U);
  18249. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18250. // The same chain spread over one field line per hop derives the same client
  18251. // address, i.e. the split and the comma-joined representations agree.
  18252. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18253. "Host: localhost\r\n"
  18254. "X-Forwarded-For: 1.2.3.4\r\n"
  18255. "X-Forwarded-For: 198.51.100.23\r\n"
  18256. "X-Forwarded-For: 192.0.2.45\r\n"
  18257. "Connection: close\r\n"
  18258. "\r\n";
  18259. out.clear();
  18260. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18261. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18262. EXPECT_EQ(observed_xff_count, 3U);
  18263. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18264. }
  18265. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18266. // crash the server (it used to call front() on an empty vector inside
  18267. // get_client_ip). The connection-level remote address must be retained instead.
  18268. static void run_malformed_xff_test(const std::string &xff_value) {
  18269. Server svr;
  18270. svr.set_trusted_proxies({"192.0.2.45"});
  18271. std::string observed_remote_addr;
  18272. svr.Get("/ip", [&](const Request &req, Response &res) {
  18273. observed_remote_addr = req.remote_addr;
  18274. res.set_content("ok", "text/plain");
  18275. });
  18276. int port = 0;
  18277. thread t = thread([&]() {
  18278. port = svr.bind_to_any_port(HOST);
  18279. svr.listen_after_bind();
  18280. });
  18281. auto se = detail::scope_exit([&] {
  18282. svr.stop();
  18283. t.join();
  18284. ASSERT_FALSE(svr.is_running());
  18285. });
  18286. svr.wait_until_ready();
  18287. Client cli(HOST, port);
  18288. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18290. EXPECT_EQ(StatusCode::OK_200, res->status);
  18291. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18292. observed_remote_addr == "127.0.0.1");
  18293. }
  18294. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18295. run_malformed_xff_test("");
  18296. }
  18297. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18298. run_malformed_xff_test(",");
  18299. }
  18300. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18301. run_malformed_xff_test(", , ,");
  18302. }
  18303. // The same rule applies to Accept: a request whose acceptable types are spread
  18304. // over several field lines must be negotiated against all of them.
  18305. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18306. // case-insensitive connection options. Comparing the whole field value against
  18307. // one option misses a client that sends several of them, and misses every
  18308. // casing but the one written in the comparison.
  18309. //
  18310. // Sends req, reads the response, then reuses the same socket for a second
  18311. // request to find out whether the server kept the connection.
  18312. static void probe_connection_reuse(int port, const std::string &req,
  18313. bool *announced_close, bool *reusable) {
  18314. auto error = Error::Success;
  18315. auto sock = detail::create_client_socket(
  18316. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18317. /*connection_timeout_sec=*/5, 0,
  18318. /*read_timeout_sec=*/1, 0,
  18319. /*write_timeout_sec=*/5, 0, std::string(), error);
  18320. ASSERT_NE(sock, INVALID_SOCKET);
  18321. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18322. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18323. "Host: localhost\r\n"
  18324. "Connection: close\r\n"
  18325. "\r\n";
  18326. std::string first_response;
  18327. std::string second_response;
  18328. detail::process_client_socket(
  18329. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18330. [&](Stream &strm) {
  18331. if (strm.write(req.data(), req.size()) !=
  18332. static_cast<ssize_t>(req.size())) {
  18333. return false;
  18334. }
  18335. char buf[512];
  18336. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18337. // Headers plus the two-byte body of the handler below
  18338. while (reader.getline()) {
  18339. first_response += reader.ptr();
  18340. if (first_response.find("ok") != std::string::npos) { break; }
  18341. }
  18342. if (strm.write(second.data(), second.size()) !=
  18343. static_cast<ssize_t>(second.size())) {
  18344. return true;
  18345. }
  18346. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18347. while (reader2.getline()) {
  18348. second_response += reader2.ptr();
  18349. if (second_response.find("ok") != std::string::npos) { break; }
  18350. }
  18351. return true;
  18352. });
  18353. *announced_close =
  18354. first_response.find("Connection: close") != std::string::npos;
  18355. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18356. }
  18357. class ConnectionTokenTest : public ::testing::Test {
  18358. protected:
  18359. void SetUp() override {
  18360. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18361. res.set_content("ok", "text/plain");
  18362. });
  18363. port_ = svr_.bind_to_any_port(HOST);
  18364. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18365. svr_.wait_until_ready();
  18366. }
  18367. void TearDown() override {
  18368. svr_.stop();
  18369. if (thread_.joinable()) { thread_.join(); }
  18370. }
  18371. Server svr_;
  18372. int port_ = 0;
  18373. thread thread_;
  18374. };
  18375. // "close" alongside another option still closes the connection, and the
  18376. // response says so rather than leaving the peer to discover it.
  18377. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18378. bool announced_close = false;
  18379. bool reusable = true;
  18380. probe_connection_reuse(port_,
  18381. "GET /keepalive HTTP/1.1\r\n"
  18382. "Host: localhost\r\n"
  18383. "Connection: keep-alive, close\r\n"
  18384. "\r\n",
  18385. &announced_close, &reusable);
  18386. EXPECT_TRUE(announced_close);
  18387. EXPECT_FALSE(reusable);
  18388. }
  18389. // "close" split over two field lines is the same list, so it is honored too.
  18390. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18391. bool announced_close = false;
  18392. bool reusable = true;
  18393. probe_connection_reuse(port_,
  18394. "GET /keepalive HTTP/1.1\r\n"
  18395. "Host: localhost\r\n"
  18396. "Connection: keep-alive\r\n"
  18397. "Connection: close\r\n"
  18398. "\r\n",
  18399. &announced_close, &reusable);
  18400. EXPECT_TRUE(announced_close);
  18401. EXPECT_FALSE(reusable);
  18402. }
  18403. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18404. // keep-alive in the spelling everyone actually sends keeps its connection.
  18405. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18406. bool announced_close = false;
  18407. bool reusable = false;
  18408. probe_connection_reuse(port_,
  18409. "GET /keepalive HTTP/1.0\r\n"
  18410. "Host: localhost\r\n"
  18411. "Connection: keep-alive\r\n"
  18412. "\r\n",
  18413. &announced_close, &reusable);
  18414. EXPECT_FALSE(announced_close);
  18415. EXPECT_TRUE(reusable);
  18416. }
  18417. // A token the value merely contains is not the token itself.
  18418. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18419. bool announced_close = false;
  18420. bool reusable = false;
  18421. probe_connection_reuse(port_,
  18422. "GET /keepalive HTTP/1.1\r\n"
  18423. "Host: localhost\r\n"
  18424. "Connection: notclose\r\n"
  18425. "\r\n",
  18426. &announced_close, &reusable);
  18427. EXPECT_FALSE(announced_close);
  18428. EXPECT_TRUE(reusable);
  18429. }
  18430. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18431. Server svr;
  18432. std::vector<std::string> observed_types;
  18433. svr.Get("/", [&](const Request &req, Response &res) {
  18434. observed_types = req.accept_content_types;
  18435. res.set_content("ok", "text/plain");
  18436. });
  18437. auto port = svr.bind_to_any_port(HOST);
  18438. thread t = thread([&]() { svr.listen_after_bind(); });
  18439. auto se = detail::scope_exit([&] {
  18440. svr.stop();
  18441. t.join();
  18442. ASSERT_FALSE(svr.is_running());
  18443. });
  18444. svr.wait_until_ready();
  18445. Client cli(HOST, port);
  18446. Headers headers;
  18447. headers.emplace("Accept", "text/plain;q=0.5");
  18448. headers.emplace("Accept", "application/json");
  18449. auto res = cli.Get("/", headers);
  18450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18451. EXPECT_EQ(StatusCode::OK_200, res->status);
  18452. // Sorted by q-value, so the second field line's type comes first
  18453. ASSERT_EQ(2U, observed_types.size());
  18454. EXPECT_EQ("application/json", observed_types[0]);
  18455. EXPECT_EQ("text/plain", observed_types[1]);
  18456. }
  18457. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18458. // empty field line must not contribute a bare comma to the combined value.
  18459. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18460. Server svr;
  18461. std::vector<std::string> observed_types;
  18462. svr.Get("/", [&](const Request &req, Response &res) {
  18463. observed_types = req.accept_content_types;
  18464. res.set_content("ok", "text/plain");
  18465. });
  18466. auto port = svr.bind_to_any_port(HOST);
  18467. thread t = thread([&]() { svr.listen_after_bind(); });
  18468. auto se = detail::scope_exit([&] {
  18469. svr.stop();
  18470. t.join();
  18471. ASSERT_FALSE(svr.is_running());
  18472. });
  18473. svr.wait_until_ready();
  18474. // Empty first field line, then a real one
  18475. std::string raw_req = "GET / HTTP/1.1\r\n"
  18476. "Host: localhost\r\n"
  18477. "Accept:\r\n"
  18478. "Accept: application/json\r\n"
  18479. "Connection: close\r\n"
  18480. "\r\n";
  18481. std::string out;
  18482. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18483. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18484. ASSERT_EQ(1U, observed_types.size());
  18485. EXPECT_EQ("application/json", observed_types[0]);
  18486. }
  18487. // The skip in get_combined_header_value() is what keeps an empty field line
  18488. // from contributing a bare comma. Only a trailing empty field line exercises
  18489. // it: a leading one is already covered by the "combined is still empty" check,
  18490. // and parse_accept_header() now ignores the empty element either way, so the
  18491. // request-level test above can no longer tell the two apart.
  18492. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18493. Headers headers;
  18494. headers.emplace("Accept", "text/html");
  18495. headers.emplace("Accept", "");
  18496. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18497. headers.clear();
  18498. headers.emplace("Accept", "");
  18499. headers.emplace("Accept", "application/json");
  18500. EXPECT_EQ("application/json",
  18501. detail::get_combined_header_value(headers, "Accept"));
  18502. }
  18503. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18504. // An encoding offered on a later Accept-Encoding field line is still offered.
  18505. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18506. Server svr;
  18507. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18508. res.set_content(std::string(1024, 'x'), "text/plain");
  18509. });
  18510. auto port = svr.bind_to_any_port(HOST);
  18511. thread t = thread([&]() { svr.listen_after_bind(); });
  18512. auto se = detail::scope_exit([&] {
  18513. svr.stop();
  18514. t.join();
  18515. ASSERT_FALSE(svr.is_running());
  18516. });
  18517. svr.wait_until_ready();
  18518. Client cli(HOST, port);
  18519. cli.set_decompress(false);
  18520. Headers headers;
  18521. headers.emplace("Accept-Encoding", "identity");
  18522. headers.emplace("Accept-Encoding", "gzip");
  18523. auto res = cli.Get("/", headers);
  18524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18525. EXPECT_EQ(StatusCode::OK_200, res->status);
  18526. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18527. }
  18528. #endif
  18529. #ifndef _WIN32
  18530. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18531. Server svr;
  18532. svr.Post("/post", [&](const Request &req, Response &res) {
  18533. res.set_content(req.body, "text/plain");
  18534. });
  18535. svr.Put("/put", [&](const Request &req, Response &res) {
  18536. res.set_content(req.body, "text/plain");
  18537. });
  18538. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18539. res.set_content(req.body, "text/plain");
  18540. });
  18541. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18542. res.set_content(req.body, "text/plain");
  18543. });
  18544. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18545. auto se = detail::scope_exit([&] {
  18546. svr.stop();
  18547. t.join();
  18548. ASSERT_FALSE(svr.is_running());
  18549. });
  18550. svr.wait_until_ready();
  18551. std::string resp;
  18552. // POST without Content-Length
  18553. ASSERT_TRUE(send_request(5,
  18554. "POST /post HTTP/1.1\r\n"
  18555. "Host: localhost\r\n"
  18556. "Connection: close\r\n"
  18557. "\r\n",
  18558. &resp));
  18559. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18560. // PUT without Content-Length
  18561. resp.clear();
  18562. ASSERT_TRUE(send_request(5,
  18563. "PUT /put HTTP/1.1\r\n"
  18564. "Host: localhost\r\n"
  18565. "Connection: close\r\n"
  18566. "\r\n",
  18567. &resp));
  18568. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18569. // PATCH without Content-Length
  18570. resp.clear();
  18571. ASSERT_TRUE(send_request(5,
  18572. "PATCH /patch HTTP/1.1\r\n"
  18573. "Host: localhost\r\n"
  18574. "Connection: close\r\n"
  18575. "\r\n",
  18576. &resp));
  18577. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18578. // DELETE without Content-Length
  18579. resp.clear();
  18580. ASSERT_TRUE(send_request(5,
  18581. "DELETE /delete HTTP/1.1\r\n"
  18582. "Host: localhost\r\n"
  18583. "Connection: close\r\n"
  18584. "\r\n",
  18585. &resp));
  18586. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18587. }
  18588. #endif
  18589. //==============================================================================
  18590. // open_stream() Tests
  18591. //==============================================================================
  18592. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18593. std::string result;
  18594. char buf[8192];
  18595. ssize_t n;
  18596. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18597. result.append(buf, static_cast<size_t>(n));
  18598. }
  18599. return result;
  18600. }
  18601. // Mock stream for unit tests
  18602. class MockStream : public Stream {
  18603. public:
  18604. std::string data;
  18605. size_t pos = 0;
  18606. ssize_t error_after = -1; // -1 = no error
  18607. explicit MockStream(const std::string &d, ssize_t err = -1)
  18608. : data(d), error_after(err) {}
  18609. bool is_readable() const override { return true; }
  18610. bool wait_readable() const override { return true; }
  18611. bool wait_writable() const override { return true; }
  18612. ssize_t read(char *ptr, size_t size) override {
  18613. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18614. if (pos >= data.size()) return 0;
  18615. size_t limit =
  18616. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18617. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18618. std::memcpy(ptr, data.data() + pos, to_read);
  18619. pos += to_read;
  18620. return static_cast<ssize_t>(to_read);
  18621. }
  18622. ssize_t write(const char *, size_t) override { return -1; }
  18623. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18624. ip = "127.0.0.1";
  18625. port = 0;
  18626. }
  18627. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18628. ip = "127.0.0.1";
  18629. port = 0;
  18630. }
  18631. socket_t socket() const override { return INVALID_SOCKET; }
  18632. time_t duration() const override { return 0; }
  18633. };
  18634. TEST(StreamHandleTest, Basic) {
  18635. ClientImpl::StreamHandle handle;
  18636. EXPECT_FALSE(handle.is_valid());
  18637. handle.response = detail::make_unique<Response>();
  18638. handle.error = Error::Connection;
  18639. EXPECT_FALSE(handle.is_valid());
  18640. handle.error = Error::Success;
  18641. EXPECT_TRUE(handle.is_valid());
  18642. }
  18643. TEST(BodyReaderTest, Basic) {
  18644. MockStream stream("Hello, World!");
  18645. detail::BodyReader reader;
  18646. reader.stream = &stream;
  18647. reader.content_length = 13;
  18648. char buf[32];
  18649. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18650. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18651. EXPECT_TRUE(reader.eof);
  18652. }
  18653. TEST(BodyReaderTest, NoStream) {
  18654. detail::BodyReader reader;
  18655. char buf[32];
  18656. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18657. EXPECT_EQ(Error::Connection, reader.last_error);
  18658. }
  18659. TEST(BodyReaderTest, Error) {
  18660. MockStream stream("Hello, World!", 5);
  18661. detail::BodyReader reader;
  18662. reader.stream = &stream;
  18663. reader.content_length = 13;
  18664. char buf[32];
  18665. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18666. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18667. EXPECT_EQ(Error::Read, reader.last_error);
  18668. }
  18669. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18670. // Mock-based StreamHandle tests relying on private internals are removed.
  18671. class OpenStreamTest : public ::testing::Test {
  18672. protected:
  18673. void SetUp() override {
  18674. svr_.Get("/hello", [](const Request &, Response &res) {
  18675. res.set_content("Hello World!", "text/plain");
  18676. });
  18677. svr_.Get("/large", [](const Request &, Response &res) {
  18678. res.set_content(std::string(10000, 'X'), "text/plain");
  18679. });
  18680. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18681. res.set_content("Hello World!", "image/jpeg");
  18682. res.set_header("Content-Encoding", "UTF-8");
  18683. });
  18684. svr_.Get("/chunked", [](const Request &, Response &res) {
  18685. res.set_chunked_content_provider("text/plain",
  18686. [](size_t offset, DataSink &sink) {
  18687. if (offset < 15) {
  18688. sink.write("chunk", 5);
  18689. return true;
  18690. }
  18691. sink.done();
  18692. return true;
  18693. });
  18694. });
  18695. svr_.Get("/compressible", [](const Request &, Response &res) {
  18696. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18697. DataSink &sink) {
  18698. if (offset < 100 * 1024) {
  18699. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18700. sink.write(chunk.data(), chunk.size());
  18701. return true;
  18702. }
  18703. sink.done();
  18704. return true;
  18705. });
  18706. });
  18707. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18708. [](const Request & /*req*/, Response &res) {
  18709. auto i = new int(0);
  18710. res.set_header("Trailer", "Content-Length, X-Allowed");
  18711. res.set_chunked_content_provider(
  18712. "text/plain",
  18713. [i](size_t /*offset*/, DataSink &sink) {
  18714. switch (*i) {
  18715. case 0: sink.os << "123"; break;
  18716. case 1: sink.os << "456"; break;
  18717. case 2: sink.os << "789"; break;
  18718. case 3: {
  18719. sink.done_with_trailer(
  18720. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18721. } break;
  18722. }
  18723. (*i)++;
  18724. return true;
  18725. },
  18726. [i](bool success) {
  18727. EXPECT_TRUE(success);
  18728. delete i;
  18729. });
  18730. });
  18731. // Echo headers endpoint for header-related tests
  18732. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18733. std::string body;
  18734. for (const auto &h : req.headers) {
  18735. body.append(h.first);
  18736. body.push_back(':');
  18737. body.append(h.second);
  18738. body.push_back('\n');
  18739. }
  18740. res.set_content(body, "text/plain");
  18741. });
  18742. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18743. std::string body;
  18744. for (const auto &h : req.headers) {
  18745. body.append(h.first);
  18746. body.push_back(':');
  18747. body.append(h.second);
  18748. body.push_back('\n');
  18749. }
  18750. res.set_content(body, "text/plain");
  18751. });
  18752. port_ = svr_.bind_to_any_port("127.0.0.1");
  18753. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18754. svr_.wait_until_ready();
  18755. }
  18756. void TearDown() override {
  18757. svr_.stop();
  18758. if (thread_.joinable()) thread_.join();
  18759. }
  18760. Server svr_;
  18761. std::thread thread_;
  18762. int port_ = 0;
  18763. };
  18764. TEST_F(OpenStreamTest, Basic) {
  18765. Client cli("127.0.0.1", port_);
  18766. auto handle = cli.open_stream("GET", "/hello");
  18767. EXPECT_TRUE(handle.is_valid());
  18768. EXPECT_EQ("Hello World!", read_all(handle));
  18769. }
  18770. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18771. Client cli("127.0.0.1", port_);
  18772. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18773. ASSERT_TRUE(handle.is_valid());
  18774. EXPECT_EQ("Hello World!", read_all(handle));
  18775. }
  18776. TEST_F(OpenStreamTest, SmallBuffer) {
  18777. Client cli("127.0.0.1", port_);
  18778. auto handle = cli.open_stream("GET", "/hello");
  18779. std::string result;
  18780. char buf[4];
  18781. ssize_t n;
  18782. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18783. result.append(buf, static_cast<size_t>(n));
  18784. EXPECT_EQ("Hello World!", result);
  18785. }
  18786. TEST_F(OpenStreamTest, DefaultHeaders) {
  18787. Client cli("127.0.0.1", port_);
  18788. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18789. {
  18790. auto handle = cli.open_stream("GET", "/echo-headers");
  18791. ASSERT_TRUE(handle.is_valid());
  18792. auto body = read_all(handle);
  18793. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18794. std::string::npos);
  18795. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18796. std::string::npos);
  18797. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18798. }
  18799. // open_stream POST with body and no explicit content_type should NOT add
  18800. // text/plain Content-Type (behavior differs from non-streaming path), but
  18801. // should include Content-Length
  18802. {
  18803. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18804. ASSERT_TRUE(handle.is_valid());
  18805. auto body = read_all(handle);
  18806. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18807. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18808. }
  18809. // open_stream POST with explicit Content-Type should preserve it
  18810. {
  18811. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18812. {{"Content-Type", "application/custom"}},
  18813. "{}", "application/custom");
  18814. ASSERT_TRUE(handle.is_valid());
  18815. auto body = read_all(handle);
  18816. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18817. }
  18818. // User-specified User-Agent must not be overwritten for stream API
  18819. {
  18820. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18821. {{"User-Agent", "MyAgent/1.2"}});
  18822. ASSERT_TRUE(handle.is_valid());
  18823. auto body = read_all(handle);
  18824. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18825. }
  18826. }
  18827. TEST_F(OpenStreamTest, Large) {
  18828. Client cli("127.0.0.1", port_);
  18829. auto handle = cli.open_stream("GET", "/large");
  18830. EXPECT_EQ(10000u, read_all(handle).size());
  18831. }
  18832. TEST_F(OpenStreamTest, ConnectionError) {
  18833. Client cli("127.0.0.1", 9999);
  18834. auto handle = cli.open_stream("GET", "/hello");
  18835. EXPECT_FALSE(handle.is_valid());
  18836. }
  18837. TEST_F(OpenStreamTest, Chunked) {
  18838. Client cli("127.0.0.1", port_);
  18839. auto handle = cli.open_stream("GET", "/chunked");
  18840. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18841. "Transfer-Encoding") == "chunked");
  18842. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18843. }
  18844. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18845. Client cli("127.0.0.1", port_);
  18846. auto handle =
  18847. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18848. ASSERT_TRUE(handle.is_valid());
  18849. // Consume body to allow trailers to be received/parsed
  18850. auto body = read_all(handle);
  18851. // Explicitly parse trailers (ensure trailers are available for assertion)
  18852. handle.parse_trailers_if_needed();
  18853. EXPECT_EQ(std::string("123456789"), body);
  18854. // The response should include a Trailer header declaring both names
  18855. ASSERT_TRUE(handle.response);
  18856. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18857. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18858. handle.response->get_header_value("Trailer"));
  18859. // Prohibited trailer must not be present
  18860. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18861. // Allowed trailer should be present
  18862. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18863. EXPECT_EQ(std::string("yes"),
  18864. handle.response->get_trailer_value("X-Allowed"));
  18865. // Verify trailers are NOT present as regular headers
  18866. EXPECT_EQ(std::string(""),
  18867. handle.response->get_header_value("Content-Length"));
  18868. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18869. }
  18870. // Accepts one connection on an OS-assigned port, which it hands over through
  18871. // port_promise, reads the request head and sends back response. after_send,
  18872. // if given, runs on the connection before it is closed.
  18873. static std::thread
  18874. serve_single_response(std::promise<int> &port_promise,
  18875. const std::string &response,
  18876. std::function<void(socket_t)> after_send = nullptr) {
  18877. return std::thread([&port_promise, response, after_send] {
  18878. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18879. default_socket_options(srv);
  18880. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18882. sockaddr_in addr{};
  18883. addr.sin_family = AF_INET;
  18884. addr.sin_port = htons(0); // Let OS assign a free port
  18885. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18886. int opt = 1;
  18887. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18888. #ifdef _WIN32
  18889. reinterpret_cast<const char *>(&opt),
  18890. #else
  18891. &opt,
  18892. #endif
  18893. sizeof(opt));
  18894. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18895. ::listen(srv, 1) != 0) {
  18896. port_promise.set_value(-1);
  18897. detail::close_socket(srv);
  18898. return;
  18899. }
  18900. socklen_t addr_len = sizeof(addr);
  18901. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18902. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18903. sockaddr_in cli_addr{};
  18904. socklen_t cli_len = sizeof(cli_addr);
  18905. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18906. if (cli != INVALID_SOCKET) {
  18907. // Read the complete HTTP request (until the blank line that terminates
  18908. // headers) before sending the response. If the server closes the socket
  18909. // while the client's request data is still unread in the kernel receive
  18910. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18911. // connection on both sides: it discards the client's receive buffer
  18912. // (which already holds our response) and causes any in-progress write on
  18913. // the client to fail with ECONNRESET. Reading all request data first
  18914. // ensures close() emits a graceful FIN.
  18915. {
  18916. char rbuf[256];
  18917. std::string req;
  18918. while (req.find("\r\n\r\n") == std::string::npos) {
  18919. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18920. if (n <= 0) { break; }
  18921. req.append(rbuf, static_cast<size_t>(n));
  18922. }
  18923. }
  18924. ::send(cli,
  18925. #ifdef _WIN32
  18926. static_cast<const char *>(response.c_str()),
  18927. static_cast<int>(response.size()),
  18928. #else
  18929. response.c_str(), response.size(),
  18930. #endif
  18931. 0);
  18932. if (after_send) { after_send(cli); }
  18933. detail::close_socket(cli);
  18934. }
  18935. detail::close_socket(srv);
  18936. });
  18937. }
  18938. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18939. #ifndef _WIN32
  18940. signal(SIGPIPE, SIG_IGN);
  18941. #endif
  18942. std::promise<int> port_promise;
  18943. auto port_future = port_promise.get_future();
  18944. auto server_thread =
  18945. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18946. "Content-Type: text/plain\r\n"
  18947. "Content-Length: not-a-number\r\n"
  18948. "Connection: close\r\n"
  18949. "\r\n"
  18950. "hello");
  18951. auto port = port_future.get();
  18952. ASSERT_GT(port, 0);
  18953. Client cli("127.0.0.1", port);
  18954. auto handle = cli.open_stream("GET", "/");
  18955. EXPECT_FALSE(handle.is_valid());
  18956. server_thread.join();
  18957. }
  18958. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18959. #ifndef _WIN32
  18960. signal(SIGPIPE, SIG_IGN);
  18961. #endif
  18962. std::promise<int> port_promise;
  18963. auto port_future = port_promise.get_future();
  18964. auto server_thread = serve_single_response(
  18965. port_promise, "HTTP/1.1 200 OK\r\n"
  18966. "Content-Type: text/plain\r\n"
  18967. "Content-Length: 99999999999999999999999999\r\n"
  18968. "Connection: close\r\n"
  18969. "\r\n"
  18970. "hello");
  18971. auto port = port_future.get();
  18972. ASSERT_GT(port, 0);
  18973. // Historically std::stoull would throw std::out_of_range here and crash
  18974. // the process, then parsing silently clamped to a bogus framing length and
  18975. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18976. // so the stream fails to open, matching the not-a-number case above. The
  18977. // process still must NOT terminate.
  18978. Client cli("127.0.0.1", port);
  18979. auto handle = cli.open_stream("GET", "/");
  18980. EXPECT_FALSE(handle.is_valid());
  18981. server_thread.join();
  18982. }
  18983. // Serves `response` to the single request `fn` makes with a fresh client.
  18984. template <typename Fn>
  18985. static void with_single_response(const std::string &response, Fn fn) {
  18986. #ifndef _WIN32
  18987. signal(SIGPIPE, SIG_IGN);
  18988. #endif
  18989. std::promise<int> port_promise;
  18990. auto port_future = port_promise.get_future();
  18991. auto server_thread = serve_single_response(port_promise, response);
  18992. auto se = detail::scope_exit([&] { server_thread.join(); });
  18993. auto port = port_future.get();
  18994. ASSERT_GT(port, 0);
  18995. Client cli("127.0.0.1", port);
  18996. fn(cli);
  18997. }
  18998. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18999. const char *responses[] = {
  19000. "HTTP/1.1 103 Early Hints\r\n"
  19001. "Link: </style.css>; rel=preload\r\n"
  19002. "\r\n"
  19003. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19004. "HTTP/1.1 100 Continue\r\n"
  19005. "X-Note: interim\r\n"
  19006. "\r\n"
  19007. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19008. };
  19009. for (auto response : responses) {
  19010. with_single_response(response, [](Client &cli) {
  19011. auto res = cli.Get("/");
  19012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19013. EXPECT_EQ(StatusCode::OK_200, res->status);
  19014. EXPECT_EQ("ok", res->body);
  19015. });
  19016. }
  19017. }
  19018. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19019. #ifndef _WIN32
  19020. signal(SIGPIPE, SIG_IGN);
  19021. #endif
  19022. // The server answers the head without asking for the body. Bytes it then
  19023. // reads on the connection would be taken for the body the request declared.
  19024. auto closed_by_client = false;
  19025. std::promise<int> port_promise;
  19026. auto server_thread = serve_single_response(
  19027. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19028. [&](socket_t sock) {
  19029. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19030. char buf[256];
  19031. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19032. });
  19033. Client cli("127.0.0.1", port_promise.get_future().get());
  19034. cli.set_keep_alive(true);
  19035. cli.set_read_timeout(1, 0);
  19036. // Long enough for the client to send Expect: 100-continue.
  19037. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19039. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19040. cli.Get("/second");
  19041. server_thread.join();
  19042. EXPECT_TRUE(closed_by_client);
  19043. }
  19044. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19045. // Long enough for the client to send Expect: 100-continue
  19046. with_single_response(
  19047. "HTTP/1.1 103 Early Hints\r\n"
  19048. "Link: </style.css>; rel=preload\r\n"
  19049. "\r\n"
  19050. "HTTP/1.1 401 Unauthorized\r\n"
  19051. "Content-Length: 0\r\n\r\n",
  19052. [](Client &cli) {
  19053. cli.set_read_timeout(2, 0);
  19054. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19056. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19057. });
  19058. }
  19059. #ifdef CPPHTTPLIB_SSL_ENABLED
  19060. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19061. #ifndef _WIN32
  19062. signal(SIGPIPE, SIG_IGN);
  19063. #endif
  19064. auto reused = false;
  19065. std::promise<int> port_promise;
  19066. auto server_thread = serve_single_response(
  19067. port_promise,
  19068. "HTTP/1.1 401 Unauthorized\r\n"
  19069. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19070. "Content-Length: 0\r\n\r\n",
  19071. [&](socket_t sock) {
  19072. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19073. char buf[256];
  19074. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19075. });
  19076. Client cli("127.0.0.1", port_promise.get_future().get());
  19077. cli.set_keep_alive(true);
  19078. cli.set_digest_auth("user", "pass");
  19079. cli.set_read_timeout(1, 0);
  19080. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19081. server_thread.join();
  19082. EXPECT_FALSE(reused);
  19083. }
  19084. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19085. // Any other answer to CONNECT would read as the origin's response.
  19086. struct {
  19087. const char *response;
  19088. bool passed_on;
  19089. } cases[] = {
  19090. {"HTTP/1.1 201 Created\r\n"
  19091. "Set-Cookie: session=from-proxy\r\n"
  19092. "Content-Length: 0\r\n\r\n",
  19093. false},
  19094. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19095. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19096. "Content-Length: 0\r\n\r\n",
  19097. true},
  19098. };
  19099. for (const auto &c : cases) {
  19100. std::promise<int> port_promise;
  19101. auto server_thread = serve_single_response(port_promise, c.response);
  19102. SSLClient cli("example.com", 443);
  19103. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19104. auto res = cli.Get("/");
  19105. server_thread.join();
  19106. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19107. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19108. if (res) {
  19109. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19110. }
  19111. }
  19112. }
  19113. #endif
  19114. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19115. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19116. // the chunked coding and drop Content-Length, so a front-end that trusts
  19117. // Content-Length would disagree about where the body ends (response
  19118. // smuggling). The client must reject such a response.
  19119. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19120. for (const char *te : {"chunked", "gzip, chunked"}) {
  19121. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19122. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19123. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19124. "5\r\nhello\r\n0\r\n\r\n";
  19125. with_single_response(response, [&](Client &cli) {
  19126. auto res = cli.Get("/");
  19127. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19128. EXPECT_EQ(Error::Read, res.error()) << te;
  19129. });
  19130. with_single_response(response, [&](Client &cli) {
  19131. auto handle = cli.open_stream("GET", "/");
  19132. EXPECT_FALSE(handle.is_valid()) << te;
  19133. EXPECT_EQ(Error::Read, handle.error) << te;
  19134. });
  19135. }
  19136. }
  19137. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19138. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19139. // closing the connection (unlike a request, which must be rejected).
  19140. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19141. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19142. "Transfer-Encoding: chunked\r\n"
  19143. "Connection: close\r\n"
  19144. "\r\n"
  19145. "5\r\nhello\r\n0\r\n\r\n",
  19146. "HTTP/1.1 200 OK\r\n"
  19147. "Transfer-Encoding: gzip\r\n"
  19148. "Connection: close\r\n"
  19149. "\r\n"
  19150. "hello"}) {
  19151. with_single_response(response, [&](Client &cli) {
  19152. auto res = cli.Get("/");
  19153. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19154. EXPECT_EQ("hello", res->body);
  19155. });
  19156. with_single_response(response, [&](Client &cli) {
  19157. auto handle = cli.open_stream("GET", "/");
  19158. ASSERT_TRUE(handle.is_valid()) << response;
  19159. EXPECT_EQ("hello", read_all(handle));
  19160. });
  19161. }
  19162. }
  19163. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19164. // framing headers describe nothing to read and must not be rejected.
  19165. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19166. const std::string framing = "Content-Length: 5\r\n"
  19167. "Transfer-Encoding: chunked\r\n"
  19168. "Connection: close\r\n"
  19169. "\r\n";
  19170. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19171. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19172. });
  19173. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19174. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19175. });
  19176. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19177. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19178. with_single_response(response, [&](Client &cli) {
  19179. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19180. });
  19181. with_single_response(response, [&](Client &cli) {
  19182. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19183. });
  19184. }
  19185. }
  19186. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19187. // response, is faulty framing, so the connection is not reused after it.
  19188. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19189. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19190. "Content-Length: 0\r\n"
  19191. "Transfer-Encoding: chunked\r\n"
  19192. "\r\n"
  19193. "5\r\nhello\r\n0\r\n\r\n",
  19194. "HTTP/1.0 200 Connection established\r\n"
  19195. "Connection: keep-alive\r\n"
  19196. "Transfer-Encoding: chunked\r\n"
  19197. "\r\n"
  19198. "5\r\nhello\r\n0\r\n\r\n"}) {
  19199. with_single_response(response, [&](Client &cli) {
  19200. cli.set_keep_alive(true);
  19201. auto res = cli.Get("/");
  19202. ASSERT_TRUE(res) << response;
  19203. EXPECT_EQ("hello", res->body);
  19204. EXPECT_FALSE(cli.is_socket_open()) << response;
  19205. });
  19206. }
  19207. }
  19208. // A payload max length of 0 means no limit, however the body is framed.
  19209. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19210. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19211. "Transfer-Encoding: chunked\r\n"
  19212. "\r\n"
  19213. "5\r\nhello\r\n0\r\n\r\n",
  19214. "HTTP/1.1 200 OK\r\n"
  19215. "Connection: close\r\n"
  19216. "\r\n"
  19217. "hello"}) {
  19218. with_single_response(response, [&](Client &cli) {
  19219. cli.set_payload_max_length(0);
  19220. auto res = cli.Get("/");
  19221. ASSERT_TRUE(res) << response;
  19222. EXPECT_EQ("hello", res->body) << response;
  19223. });
  19224. }
  19225. }
  19226. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19227. Server svr;
  19228. svr.set_payload_max_length(0);
  19229. svr.Post("/echo", [](const Request &req, Response &res) {
  19230. res.set_content(req.body, "text/plain");
  19231. });
  19232. auto port = svr.bind_to_any_port(HOST);
  19233. thread t = thread([&] { svr.listen_after_bind(); });
  19234. auto se = detail::scope_exit([&] {
  19235. svr.stop();
  19236. t.join();
  19237. ASSERT_FALSE(svr.is_running());
  19238. });
  19239. svr.wait_until_ready();
  19240. Client cli(HOST, port);
  19241. auto res = cli.Post(
  19242. "/echo",
  19243. [](size_t /*offset*/, DataSink &sink) {
  19244. sink.write("hello", 5);
  19245. sink.done();
  19246. return true;
  19247. },
  19248. "text/plain");
  19249. ASSERT_TRUE(res);
  19250. EXPECT_EQ(StatusCode::OK_200, res->status);
  19251. EXPECT_EQ("hello", res->body);
  19252. }
  19253. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19254. TEST_F(OpenStreamTest, Gzip) {
  19255. Client cli("127.0.0.1", port_);
  19256. auto handle = cli.open_stream("GET", "/compressible", {},
  19257. {{"Accept-Encoding", "gzip"}});
  19258. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19259. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19260. }
  19261. #endif
  19262. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19263. TEST_F(OpenStreamTest, Brotli) {
  19264. Client cli("127.0.0.1", port_);
  19265. auto handle =
  19266. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19267. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19268. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19269. }
  19270. #endif
  19271. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19272. TEST_F(OpenStreamTest, Zstd) {
  19273. Client cli("127.0.0.1", port_);
  19274. auto handle = cli.open_stream("GET", "/compressible", {},
  19275. {{"Accept-Encoding", "zstd"}});
  19276. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19277. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19278. }
  19279. #endif
  19280. #ifdef CPPHTTPLIB_SSL_ENABLED
  19281. class SSLOpenStreamTest : public ::testing::Test {
  19282. protected:
  19283. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19284. void SetUp() override {
  19285. svr_.Get("/hello", [](const Request &, Response &res) {
  19286. res.set_content("Hello SSL World!", "text/plain");
  19287. });
  19288. svr_.Get("/chunked", [](const Request &, Response &res) {
  19289. res.set_chunked_content_provider("text/plain",
  19290. [](size_t offset, DataSink &sink) {
  19291. if (offset < 15) {
  19292. sink.write("chunk", 5);
  19293. return true;
  19294. }
  19295. sink.done();
  19296. return true;
  19297. });
  19298. });
  19299. svr_.Post("/echo", [](const Request &req, Response &res) {
  19300. res.set_content(req.body, req.get_header_value("Content-Type"));
  19301. });
  19302. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19303. std::string body = req.body;
  19304. res.set_chunked_content_provider(
  19305. "text/plain", [body](size_t offset, DataSink &sink) {
  19306. if (offset < body.size()) {
  19307. sink.write(body.data() + offset, body.size() - offset);
  19308. }
  19309. sink.done();
  19310. return true;
  19311. });
  19312. });
  19313. port_ = svr_.bind_to_any_port("127.0.0.1");
  19314. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19315. svr_.wait_until_ready();
  19316. }
  19317. void TearDown() override {
  19318. svr_.stop();
  19319. if (thread_.joinable()) thread_.join();
  19320. }
  19321. SSLServer svr_;
  19322. std::thread thread_;
  19323. int port_ = 0;
  19324. };
  19325. TEST_F(SSLOpenStreamTest, Basic) {
  19326. SSLClient cli("127.0.0.1", port_);
  19327. cli.enable_server_certificate_verification(false);
  19328. auto handle = cli.open_stream("GET", "/hello");
  19329. ASSERT_TRUE(handle.is_valid());
  19330. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19331. }
  19332. TEST_F(SSLOpenStreamTest, Chunked) {
  19333. SSLClient cli("127.0.0.1", port_);
  19334. cli.enable_server_certificate_verification(false);
  19335. auto handle = cli.open_stream("GET", "/chunked");
  19336. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19337. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19338. "Transfer-Encoding") == "chunked");
  19339. auto body = read_all(handle);
  19340. EXPECT_EQ("chunkchunkchunk", body);
  19341. }
  19342. TEST_F(SSLOpenStreamTest, Post) {
  19343. SSLClient cli("127.0.0.1", port_);
  19344. cli.enable_server_certificate_verification(false);
  19345. auto handle =
  19346. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19347. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19348. EXPECT_EQ(200, handle.response->status);
  19349. auto body = read_all(handle);
  19350. EXPECT_EQ("Hello SSL POST", body);
  19351. }
  19352. TEST_F(SSLOpenStreamTest, PostChunked) {
  19353. SSLClient cli("127.0.0.1", port_);
  19354. cli.enable_server_certificate_verification(false);
  19355. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19356. "Chunked SSL Data", "text/plain");
  19357. ASSERT_TRUE(handle.is_valid());
  19358. EXPECT_EQ(200, handle.response->status);
  19359. auto body = read_all(handle);
  19360. EXPECT_EQ("Chunked SSL Data", body);
  19361. }
  19362. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19363. // Content-Length is terminated by the server closing the connection. When the
  19364. // SSL peer sends a close_notify after the body, the client must treat it as a
  19365. // clean EOF and return a successful response rather than an error.
  19366. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19367. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19368. ASSERT_TRUE(svr.is_valid());
  19369. svr.set_keep_alive_max_count(1);
  19370. const std::string expected_body = "Hello from connection-close response!";
  19371. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19372. res.set_content_provider("text/plain",
  19373. [&](size_t offset, DataSink &sink) -> bool {
  19374. if (offset < expected_body.size()) {
  19375. sink.write(expected_body.data() + offset,
  19376. expected_body.size() - offset);
  19377. }
  19378. sink.done();
  19379. return true;
  19380. });
  19381. });
  19382. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19383. auto se = detail::scope_exit([&] {
  19384. svr.stop();
  19385. listen_thread.join();
  19386. ASSERT_FALSE(svr.is_running());
  19387. });
  19388. svr.wait_until_ready();
  19389. SSLClient cli(HOST, PORT);
  19390. cli.enable_server_certificate_verification(false);
  19391. auto res = cli.Get("/no-content-length");
  19392. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19393. EXPECT_EQ(StatusCode::OK_200, res->status);
  19394. EXPECT_EQ(expected_body, res->body);
  19395. }
  19396. #endif // CPPHTTPLIB_SSL_ENABLED
  19397. //==============================================================================
  19398. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19399. // results for various scenarios.
  19400. //==============================================================================
  19401. TEST(ParityTest, GetVsOpenStream) {
  19402. Server svr;
  19403. const std::string path = "/parity";
  19404. const std::string content = "Parity test content: hello world";
  19405. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19406. res.set_content(content, "text/plain");
  19407. });
  19408. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19409. auto se = detail::scope_exit([&] {
  19410. svr.stop();
  19411. t.join();
  19412. ASSERT_FALSE(svr.is_running());
  19413. });
  19414. svr.wait_until_ready();
  19415. Client cli(HOST, PORT);
  19416. // Non-stream path
  19417. auto r1 = cli.Get(path);
  19418. ASSERT_TRUE(r1);
  19419. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19420. // Stream path
  19421. auto h = cli.open_stream("GET", path);
  19422. ASSERT_TRUE(h.is_valid());
  19423. EXPECT_EQ(r1->body, read_all(h));
  19424. }
  19425. // Helper to compress data with provided compressor type T
  19426. template <typename Compressor>
  19427. static std::string compress_payload_for_parity(const std::string &in) {
  19428. std::string out;
  19429. Compressor compressor;
  19430. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19431. [&](const char *data, size_t n) {
  19432. out.append(data, n);
  19433. return true;
  19434. });
  19435. EXPECT_TRUE(ok);
  19436. return out;
  19437. }
  19438. // Helper function for compression parity tests
  19439. template <typename Compressor>
  19440. static void test_compression_parity(const std::string &original,
  19441. const std::string &path,
  19442. const std::string &encoding) {
  19443. const std::string compressed =
  19444. compress_payload_for_parity<Compressor>(original);
  19445. Server svr;
  19446. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19447. res.set_content(compressed, "application/octet-stream");
  19448. res.set_header("Content-Encoding", encoding);
  19449. });
  19450. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19451. auto se = detail::scope_exit([&] {
  19452. svr.stop();
  19453. t.join();
  19454. ASSERT_FALSE(svr.is_running());
  19455. });
  19456. svr.wait_until_ready();
  19457. Client cli(HOST, PORT);
  19458. // Non-streaming
  19459. {
  19460. auto res = cli.Get(path);
  19461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19462. EXPECT_EQ(StatusCode::OK_200, res->status);
  19463. EXPECT_EQ(original, res->body);
  19464. }
  19465. // Streaming
  19466. {
  19467. auto h = cli.open_stream("GET", path);
  19468. ASSERT_TRUE(h.is_valid());
  19469. EXPECT_EQ(original, read_all(h));
  19470. }
  19471. }
  19472. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19473. TEST(ParityTest, Gzip) {
  19474. test_compression_parity<detail::gzip_compressor>(
  19475. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19476. }
  19477. #endif
  19478. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19479. TEST(ParityTest, Brotli) {
  19480. test_compression_parity<detail::brotli_compressor>(
  19481. "Hello, brotli parity test payload", "/parity-br", "br");
  19482. }
  19483. #endif
  19484. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19485. TEST(ParityTest, Zstd) {
  19486. test_compression_parity<detail::zstd_compressor>(
  19487. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19488. }
  19489. #endif
  19490. //==============================================================================
  19491. // New Stream API Tests
  19492. //==============================================================================
  19493. inline std::string read_body(httplib::stream::Result &result) {
  19494. std::string body;
  19495. while (result.next()) {
  19496. body.append(result.data(), result.size());
  19497. }
  19498. return body;
  19499. }
  19500. TEST(ClientConnectionTest, Basic) {
  19501. httplib::ClientConnection conn;
  19502. EXPECT_FALSE(conn.is_open());
  19503. conn.sock = 1;
  19504. EXPECT_TRUE(conn.is_open());
  19505. httplib::ClientConnection conn2(std::move(conn));
  19506. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19507. conn2.sock = INVALID_SOCKET;
  19508. }
  19509. // Unified test server for all stream::* tests
  19510. class StreamApiTest : public ::testing::Test {
  19511. protected:
  19512. void SetUp() override {
  19513. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19514. res.set_content("Hello World!", "text/plain");
  19515. });
  19516. svr_.Get("/echo-params",
  19517. [](const httplib::Request &req, httplib::Response &res) {
  19518. std::string r;
  19519. for (const auto &p : req.params) {
  19520. if (!r.empty()) r += "&";
  19521. r += p.first + "=" + p.second;
  19522. }
  19523. res.set_content(r, "text/plain");
  19524. });
  19525. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19526. res.set_content(req.body, req.get_header_value("Content-Type"));
  19527. });
  19528. svr_.Post("/echo-headers",
  19529. [](const httplib::Request &req, httplib::Response &res) {
  19530. std::string r;
  19531. for (const auto &h : req.headers)
  19532. r += h.first + ": " + h.second + "\n";
  19533. res.set_content(r, "text/plain");
  19534. });
  19535. svr_.Post("/echo-params",
  19536. [](const httplib::Request &req, httplib::Response &res) {
  19537. std::string r = "params:";
  19538. for (const auto &p : req.params)
  19539. r += p.first + "=" + p.second + ";";
  19540. res.set_content(r + " body:" + req.body, "text/plain");
  19541. });
  19542. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19543. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19544. });
  19545. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19546. res.set_content("PUT:" + req.body, "text/plain");
  19547. });
  19548. svr_.Patch("/echo",
  19549. [](const httplib::Request &req, httplib::Response &res) {
  19550. res.set_content("PATCH:" + req.body, "text/plain");
  19551. });
  19552. svr_.Delete(
  19553. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19554. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19555. "text/plain");
  19556. });
  19557. svr_.Get("/head-test",
  19558. [](const httplib::Request &, httplib::Response &res) {
  19559. res.set_content("body for HEAD", "text/plain");
  19560. });
  19561. svr_.Options("/options",
  19562. [](const httplib::Request &, httplib::Response &res) {
  19563. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19564. });
  19565. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19566. svr_.wait_until_ready();
  19567. }
  19568. void TearDown() override {
  19569. svr_.stop();
  19570. if (thread_.joinable()) thread_.join();
  19571. }
  19572. httplib::Server svr_;
  19573. std::thread thread_;
  19574. };
  19575. // stream::Get tests
  19576. TEST_F(StreamApiTest, GetBasic) {
  19577. httplib::Client cli(HOST, PORT);
  19578. auto result = httplib::stream::Get(cli, "/hello");
  19579. ASSERT_TRUE(result.is_valid());
  19580. EXPECT_EQ(200, result.status());
  19581. EXPECT_EQ("Hello World!", read_body(result));
  19582. }
  19583. TEST_F(StreamApiTest, GetWithParams) {
  19584. httplib::Client cli(HOST, PORT);
  19585. httplib::Params params{{"foo", "bar"}};
  19586. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19587. ASSERT_TRUE(result.is_valid());
  19588. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19589. }
  19590. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19591. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19592. httplib::Client cli(HOST, PORT);
  19593. cli.set_payload_max_length(0);
  19594. auto result = httplib::stream::Get(cli, "/hello");
  19595. ASSERT_TRUE(result.is_valid());
  19596. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19597. EXPECT_EQ("Hello World!", read_body(result));
  19598. }
  19599. #endif
  19600. TEST_F(StreamApiTest, GetConnectionError) {
  19601. httplib::Client cli(HOST, 9999);
  19602. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19603. }
  19604. TEST_F(StreamApiTest, Get404) {
  19605. httplib::Client cli(HOST, PORT);
  19606. auto result = httplib::stream::Get(cli, "/nonexistent");
  19607. EXPECT_TRUE(result.is_valid());
  19608. EXPECT_EQ(404, result.status());
  19609. }
  19610. // stream::Post tests
  19611. TEST_F(StreamApiTest, PostBasic) {
  19612. httplib::Client cli(HOST, PORT);
  19613. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19614. "application/json");
  19615. ASSERT_TRUE(result.is_valid());
  19616. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19617. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19618. }
  19619. TEST_F(StreamApiTest, PostWithHeaders) {
  19620. httplib::Client cli(HOST, PORT);
  19621. httplib::Headers headers{{"X-Custom", "value"}};
  19622. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19623. "text/plain");
  19624. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19625. }
  19626. TEST_F(StreamApiTest, PostWithParams) {
  19627. httplib::Client cli(HOST, PORT);
  19628. httplib::Params params{{"k", "v"}};
  19629. auto result =
  19630. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19631. auto body = read_body(result);
  19632. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19633. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19634. }
  19635. TEST_F(StreamApiTest, PostLarge) {
  19636. httplib::Client cli(HOST, PORT);
  19637. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19638. size_t total = 0;
  19639. while (result.next()) {
  19640. total += result.size();
  19641. }
  19642. EXPECT_EQ(100u * 1024u, total);
  19643. }
  19644. // stream::Put/Patch tests
  19645. TEST_F(StreamApiTest, PutAndPatch) {
  19646. httplib::Client cli(HOST, PORT);
  19647. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19648. EXPECT_EQ("PUT:test", read_body(put));
  19649. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19650. EXPECT_EQ("PATCH:test", read_body(patch));
  19651. }
  19652. // stream::Delete tests
  19653. TEST_F(StreamApiTest, Delete) {
  19654. httplib::Client cli(HOST, PORT);
  19655. auto del1 = httplib::stream::Delete(cli, "/resource");
  19656. EXPECT_EQ("Deleted", read_body(del1));
  19657. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19658. EXPECT_EQ("Deleted:data", read_body(del2));
  19659. }
  19660. // stream::Head/Options tests
  19661. TEST_F(StreamApiTest, HeadAndOptions) {
  19662. httplib::Client cli(HOST, PORT);
  19663. auto head = httplib::stream::Head(cli, "/head-test");
  19664. EXPECT_TRUE(head.is_valid());
  19665. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19666. auto opts = httplib::stream::Options(cli, "/options");
  19667. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19668. }
  19669. // SSL stream::* tests
  19670. #ifdef CPPHTTPLIB_SSL_ENABLED
  19671. class SSLStreamApiTest : public ::testing::Test {
  19672. protected:
  19673. void SetUp() override {
  19674. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19675. res.set_content("Hello SSL!", "text/plain");
  19676. });
  19677. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19678. res.set_content(req.body, "text/plain");
  19679. });
  19680. port_ = svr_.bind_to_any_port("127.0.0.1");
  19681. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19682. svr_.wait_until_ready();
  19683. }
  19684. void TearDown() override {
  19685. svr_.stop();
  19686. if (thread_.joinable()) thread_.join();
  19687. }
  19688. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19689. std::thread thread_;
  19690. int port_ = 0;
  19691. };
  19692. TEST_F(SSLStreamApiTest, GetAndPost) {
  19693. httplib::SSLClient cli("127.0.0.1", port_);
  19694. cli.enable_server_certificate_verification(false);
  19695. auto get = httplib::stream::Get(cli, "/hello");
  19696. EXPECT_EQ("Hello SSL!", read_body(get));
  19697. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19698. EXPECT_EQ("test", read_body(post));
  19699. }
  19700. #endif
  19701. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19702. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19703. // BodyReader
  19704. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19705. // Test that read timeout during streaming is detected
  19706. // Use a large content-length response where server delays mid-stream
  19707. Server svr;
  19708. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19709. // Send a large response with delay in the middle
  19710. res.set_content_provider(
  19711. 1000, // content_length
  19712. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19713. if (offset < 100) {
  19714. // Send first 100 bytes immediately
  19715. std::string data(100, 'A');
  19716. sink.write(data.c_str(), data.size());
  19717. return true;
  19718. }
  19719. // Then delay longer than client timeout
  19720. std::this_thread::sleep_for(std::chrono::seconds(3));
  19721. std::string data(900, 'B');
  19722. sink.write(data.c_str(), data.size());
  19723. return true;
  19724. });
  19725. });
  19726. auto port = 8091;
  19727. std::thread t([&]() { svr.listen("localhost", port); });
  19728. svr.wait_until_ready();
  19729. Client cli("localhost", port);
  19730. cli.set_read_timeout(1, 0); // 1 second timeout
  19731. auto handle = cli.open_stream("GET", "/slow-stream");
  19732. ASSERT_TRUE(handle.is_valid());
  19733. char buf[256];
  19734. ssize_t total = 0;
  19735. ssize_t n;
  19736. bool got_error = false;
  19737. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19738. total += n;
  19739. }
  19740. if (n < 0) {
  19741. got_error = true;
  19742. // Should be timeout or read error
  19743. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19744. handle.get_read_error() == Error::Read)
  19745. << "Actual error: " << to_string(handle.get_read_error());
  19746. }
  19747. // Either we got an error, or we got less data than expected
  19748. EXPECT_TRUE(got_error || total < 1000)
  19749. << "Expected timeout but got all " << total << " bytes";
  19750. svr.stop();
  19751. t.join();
  19752. }
  19753. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19754. // Test connection closed detection via BodyReader
  19755. Server svr;
  19756. std::atomic<bool> close_now{false};
  19757. svr.Get("/will-close", [&](const Request &, Response &res) {
  19758. res.set_content_provider(
  19759. 10000, // Large content_length that we won't fully send
  19760. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19761. if (offset < 100) {
  19762. std::string data(100, 'X');
  19763. sink.write(data.c_str(), data.size());
  19764. return true;
  19765. }
  19766. // Wait for signal then abort
  19767. while (!close_now) {
  19768. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19769. }
  19770. return false; // Abort - server will close connection
  19771. });
  19772. });
  19773. auto port = 8092;
  19774. std::thread t([&]() { svr.listen("localhost", port); });
  19775. svr.wait_until_ready();
  19776. Client cli("localhost", port);
  19777. auto handle = cli.open_stream("GET", "/will-close");
  19778. ASSERT_TRUE(handle.is_valid());
  19779. char buf[256];
  19780. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19781. EXPECT_GT(n, 0) << "First read should succeed";
  19782. // Signal server to close
  19783. close_now = true;
  19784. // Keep reading until error or EOF
  19785. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19786. // Keep reading
  19787. }
  19788. // Should get an error since content_length wasn't satisfied
  19789. if (n < 0) {
  19790. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19791. handle.get_read_error() == Error::Read)
  19792. << "Actual error: " << to_string(handle.get_read_error());
  19793. }
  19794. svr.stop();
  19795. t.join();
  19796. }
  19797. #ifdef CPPHTTPLIB_SSL_ENABLED
  19798. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19799. // Test that read timeout during SSL streaming is detected
  19800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19801. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19802. res.set_content_provider(
  19803. 1000, "text/plain",
  19804. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19805. if (offset < 100) {
  19806. std::string data(100, 'A');
  19807. sink.write(data.c_str(), data.size());
  19808. return true;
  19809. }
  19810. std::this_thread::sleep_for(std::chrono::seconds(3));
  19811. std::string data(900, 'B');
  19812. sink.write(data.c_str(), data.size());
  19813. return true;
  19814. });
  19815. });
  19816. auto port = 8093;
  19817. std::thread t([&]() { svr.listen("localhost", port); });
  19818. svr.wait_until_ready();
  19819. SSLClient cli("localhost", port);
  19820. cli.enable_server_certificate_verification(false);
  19821. cli.set_read_timeout(1, 0); // 1 second timeout
  19822. auto handle = cli.open_stream("GET", "/slow-stream");
  19823. ASSERT_TRUE(handle.is_valid());
  19824. char buf[256];
  19825. ssize_t total = 0;
  19826. ssize_t n;
  19827. bool got_error = false;
  19828. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19829. total += n;
  19830. }
  19831. if (n < 0) {
  19832. got_error = true;
  19833. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19834. handle.get_read_error() == Error::Read)
  19835. << "Actual error: " << to_string(handle.get_read_error());
  19836. }
  19837. EXPECT_TRUE(got_error || total < 1000)
  19838. << "Expected timeout but got all " << total << " bytes";
  19839. svr.stop();
  19840. t.join();
  19841. }
  19842. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19843. // Test SSL connection closed detection
  19844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19845. std::atomic<bool> close_now{false};
  19846. svr.Get("/will-close", [&](const Request &, Response &res) {
  19847. res.set_content_provider(
  19848. 10000, "text/plain",
  19849. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19850. if (offset < 100) {
  19851. std::string data(100, 'X');
  19852. sink.write(data.c_str(), data.size());
  19853. return true;
  19854. }
  19855. while (!close_now) {
  19856. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19857. }
  19858. return false;
  19859. });
  19860. });
  19861. auto port = 8094;
  19862. std::thread t([&]() { svr.listen("localhost", port); });
  19863. svr.wait_until_ready();
  19864. SSLClient cli("localhost", port);
  19865. cli.enable_server_certificate_verification(false);
  19866. auto handle = cli.open_stream("GET", "/will-close");
  19867. ASSERT_TRUE(handle.is_valid());
  19868. char buf[256];
  19869. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19870. EXPECT_GT(n, 0);
  19871. // Signal server to close
  19872. close_now = true;
  19873. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19874. // Keep reading
  19875. }
  19876. if (n < 0) {
  19877. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19878. handle.get_read_error() == Error::Read)
  19879. << "Actual error: " << to_string(handle.get_read_error());
  19880. }
  19881. svr.stop();
  19882. t.join();
  19883. }
  19884. #endif
  19885. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19886. using namespace httplib;
  19887. // Create a test file
  19888. const char *fname = "etag_testfile.txt";
  19889. const char *content = "etag-content";
  19890. {
  19891. std::ofstream ofs(fname);
  19892. ofs << content;
  19893. ASSERT_TRUE(ofs.good());
  19894. }
  19895. Server svr;
  19896. svr.set_mount_point("/static", ".");
  19897. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19898. svr.wait_until_ready();
  19899. Client cli(HOST, PORT);
  19900. // First request: should get 200 with ETag header
  19901. auto res1 = cli.Get("/static/etag_testfile.txt");
  19902. ASSERT_TRUE(res1);
  19903. ASSERT_EQ(200, res1->status);
  19904. ASSERT_TRUE(res1->has_header("ETag"));
  19905. std::string etag = res1->get_header_value("ETag");
  19906. EXPECT_FALSE(etag.empty());
  19907. // Verify ETag format: W/"hex-hex"
  19908. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19909. EXPECT_EQ('W', etag[0]);
  19910. EXPECT_EQ('/', etag[1]);
  19911. EXPECT_EQ('"', etag[2]);
  19912. EXPECT_EQ('"', etag.back());
  19913. // Exact match: expect 304 Not Modified
  19914. Headers h2 = {{"If-None-Match", etag}};
  19915. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19916. ASSERT_TRUE(res2);
  19917. EXPECT_EQ(304, res2->status);
  19918. // Wildcard match: expect 304 Not Modified
  19919. Headers h3 = {{"If-None-Match", "*"}};
  19920. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19921. ASSERT_TRUE(res3);
  19922. EXPECT_EQ(304, res3->status);
  19923. // Non-matching ETag: expect 200
  19924. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19925. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19926. ASSERT_TRUE(res4);
  19927. EXPECT_EQ(200, res4->status);
  19928. // Multiple ETags with one matching: expect 304
  19929. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19930. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19931. ASSERT_TRUE(res5);
  19932. EXPECT_EQ(304, res5->status);
  19933. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19934. // that equivalent to the single comma-separated list above, so the match on
  19935. // the second line must still be found.
  19936. Headers h6;
  19937. h6.emplace("If-None-Match", "W/\"other\"");
  19938. h6.emplace("If-None-Match", etag);
  19939. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19940. ASSERT_TRUE(res6);
  19941. EXPECT_EQ(304, res6->status);
  19942. svr.stop();
  19943. t.join();
  19944. std::remove(fname);
  19945. }
  19946. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19947. using namespace httplib;
  19948. Server svr;
  19949. svr.set_mount_point("/static", ".");
  19950. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19951. svr.wait_until_ready();
  19952. Client cli(HOST, PORT);
  19953. // Send If-None-Match: * to a non-existent file
  19954. Headers h = {{"If-None-Match", "*"}};
  19955. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19957. EXPECT_EQ(404, res->status);
  19958. svr.stop();
  19959. t.join();
  19960. }
  19961. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19962. using namespace httplib;
  19963. // Create a test file
  19964. const char *fname = "etag_boundary_testfile.txt";
  19965. const char *content = "boundary-test";
  19966. {
  19967. std::ofstream ofs(fname);
  19968. ofs << content;
  19969. ASSERT_TRUE(ofs.good());
  19970. }
  19971. Server svr;
  19972. svr.set_mount_point("/static", ".");
  19973. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19974. svr.wait_until_ready();
  19975. Client cli(HOST, PORT);
  19976. // Get the actual ETag
  19977. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19978. ASSERT_TRUE(res1);
  19979. ASSERT_EQ(200, res1->status);
  19980. ASSERT_TRUE(res1->has_header("ETag"));
  19981. std::string etag = res1->get_header_value("ETag");
  19982. // Test 1: Very long ETag value (longer than actual ETag)
  19983. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19984. Headers h1 = {{"If-None-Match", "W/"
  19985. "\"very-long-etag-value-that-is-much-longer-"
  19986. "than-the-actual-etag-value\""}};
  19987. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19988. ASSERT_TRUE(res2);
  19989. EXPECT_EQ(200, res2->status); // Should not match
  19990. // Test 2: Long string followed by wildcard
  19991. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19992. // string)
  19993. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19994. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19995. ASSERT_TRUE(res3);
  19996. EXPECT_EQ(304, res3->status); // Should match on "*"
  19997. // Test 3: Wildcard followed by long string
  19998. // Should match on "*" immediately and return 304
  19999. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20000. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20001. ASSERT_TRUE(res4);
  20002. EXPECT_EQ(304, res4->status); // Should match on "*"
  20003. // Test 4: Multiple long non-matching values
  20004. // Should NOT match and return 200 (test that all comparisons are safe)
  20005. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20006. "W/\"second-long-non-matching-value\", "
  20007. "W/\"third-long-non-matching-value\""}};
  20008. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20009. ASSERT_TRUE(res5);
  20010. EXPECT_EQ(200, res5->status); // Should not match
  20011. // Test 5: Single character that is not "*" (edge case)
  20012. Headers h5 = {{"If-None-Match", "X"}};
  20013. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20014. ASSERT_TRUE(res6);
  20015. EXPECT_EQ(200, res6->status); // Should not match
  20016. svr.stop();
  20017. t.join();
  20018. std::remove(fname);
  20019. }
  20020. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20021. using namespace httplib;
  20022. // Create a test file
  20023. const char *fname = "ims_testfile.txt";
  20024. const char *content = "if-modified-since-test";
  20025. {
  20026. std::ofstream ofs(fname);
  20027. ofs << content;
  20028. ASSERT_TRUE(ofs.good());
  20029. }
  20030. Server svr;
  20031. svr.set_mount_point("/static", ".");
  20032. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20033. svr.wait_until_ready();
  20034. Client cli(HOST, PORT);
  20035. // First request: should get 200 with Last-Modified header
  20036. auto res1 = cli.Get("/static/ims_testfile.txt");
  20037. ASSERT_TRUE(res1);
  20038. ASSERT_EQ(200, res1->status);
  20039. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20040. std::string last_modified = res1->get_header_value("Last-Modified");
  20041. EXPECT_FALSE(last_modified.empty());
  20042. // If-Modified-Since with same time: expect 304
  20043. Headers h2 = {{"If-Modified-Since", last_modified}};
  20044. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20045. ASSERT_TRUE(res2);
  20046. EXPECT_EQ(304, res2->status);
  20047. // If-Modified-Since with future time: expect 304
  20048. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20049. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20050. ASSERT_TRUE(res3);
  20051. EXPECT_EQ(304, res3->status);
  20052. // If-Modified-Since with past time: expect 200
  20053. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20054. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20055. ASSERT_TRUE(res4);
  20056. EXPECT_EQ(200, res4->status);
  20057. // If-None-Match takes precedence over If-Modified-Since
  20058. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20059. ASSERT_TRUE(res1->has_header("ETag"));
  20060. std::string etag = res1->get_header_value("ETag");
  20061. Headers h5 = {{"If-None-Match", etag},
  20062. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20063. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20064. ASSERT_TRUE(res5);
  20065. EXPECT_EQ(304, res5->status);
  20066. svr.stop();
  20067. t.join();
  20068. std::remove(fname);
  20069. }
  20070. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20071. using namespace httplib;
  20072. Server svr;
  20073. // Endpoint that returns compressible content
  20074. svr.Get("/compressible", [](const Request &, Response &res) {
  20075. // Return a large enough body to trigger compression
  20076. std::string body(1000, 'a');
  20077. res.set_content(body, "text/plain");
  20078. });
  20079. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20080. svr.wait_until_ready();
  20081. Client cli(HOST, PORT);
  20082. // Request with gzip support: should get Vary header when compressed
  20083. cli.set_compress(true);
  20084. auto res1 = cli.Get("/compressible");
  20085. ASSERT_TRUE(res1);
  20086. EXPECT_EQ(200, res1->status);
  20087. // If Content-Encoding is set, Vary should also be set
  20088. if (res1->has_header("Content-Encoding")) {
  20089. EXPECT_TRUE(res1->has_header("Vary"));
  20090. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20091. }
  20092. // Request without Accept-Encoding header: should not have compression
  20093. Headers h_no_compress;
  20094. auto res2 = cli.Get("/compressible", h_no_compress);
  20095. ASSERT_TRUE(res2);
  20096. EXPECT_EQ(200, res2->status);
  20097. // Verify Vary header is present when compression is applied
  20098. // (the exact behavior depends on server configuration)
  20099. svr.stop();
  20100. t.join();
  20101. }
  20102. TEST(ETagTest, IfRangeWithETag) {
  20103. using namespace httplib;
  20104. // Create a test file with known content
  20105. const char *fname = "if_range_testfile.txt";
  20106. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20107. {
  20108. std::ofstream ofs(fname);
  20109. ofs << content;
  20110. ASSERT_TRUE(ofs.good());
  20111. }
  20112. Server svr;
  20113. svr.set_mount_point("/static", ".");
  20114. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20115. svr.wait_until_ready();
  20116. Client cli(HOST, PORT);
  20117. // First request: get ETag
  20118. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20119. ASSERT_TRUE(res1);
  20120. ASSERT_EQ(200, res1->status);
  20121. ASSERT_TRUE(res1->has_header("ETag"));
  20122. std::string etag = res1->get_header_value("ETag");
  20123. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20124. // Since our server generates weak ETags (W/"..."), If-Range with our
  20125. // ETag should NOT result in partial content - it should return full content.
  20126. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20127. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20128. ASSERT_TRUE(res2);
  20129. // Weak ETag in If-Range -> full content (200), not partial (206)
  20130. EXPECT_EQ(200, res2->status);
  20131. EXPECT_EQ(content, res2->body);
  20132. EXPECT_FALSE(res2->has_header("Content-Range"));
  20133. // Range request with non-matching If-Range (ETag): should get 200 (full
  20134. // content)
  20135. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20136. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20137. ASSERT_TRUE(res3);
  20138. EXPECT_EQ(200, res3->status);
  20139. EXPECT_EQ(content, res3->body);
  20140. EXPECT_FALSE(res3->has_header("Content-Range"));
  20141. // Range request with strong ETag (hypothetical - our server doesn't generate
  20142. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20143. // should return full content)
  20144. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20145. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20146. ASSERT_TRUE(res4);
  20147. EXPECT_EQ(200, res4->status);
  20148. EXPECT_EQ(content, res4->body);
  20149. EXPECT_FALSE(res4->has_header("Content-Range"));
  20150. svr.stop();
  20151. t.join();
  20152. std::remove(fname);
  20153. }
  20154. TEST(ETagTest, IfRangeWithDate) {
  20155. using namespace httplib;
  20156. // Create a test file
  20157. const char *fname = "if_range_date_testfile.txt";
  20158. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20159. {
  20160. std::ofstream ofs(fname);
  20161. ofs << content;
  20162. ASSERT_TRUE(ofs.good());
  20163. }
  20164. Server svr;
  20165. svr.set_mount_point("/static", ".");
  20166. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20167. svr.wait_until_ready();
  20168. Client cli(HOST, PORT);
  20169. // First request: get Last-Modified
  20170. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20171. ASSERT_TRUE(res1);
  20172. ASSERT_EQ(200, res1->status);
  20173. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20174. std::string last_modified = res1->get_header_value("Last-Modified");
  20175. // Range request with matching If-Range (date): should get 206
  20176. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20177. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20178. ASSERT_TRUE(res2);
  20179. EXPECT_EQ(206, res2->status);
  20180. EXPECT_EQ("FGHIJ", res2->body);
  20181. // Range request with old If-Range date: should get 200 (full content)
  20182. Headers h3 = {{"Range", "bytes=5-9"},
  20183. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20184. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20185. ASSERT_TRUE(res3);
  20186. EXPECT_EQ(200, res3->status);
  20187. EXPECT_EQ(content, res3->body);
  20188. // Range request with future If-Range date: should get 206
  20189. Headers h4 = {{"Range", "bytes=0-4"},
  20190. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20191. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20192. ASSERT_TRUE(res4);
  20193. EXPECT_EQ(206, res4->status);
  20194. EXPECT_EQ("ABCDE", res4->body);
  20195. svr.stop();
  20196. t.join();
  20197. std::remove(fname);
  20198. }
  20199. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20200. using namespace httplib;
  20201. const char *fname = "etag_malformed.txt";
  20202. const char *content = "malformed-etag";
  20203. {
  20204. std::ofstream ofs(fname);
  20205. ofs << content;
  20206. ASSERT_TRUE(ofs.good());
  20207. }
  20208. Server svr;
  20209. svr.set_mount_point("/static", ".");
  20210. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20211. svr.wait_until_ready();
  20212. Client cli(HOST, PORT);
  20213. // baseline: should get 200 and an ETag
  20214. auto res1 = cli.Get("/static/etag_malformed.txt");
  20215. ASSERT_TRUE(res1);
  20216. ASSERT_EQ(200, res1->status);
  20217. ASSERT_TRUE(res1->has_header("ETag"));
  20218. // Malformed ETag value (missing quotes) should be treated as non-matching
  20219. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20220. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20221. ASSERT_TRUE(res_bad);
  20222. EXPECT_EQ(200, res_bad->status);
  20223. // Whitespace-only header value should be considered invalid / non-matching
  20224. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20225. "Host: localhost\r\n"
  20226. "If-None-Match: \r\n"
  20227. "Connection: close\r\n"
  20228. "\r\n";
  20229. std::string out;
  20230. ASSERT_TRUE(send_request(5, raw_req, &out));
  20231. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20232. svr.stop();
  20233. t.join();
  20234. std::remove(fname);
  20235. }
  20236. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20237. using namespace httplib;
  20238. const char *fname = "ims_invalid_format.txt";
  20239. const char *content = "ims-bad-format";
  20240. {
  20241. std::ofstream ofs(fname);
  20242. ofs << content;
  20243. ASSERT_TRUE(ofs.good());
  20244. }
  20245. Server svr;
  20246. svr.set_mount_point("/static", ".");
  20247. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20248. svr.wait_until_ready();
  20249. Client cli(HOST, PORT);
  20250. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20251. ASSERT_TRUE(res1);
  20252. ASSERT_EQ(200, res1->status);
  20253. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20254. // If-Modified-Since with invalid format should not result in 304
  20255. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20256. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20257. ASSERT_TRUE(res_bad);
  20258. EXPECT_EQ(200, res_bad->status);
  20259. // If-Range with invalid date format should be treated as mismatch -> full
  20260. // content (200)
  20261. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20262. {"If-Range", "invalid-date"}};
  20263. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20264. ASSERT_TRUE(res_ifrange);
  20265. EXPECT_EQ(200, res_ifrange->status);
  20266. svr.stop();
  20267. t.join();
  20268. std::remove(fname);
  20269. }
  20270. TEST(ETagTest, IfRangeWithMalformedETag) {
  20271. using namespace httplib;
  20272. const char *fname = "ifrange_malformed.txt";
  20273. const std::string content = "0123456789";
  20274. {
  20275. std::ofstream ofs(fname);
  20276. ofs << content;
  20277. ASSERT_TRUE(ofs.good());
  20278. }
  20279. Server svr;
  20280. svr.set_mount_point("/static", ".");
  20281. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20282. svr.wait_until_ready();
  20283. Client cli(HOST, PORT);
  20284. // First request: get ETag
  20285. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20286. ASSERT_TRUE(res1);
  20287. ASSERT_EQ(200, res1->status);
  20288. ASSERT_TRUE(res1->has_header("ETag"));
  20289. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20290. // full content (200)
  20291. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20292. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20293. ASSERT_TRUE(res2);
  20294. EXPECT_EQ(200, res2->status);
  20295. EXPECT_EQ(content, res2->body);
  20296. svr.stop();
  20297. t.join();
  20298. std::remove(fname);
  20299. }
  20300. TEST(ETagTest, ExtremeLargeDateValues) {
  20301. using namespace httplib;
  20302. const char *fname = "ims_extreme_date.txt";
  20303. const char *content = "ims-extreme-date";
  20304. {
  20305. std::ofstream ofs(fname);
  20306. ofs << content;
  20307. ASSERT_TRUE(ofs.good());
  20308. }
  20309. Server svr;
  20310. svr.set_mount_point("/static", ".");
  20311. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20312. svr.wait_until_ready();
  20313. Client cli(HOST, PORT);
  20314. auto res1 = cli.Get(std::string("/static/") + fname);
  20315. ASSERT_TRUE(res1);
  20316. ASSERT_EQ(200, res1->status);
  20317. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20318. // Extremely large year that may overflow date parsing routines.
  20319. Headers h_large_date = {
  20320. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20321. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20322. ASSERT_TRUE(res_bad);
  20323. // Expect server to treat this as invalid/mismatch and return full content
  20324. EXPECT_EQ(200, res_bad->status);
  20325. // If-Range with extremely large date should be treated as mismatch -> full
  20326. // content (200)
  20327. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20328. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20329. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20330. ASSERT_TRUE(res_ifrange);
  20331. EXPECT_EQ(200, res_ifrange->status);
  20332. svr.stop();
  20333. t.join();
  20334. std::remove(fname);
  20335. }
  20336. TEST(ETagTest, NegativeFileModificationTime) {
  20337. using namespace httplib;
  20338. const char *fname = "ims_negative_mtime.txt";
  20339. const std::string content = "negative-mtime";
  20340. {
  20341. std::ofstream ofs(fname);
  20342. ofs << content;
  20343. ASSERT_TRUE(ofs.good());
  20344. }
  20345. // Try to set file mtime to a negative value. This may fail on some
  20346. // platforms/filesystems; if it fails, the test will still verify server
  20347. // behaves safely by performing a regular conditional request.
  20348. #if defined(__APPLE__) || defined(__linux__)
  20349. bool set_negative = false;
  20350. do {
  20351. struct timeval times[2];
  20352. // access time: now
  20353. times[0].tv_sec = time(nullptr);
  20354. times[0].tv_usec = 0;
  20355. // modification time: negative (e.g., -1)
  20356. times[1].tv_sec = -1;
  20357. times[1].tv_usec = 0;
  20358. if (utimes(fname, times) == 0) { set_negative = true; }
  20359. } while (0);
  20360. #else
  20361. bool set_negative = false;
  20362. #endif
  20363. Server svr;
  20364. svr.set_mount_point("/static", ".");
  20365. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20366. svr.wait_until_ready();
  20367. Client cli(HOST, PORT);
  20368. auto res1 = cli.Get(std::string("/static/") + fname);
  20369. ASSERT_TRUE(res1);
  20370. ASSERT_EQ(200, res1->status);
  20371. bool has_last_modified = res1->has_header("Last-Modified");
  20372. std::string last_modified;
  20373. if (has_last_modified) {
  20374. last_modified = res1->get_header_value("Last-Modified");
  20375. }
  20376. if (set_negative) {
  20377. // If we successfully set a negative mtime, ensure server returns a
  20378. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20379. // with an old date and ensure server handles it without crash.
  20380. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20381. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20382. ASSERT_TRUE(res2);
  20383. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20384. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20385. } else {
  20386. // Could not set negative mtime on this platform; fall back to verifying
  20387. // that normal invalid/malformed dates are treated safely (non-304).
  20388. Headers h_bad_date = {
  20389. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20390. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20391. ASSERT_TRUE(res_bad);
  20392. EXPECT_EQ(200, res_bad->status);
  20393. }
  20394. svr.stop();
  20395. t.join();
  20396. std::remove(fname);
  20397. }
  20398. //==============================================================================
  20399. // Integration Tests with Server
  20400. //==============================================================================
  20401. class SSEIntegrationTest : public ::testing::Test {
  20402. protected:
  20403. void SetUp() override {
  20404. stop_server_.store(false);
  20405. events_.clear();
  20406. server_ = httplib::detail::make_unique<Server>();
  20407. setup_server();
  20408. start_server();
  20409. }
  20410. void TearDown() override {
  20411. stop_server_.store(true);
  20412. event_cv_.notify_all();
  20413. server_->stop();
  20414. if (server_thread_.joinable()) { server_thread_.join(); }
  20415. }
  20416. void setup_server() {
  20417. // Simple SSE endpoint
  20418. server_->Get("/events", [this](const Request &req, Response &res) {
  20419. auto last_id = req.get_header_value("Last-Event-ID");
  20420. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20421. res.set_chunked_content_provider(
  20422. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20423. std::unique_lock<std::mutex> lock(event_mutex_);
  20424. if (event_cv_.wait_for(
  20425. lock, std::chrono::milliseconds(200), [this] {
  20426. return !events_.empty() || stop_server_.load();
  20427. })) {
  20428. if (stop_server_.load()) { return false; }
  20429. if (!events_.empty()) {
  20430. std::string event = events_.front();
  20431. events_.erase(events_.begin());
  20432. sink.write(event.data(), event.size());
  20433. return true;
  20434. }
  20435. }
  20436. return !stop_server_.load();
  20437. });
  20438. });
  20439. // Endpoint that returns error
  20440. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20441. res.status = 500;
  20442. res.set_content("Internal Server Error", "text/plain");
  20443. });
  20444. // Endpoint for custom event types
  20445. server_->Get("/custom-events", [](const Request &, Response &res) {
  20446. res.set_chunked_content_provider(
  20447. "text/event-stream", [](size_t offset, DataSink &sink) {
  20448. if (offset == 0) {
  20449. std::string event = "event: update\ndata: updated\n\n"
  20450. "event: delete\ndata: deleted\n\n";
  20451. sink.write(event.data(), event.size());
  20452. }
  20453. return false; // End stream after sending
  20454. });
  20455. });
  20456. }
  20457. void start_server() {
  20458. port_ = server_->bind_to_any_port(HOST);
  20459. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20460. // Wait for server to start
  20461. while (!server_->is_running()) {
  20462. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20463. }
  20464. }
  20465. int get_port() const { return port_; }
  20466. void send_event(const std::string &event) {
  20467. std::lock_guard<std::mutex> lock(event_mutex_);
  20468. events_.push_back(event);
  20469. event_cv_.notify_all();
  20470. }
  20471. std::unique_ptr<Server> server_;
  20472. std::thread server_thread_;
  20473. std::mutex event_mutex_;
  20474. std::condition_variable event_cv_;
  20475. std::vector<std::string> events_;
  20476. std::atomic<bool> stop_server_{false};
  20477. std::string last_received_event_id_;
  20478. int port_ = 0;
  20479. };
  20480. //==============================================================================
  20481. // SSE Parsing Tests
  20482. //==============================================================================
  20483. class SSEParsingTest : public SSEIntegrationTest {
  20484. protected:
  20485. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20486. // A trailing sentinel event tells when the whole stream has been parsed.
  20487. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20488. auto body = stream + "event: end\ndata: end\n\n";
  20489. server_->Get("/parse", [body](const Request &, Response &res) {
  20490. res.set_content(body, "text/event-stream");
  20491. });
  20492. return collect("/parse");
  20493. }
  20494. // Runs SSEClient against path until an "end" event arrives and returns the
  20495. // messages dispatched before it
  20496. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20497. Client client(HOST, get_port());
  20498. sse::SSEClient sse(client, path);
  20499. std::mutex mutex;
  20500. std::condition_variable cv;
  20501. std::vector<sse::SSEMessage> messages;
  20502. auto done = false;
  20503. sse.on_message([&](const sse::SSEMessage &msg) {
  20504. std::lock_guard<std::mutex> lock(mutex);
  20505. // Ignore a replay from a reconnect that races with stop()
  20506. if (!done) { messages.push_back(msg); }
  20507. });
  20508. sse.on_event("end", [&](const sse::SSEMessage &) {
  20509. std::lock_guard<std::mutex> lock(mutex);
  20510. done = true;
  20511. cv.notify_all();
  20512. });
  20513. sse.set_reconnect_interval(100);
  20514. sse.start_async();
  20515. {
  20516. std::unique_lock<std::mutex> lock(mutex);
  20517. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20518. }
  20519. sse.stop();
  20520. EXPECT_TRUE(done);
  20521. return messages;
  20522. }
  20523. };
  20524. TEST_F(SSEParsingTest, SingleLineData) {
  20525. auto msgs = parse("data: hello\n\n");
  20526. ASSERT_EQ(msgs.size(), 1u);
  20527. EXPECT_EQ(msgs[0].data, "hello");
  20528. EXPECT_EQ(msgs[0].event, "message");
  20529. }
  20530. TEST_F(SSEParsingTest, MultiLineData) {
  20531. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20532. ASSERT_EQ(msgs.size(), 1u);
  20533. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20534. }
  20535. TEST_F(SSEParsingTest, CustomEventType) {
  20536. auto msgs = parse("event: update\ndata: payload\n\n");
  20537. ASSERT_EQ(msgs.size(), 1u);
  20538. EXPECT_EQ(msgs[0].event, "update");
  20539. EXPECT_EQ(msgs[0].data, "payload");
  20540. }
  20541. TEST_F(SSEParsingTest, EventIdHandling) {
  20542. auto msgs = parse("id: 12345\ndata: test\n\n");
  20543. ASSERT_EQ(msgs.size(), 1u);
  20544. EXPECT_EQ(msgs[0].id, "12345");
  20545. }
  20546. TEST_F(SSEParsingTest, EmptyEventId) {
  20547. auto msgs = parse("id:\ndata: test\n\n");
  20548. ASSERT_EQ(msgs.size(), 1u);
  20549. EXPECT_EQ(msgs[0].id, "");
  20550. }
  20551. TEST_F(SSEParsingTest, CommentsIgnored) {
  20552. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20553. ASSERT_EQ(msgs.size(), 1u);
  20554. EXPECT_EQ(msgs[0].data, "hello");
  20555. EXPECT_EQ(msgs[0].event, "message");
  20556. }
  20557. TEST_F(SSEParsingTest, ColonInValue) {
  20558. auto msgs = parse("data: hello:world:test\n\n");
  20559. ASSERT_EQ(msgs.size(), 1u);
  20560. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20561. }
  20562. TEST_F(SSEParsingTest, FieldNameOnly) {
  20563. // A line without a colon is a field name with an empty value
  20564. auto msgs = parse("data\n\n");
  20565. ASSERT_EQ(msgs.size(), 1u);
  20566. EXPECT_EQ(msgs[0].data, "");
  20567. }
  20568. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20569. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20570. ASSERT_EQ(msgs.size(), 1u);
  20571. EXPECT_EQ(msgs[0].event, "update");
  20572. EXPECT_EQ(msgs[0].data, "hello");
  20573. }
  20574. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20575. auto msgs = parse("data\r\n\r\n");
  20576. ASSERT_EQ(msgs.size(), 1u);
  20577. EXPECT_EQ(msgs[0].data, "");
  20578. }
  20579. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20580. auto msgs = parse("event: update\rdata: hello\r\r");
  20581. ASSERT_EQ(msgs.size(), 1u);
  20582. EXPECT_EQ(msgs[0].event, "update");
  20583. EXPECT_EQ(msgs[0].data, "hello");
  20584. }
  20585. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20586. // Chunk boundaries fall inside every \r\n and right before the first one
  20587. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20588. "\n\r", "\nevent: end\ndata: end\n\n"};
  20589. server_->Get("/split", [chunks](const Request &, Response &res) {
  20590. auto i = std::make_shared<size_t>(0);
  20591. res.set_chunked_content_provider(
  20592. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20593. if (*i == chunks.size()) {
  20594. sink.done();
  20595. } else {
  20596. sink.write(chunks[*i].data(), chunks[*i].size());
  20597. (*i)++;
  20598. }
  20599. return true;
  20600. });
  20601. });
  20602. auto msgs = collect("/split");
  20603. ASSERT_EQ(msgs.size(), 1u);
  20604. EXPECT_EQ(msgs[0].event, "update");
  20605. EXPECT_EQ(msgs[0].data, "hello");
  20606. }
  20607. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20608. // Only a BOM at the start of the stream is ignored
  20609. auto msgs = parse("\xEF\xBB\xBF"
  20610. "data: first\n\n"
  20611. "\xEF\xBB\xBF"
  20612. "data: second\n\n");
  20613. ASSERT_EQ(msgs.size(), 1u);
  20614. EXPECT_EQ(msgs[0].data, "first");
  20615. }
  20616. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20617. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20618. ASSERT_EQ(msgs.size(), 1u);
  20619. EXPECT_EQ(msgs[0].data, "hello");
  20620. EXPECT_EQ(msgs[0].event, "message");
  20621. }
  20622. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20623. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20624. ASSERT_EQ(msgs.size(), 2u);
  20625. EXPECT_EQ(msgs[0].data, "hello");
  20626. EXPECT_EQ(msgs[1].data, "hello");
  20627. }
  20628. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20629. // An event without data is not dispatched, and its type must not leak
  20630. // into the next event
  20631. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20632. ASSERT_EQ(msgs.size(), 1u);
  20633. EXPECT_EQ(msgs[0].event, "message");
  20634. EXPECT_EQ(msgs[0].data, "hello");
  20635. }
  20636. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20637. // The first connection sends only an id; the second echoes back the
  20638. // Last-Event-ID it was reconnected with
  20639. std::atomic<int> connection_count{0};
  20640. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20641. if (connection_count++ == 0) {
  20642. res.set_content("id: 42\n\n", "text/event-stream");
  20643. } else {
  20644. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20645. "\n\nevent: end\ndata: end\n\n",
  20646. "text/event-stream");
  20647. }
  20648. });
  20649. auto msgs = collect("/id-only");
  20650. ASSERT_EQ(msgs.size(), 1u);
  20651. EXPECT_EQ(msgs[0].data, "42");
  20652. }
  20653. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20654. // The first connection sets an id and then clears it with an empty one; the
  20655. // second reports whether it was reconnected with a Last-Event-ID
  20656. std::atomic<int> connection_count{0};
  20657. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20658. if (connection_count++ == 0) {
  20659. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20660. "text/event-stream");
  20661. } else {
  20662. res.set_content(
  20663. std::string("data: ") +
  20664. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20665. "\n\nevent: end\ndata: end\n\n",
  20666. "text/event-stream");
  20667. }
  20668. });
  20669. auto msgs = collect("/id-clear");
  20670. ASSERT_EQ(msgs.size(), 3u);
  20671. EXPECT_EQ(msgs[0].id, "1");
  20672. EXPECT_EQ(msgs[1].id, "");
  20673. EXPECT_EQ(msgs[2].data, "not sent");
  20674. }
  20675. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20676. // The first connection sets an id and then sends ids that cannot be carried
  20677. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20678. // with
  20679. std::atomic<int> connection_count{0};
  20680. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20681. if (connection_count++ == 0) {
  20682. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20683. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20684. "text/event-stream");
  20685. } else {
  20686. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20687. "\n\nevent: end\ndata: end\n\n",
  20688. "text/event-stream");
  20689. }
  20690. });
  20691. auto msgs = collect("/id-unsendable");
  20692. ASSERT_EQ(msgs.size(), 1u);
  20693. EXPECT_EQ(msgs[0].data, "42");
  20694. }
  20695. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20696. auto msgs = parse("event: notification\nid: evt-42\n"
  20697. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20698. ASSERT_EQ(msgs.size(), 1u);
  20699. EXPECT_EQ(msgs[0].event, "notification");
  20700. EXPECT_EQ(msgs[0].id, "evt-42");
  20701. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20702. }
  20703. TEST(SSEMessageTest, Clear) {
  20704. sse::SSEMessage msg;
  20705. msg.event = "custom";
  20706. msg.data = "some data";
  20707. msg.id = "123";
  20708. msg.clear();
  20709. EXPECT_EQ(msg.event, "message");
  20710. EXPECT_EQ(msg.data, "");
  20711. EXPECT_EQ(msg.id, "");
  20712. }
  20713. //==============================================================================
  20714. // SSE Integration Tests
  20715. //==============================================================================
  20716. // Test: Successful connection and on_open callback
  20717. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20718. // Add a simple endpoint that sends one event and closes
  20719. server_->Get("/simple-event", [](const Request &, Response &res) {
  20720. res.set_chunked_content_provider(
  20721. "text/event-stream", [](size_t offset, DataSink &sink) {
  20722. if (offset == 0) {
  20723. std::string event = "data: hello\n\n";
  20724. sink.write(event.data(), event.size());
  20725. }
  20726. return false; // Close stream after sending
  20727. });
  20728. });
  20729. Client client("localhost", get_port());
  20730. sse::SSEClient sse(client, "/simple-event");
  20731. std::atomic<bool> open_called{false};
  20732. std::atomic<bool> message_received{false};
  20733. sse.on_open([&open_called]() { open_called.store(true); });
  20734. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20735. if (msg.data == "hello") { message_received.store(true); }
  20736. });
  20737. sse.set_reconnect_interval(100);
  20738. sse.set_max_reconnect_attempts(1);
  20739. // Start async
  20740. sse.start_async();
  20741. // Wait for message to be processed
  20742. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20743. sse.stop();
  20744. EXPECT_TRUE(open_called.load());
  20745. EXPECT_TRUE(message_received.load());
  20746. }
  20747. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20748. // A data line that never ends.
  20749. server_->Get("/endless-line", [](const Request &, Response &res) {
  20750. res.set_chunked_content_provider(
  20751. "text/event-stream", [](size_t offset, DataSink &sink) {
  20752. if (offset == 0) { sink.write("data: ", 6); }
  20753. std::string chunk(64 * 1024, 'A');
  20754. return sink.write(chunk.data(), chunk.size());
  20755. });
  20756. });
  20757. Client client("localhost", get_port());
  20758. sse::SSEClient sse(client, "/endless-line");
  20759. std::atomic<bool> too_long{false};
  20760. sse.on_error([&](Error err) {
  20761. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20762. });
  20763. sse.set_max_reconnect_attempts(1);
  20764. sse.start_async();
  20765. for (int i = 0; i < 500 && !too_long; i++) {
  20766. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20767. }
  20768. sse.stop();
  20769. EXPECT_TRUE(too_long);
  20770. }
  20771. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20772. // Far more in all than the client's payload limit below.
  20773. server_->Get("/many-events", [](const Request &, Response &res) {
  20774. res.set_chunked_content_provider(
  20775. "text/event-stream", [](size_t offset, DataSink &sink) {
  20776. if (offset == 0) {
  20777. std::string events;
  20778. for (int i = 0; i < 1000; i++) {
  20779. events += "data: message\n\n";
  20780. }
  20781. sink.write(events.data(), events.size());
  20782. }
  20783. return false;
  20784. });
  20785. });
  20786. Client client("localhost", get_port());
  20787. client.set_payload_max_length(1024);
  20788. sse::SSEClient sse(client, "/many-events");
  20789. std::atomic<int> messages{0};
  20790. std::atomic<bool> too_large{false};
  20791. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20792. sse.on_error([&](Error err) {
  20793. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20794. });
  20795. sse.set_max_reconnect_attempts(1);
  20796. sse.start_async();
  20797. for (int i = 0; i < 500 && messages < 1000; i++) {
  20798. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20799. }
  20800. sse.stop();
  20801. EXPECT_GE(messages.load(), 1000);
  20802. EXPECT_FALSE(too_large);
  20803. }
  20804. // Test: on_message callback
  20805. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20806. // Endpoint that sends multiple events then closes
  20807. server_->Get("/multi-event", [](const Request &, Response &res) {
  20808. res.set_chunked_content_provider(
  20809. "text/event-stream", [](size_t offset, DataSink &sink) {
  20810. if (offset == 0) {
  20811. std::string events = "data: message1\n\ndata: message2\n\n";
  20812. sink.write(events.data(), events.size());
  20813. }
  20814. return false;
  20815. });
  20816. });
  20817. Client client("localhost", get_port());
  20818. sse::SSEClient sse(client, "/multi-event");
  20819. std::vector<std::string> received_messages;
  20820. std::mutex messages_mutex;
  20821. sse.on_message([&](const sse::SSEMessage &msg) {
  20822. std::lock_guard<std::mutex> lock(messages_mutex);
  20823. received_messages.push_back(msg.data);
  20824. });
  20825. sse.set_reconnect_interval(100);
  20826. sse.set_max_reconnect_attempts(1);
  20827. sse.start_async();
  20828. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20829. sse.stop();
  20830. std::lock_guard<std::mutex> lock(messages_mutex);
  20831. EXPECT_GE(received_messages.size(), 2u);
  20832. if (received_messages.size() >= 2) {
  20833. EXPECT_EQ(received_messages[0], "message1");
  20834. EXPECT_EQ(received_messages[1], "message2");
  20835. }
  20836. }
  20837. // Test: on_event for specific types
  20838. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20839. Client client("localhost", get_port());
  20840. sse::SSEClient sse(client, "/custom-events");
  20841. std::atomic<bool> update_received{false};
  20842. std::atomic<bool> delete_received{false};
  20843. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20844. if (msg.data == "updated") { update_received.store(true); }
  20845. });
  20846. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20847. if (msg.data == "deleted") { delete_received.store(true); }
  20848. });
  20849. sse.set_max_reconnect_attempts(1);
  20850. sse.start_async();
  20851. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20852. sse.stop();
  20853. EXPECT_TRUE(update_received.load());
  20854. EXPECT_TRUE(delete_received.load());
  20855. }
  20856. // Test: on_error callback on connection failure
  20857. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20858. // Connect to a non-existent port
  20859. Client client("localhost", 59999);
  20860. sse::SSEClient sse(client, "/events");
  20861. std::atomic<bool> error_called{false};
  20862. Error received_error = Error::Success;
  20863. sse.on_error([&](Error err) {
  20864. error_called.store(true);
  20865. received_error = err;
  20866. });
  20867. sse.set_reconnect_interval(50);
  20868. sse.set_max_reconnect_attempts(1);
  20869. sse.start_async();
  20870. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20871. sse.stop();
  20872. EXPECT_TRUE(error_called.load());
  20873. EXPECT_NE(received_error, Error::Success);
  20874. }
  20875. // Test: Last-Event-ID header sent on reconnect
  20876. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20877. // Endpoint that sends event with ID
  20878. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20879. res.set_chunked_content_provider(
  20880. "text/event-stream", [](size_t offset, DataSink &sink) {
  20881. if (offset == 0) {
  20882. std::string event = "id: evt-123\ndata: test\n\n";
  20883. sink.write(event.data(), event.size());
  20884. }
  20885. return false;
  20886. });
  20887. });
  20888. Client client("localhost", get_port());
  20889. sse::SSEClient sse(client, "/event-with-id");
  20890. std::atomic<bool> id_received{false};
  20891. sse.on_message([&](const sse::SSEMessage &msg) {
  20892. if (!msg.id.empty()) { id_received.store(true); }
  20893. });
  20894. sse.set_reconnect_interval(100);
  20895. sse.set_max_reconnect_attempts(1);
  20896. sse.start_async();
  20897. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20898. sse.stop();
  20899. EXPECT_TRUE(id_received.load());
  20900. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20901. }
  20902. // Test: Manual stop
  20903. TEST_F(SSEIntegrationTest, ManualStop) {
  20904. // Endpoint that sends one event and stays open briefly
  20905. std::atomic<bool> handler_running{true};
  20906. server_->Get("/stay-open", [&handler_running](const Request &,
  20907. Response &res) {
  20908. res.set_chunked_content_provider(
  20909. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20910. if (offset == 0) {
  20911. std::string event = "data: connected\n\n";
  20912. sink.write(event.data(), event.size());
  20913. }
  20914. // Keep connection open while handler_running is true
  20915. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20916. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20917. }
  20918. return false;
  20919. });
  20920. });
  20921. Client client("localhost", get_port());
  20922. sse::SSEClient sse(client, "/stay-open");
  20923. std::atomic<bool> connected{false};
  20924. sse.on_open([&connected]() { connected.store(true); });
  20925. sse.set_reconnect_interval(100);
  20926. sse.set_max_reconnect_attempts(1);
  20927. sse.start_async();
  20928. // Wait for connection to establish
  20929. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20930. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20931. }
  20932. EXPECT_TRUE(connected.load());
  20933. EXPECT_TRUE(sse.is_connected());
  20934. // Signal handler to stop
  20935. handler_running.store(false);
  20936. // Stop SSE client
  20937. sse.stop();
  20938. EXPECT_FALSE(sse.is_connected());
  20939. }
  20940. // Test: SSEClient with custom headers
  20941. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20942. // Setup a server endpoint that checks for custom header
  20943. std::atomic<bool> header_received{false};
  20944. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20945. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20946. header_received.store(true);
  20947. }
  20948. res.set_chunked_content_provider("text/event-stream",
  20949. [](size_t, DataSink &) { return false; });
  20950. });
  20951. Client client("localhost", get_port());
  20952. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20953. sse::SSEClient sse(client, "/header-check", headers);
  20954. sse.set_max_reconnect_attempts(1);
  20955. sse.start_async();
  20956. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20957. sse.stop();
  20958. EXPECT_TRUE(header_received.load());
  20959. }
  20960. // Test: Reconnect interval configuration
  20961. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20962. Client client("localhost", get_port());
  20963. sse::SSEClient sse(client, "/events");
  20964. auto &result = sse.set_reconnect_interval(500);
  20965. // Builder pattern should return reference to self
  20966. EXPECT_EQ(&result, &sse);
  20967. }
  20968. // Test: Max reconnect attempts
  20969. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20970. // Connect to non-existent port to force reconnects
  20971. Client client("localhost", 59998);
  20972. sse::SSEClient sse(client, "/events");
  20973. std::atomic<int> error_count{0};
  20974. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20975. sse.set_reconnect_interval(50);
  20976. sse.set_max_reconnect_attempts(2);
  20977. auto start = std::chrono::steady_clock::now();
  20978. sse.start(); // Blocking call
  20979. auto end = std::chrono::steady_clock::now();
  20980. // Should have stopped after 2 failed attempts
  20981. EXPECT_GE(error_count.load(), 2);
  20982. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20983. auto duration =
  20984. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20985. #ifdef _WIN32
  20986. // Windows is much slower for socket connection failures
  20987. EXPECT_LT(duration.count(), 7000);
  20988. #else
  20989. EXPECT_LT(duration.count(), 1000);
  20990. #endif
  20991. }
  20992. // Test: Multi-line data in integration
  20993. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20994. // Endpoint with multi-line data
  20995. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20996. res.set_chunked_content_provider(
  20997. "text/event-stream", [](size_t offset, DataSink &sink) {
  20998. if (offset == 0) {
  20999. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21000. sink.write(event.data(), event.size());
  21001. }
  21002. return false;
  21003. });
  21004. });
  21005. Client client("localhost", get_port());
  21006. sse::SSEClient sse(client, "/multiline-data");
  21007. std::string received_data;
  21008. std::mutex data_mutex;
  21009. sse.on_message([&](const sse::SSEMessage &msg) {
  21010. std::lock_guard<std::mutex> lock(data_mutex);
  21011. received_data = msg.data;
  21012. });
  21013. sse.set_reconnect_interval(100);
  21014. sse.set_max_reconnect_attempts(1);
  21015. sse.start_async();
  21016. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21017. sse.stop();
  21018. std::lock_guard<std::mutex> lock(data_mutex);
  21019. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21020. }
  21021. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21022. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21023. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21024. DataSink &sink) {
  21025. if (offset == 0) {
  21026. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21027. sink.write(events.data(), events.size());
  21028. }
  21029. return false;
  21030. });
  21031. });
  21032. Client client("localhost", get_port());
  21033. sse::SSEClient sse(client, "/empty-data-lines");
  21034. std::mutex mutex;
  21035. std::condition_variable cv;
  21036. std::vector<std::string> received;
  21037. sse.on_message([&](const sse::SSEMessage &msg) {
  21038. std::lock_guard<std::mutex> lock(mutex);
  21039. received.push_back(msg.data);
  21040. cv.notify_all();
  21041. });
  21042. sse.set_max_reconnect_attempts(1);
  21043. sse.start_async();
  21044. {
  21045. std::unique_lock<std::mutex> lock(mutex);
  21046. cv.wait_for(lock, std::chrono::seconds(2),
  21047. [&] { return received.size() >= 3; });
  21048. }
  21049. sse.stop();
  21050. ASSERT_GE(received.size(), 3u);
  21051. EXPECT_EQ(received[0], "");
  21052. EXPECT_EQ(received[1], "\nhello");
  21053. EXPECT_EQ(received[2], "");
  21054. }
  21055. // Test: Auto-reconnect after server disconnection
  21056. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21057. std::atomic<int> connection_count{0};
  21058. std::atomic<int> message_count{0};
  21059. // Endpoint that sends one event and closes, forcing reconnect
  21060. server_->Get("/reconnect-test",
  21061. [&connection_count](const Request &, Response &res) {
  21062. connection_count.fetch_add(1);
  21063. res.set_chunked_content_provider(
  21064. "text/event-stream", [](size_t offset, DataSink &sink) {
  21065. if (offset == 0) {
  21066. std::string event = "data: hello\n\n";
  21067. sink.write(event.data(), event.size());
  21068. }
  21069. return false; // Close connection after sending
  21070. });
  21071. });
  21072. Client client("localhost", get_port());
  21073. sse::SSEClient sse(client, "/reconnect-test");
  21074. sse.on_message([&message_count](const sse::SSEMessage &) {
  21075. message_count.fetch_add(1);
  21076. });
  21077. sse.set_reconnect_interval(100);
  21078. sse.set_max_reconnect_attempts(3);
  21079. sse.start_async();
  21080. // Wait long enough for multiple reconnects
  21081. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21082. sse.stop();
  21083. // Should have connected multiple times (initial + reconnects)
  21084. EXPECT_GE(connection_count.load(), 2);
  21085. // Should have received messages from multiple connections
  21086. EXPECT_GE(message_count.load(), 2);
  21087. }
  21088. // Test: A retry field that is not all ASCII digits is ignored
  21089. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21090. std::atomic<int> connection_count{0};
  21091. server_->Get("/bad-retry",
  21092. [&connection_count](const Request &, Response &res) {
  21093. connection_count.fetch_add(1);
  21094. res.set_chunked_content_provider(
  21095. "text/event-stream", [](size_t offset, DataSink &sink) {
  21096. if (offset == 0) {
  21097. std::string event = "retry: -1\ndata: hello\n\n";
  21098. sink.write(event.data(), event.size());
  21099. }
  21100. return false;
  21101. });
  21102. });
  21103. Client client("localhost", get_port());
  21104. sse::SSEClient sse(client, "/bad-retry");
  21105. sse.set_reconnect_interval(10000);
  21106. sse.start_async();
  21107. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21108. sse.stop();
  21109. EXPECT_EQ(connection_count.load(), 1);
  21110. }
  21111. // Test: A retry field of all ASCII digits sets the reconnection time
  21112. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21113. std::mutex mutex;
  21114. std::condition_variable cv;
  21115. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21116. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21117. {
  21118. std::lock_guard<std::mutex> lock(mutex);
  21119. connected_at.push_back(std::chrono::steady_clock::now());
  21120. cv.notify_all();
  21121. }
  21122. res.set_chunked_content_provider(
  21123. "text/event-stream", [](size_t offset, DataSink &sink) {
  21124. if (offset == 0) {
  21125. std::string event = "retry: 0\ndata: hello\n\n";
  21126. sink.write(event.data(), event.size());
  21127. }
  21128. return false;
  21129. });
  21130. });
  21131. Client client("localhost", get_port());
  21132. sse::SSEClient sse(client, "/zero-retry");
  21133. sse.set_reconnect_interval(10000);
  21134. sse.start_async();
  21135. {
  21136. std::unique_lock<std::mutex> lock(mutex);
  21137. cv.wait_for(lock, std::chrono::seconds(5),
  21138. [&] { return connected_at.size() >= 2; });
  21139. }
  21140. sse.stop();
  21141. // The server-supplied interval is applied, but never below 100ms, so
  21142. // "retry: 0" does not cause a busy reconnect loop
  21143. std::lock_guard<std::mutex> lock(mutex);
  21144. ASSERT_GE(connected_at.size(), 2u);
  21145. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21146. connected_at[1] - connected_at[0])
  21147. .count();
  21148. EXPECT_GE(interval_ms, 100);
  21149. }
  21150. // Test: Last-Event-ID sent on reconnect
  21151. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21152. std::atomic<int> connection_count{0};
  21153. std::vector<std::string> received_last_event_ids;
  21154. std::mutex id_mutex;
  21155. // Endpoint that checks Last-Event-ID header and sends event with ID
  21156. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21157. int conn = connection_count.fetch_add(1);
  21158. // Capture the Last-Event-ID header from each connection
  21159. {
  21160. std::lock_guard<std::mutex> lock(id_mutex);
  21161. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21162. }
  21163. res.set_chunked_content_provider(
  21164. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21165. if (offset == 0) {
  21166. std::string event =
  21167. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21168. sink.write(event.data(), event.size());
  21169. }
  21170. return false;
  21171. });
  21172. });
  21173. Client client("localhost", get_port());
  21174. sse::SSEClient sse(client, "/reconnect-with-id");
  21175. sse.set_reconnect_interval(100);
  21176. sse.set_max_reconnect_attempts(3);
  21177. sse.start_async();
  21178. // Wait for at least 2 connections
  21179. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21180. sse.stop();
  21181. // Verify behavior
  21182. std::lock_guard<std::mutex> lock(id_mutex);
  21183. EXPECT_GE(received_last_event_ids.size(), 2u);
  21184. // First connection should have no Last-Event-ID
  21185. if (!received_last_event_ids.empty()) {
  21186. EXPECT_EQ(received_last_event_ids[0], "");
  21187. }
  21188. // Second connection should have Last-Event-ID from first connection
  21189. if (received_last_event_ids.size() >= 2) {
  21190. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21191. }
  21192. }
  21193. // Test: set_headers updates headers used on reconnect
  21194. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21195. std::vector<std::string> received_tokens;
  21196. std::mutex token_mutex;
  21197. // Endpoint that captures Authorization header
  21198. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21199. {
  21200. std::lock_guard<std::mutex> lock(token_mutex);
  21201. received_tokens.push_back(req.get_header_value("Authorization"));
  21202. }
  21203. res.set_chunked_content_provider(
  21204. "text/event-stream", [](size_t offset, DataSink &sink) {
  21205. if (offset == 0) {
  21206. std::string event = "data: hello\n\n";
  21207. sink.write(event.data(), event.size());
  21208. }
  21209. return false; // Close connection to trigger reconnect
  21210. });
  21211. });
  21212. Client client("localhost", get_port());
  21213. Headers headers = {{"Authorization", "Bearer old-token"}};
  21214. sse::SSEClient sse(client, "/auth-check", headers);
  21215. // Update headers on each successful connection
  21216. sse.on_open(
  21217. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21218. sse.set_reconnect_interval(100);
  21219. sse.set_max_reconnect_attempts(3);
  21220. sse.start_async();
  21221. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21222. sse.stop();
  21223. std::lock_guard<std::mutex> lock(token_mutex);
  21224. ASSERT_GE(received_tokens.size(), 2u);
  21225. // First connection uses original header
  21226. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21227. // Second connection uses updated header from set_headers
  21228. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21229. }
  21230. // Test: 401 allows reconnection (so on_error can refresh headers)
  21231. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21232. std::atomic<int> connection_count{0};
  21233. // Endpoint: returns 401 on first attempt, 200 on second
  21234. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21235. int conn = connection_count.fetch_add(1);
  21236. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21237. res.status = StatusCode::Unauthorized_401;
  21238. res.set_content("Unauthorized", "text/plain");
  21239. return;
  21240. }
  21241. res.set_chunked_content_provider(
  21242. "text/event-stream", [](size_t offset, DataSink &sink) {
  21243. if (offset == 0) {
  21244. std::string event = "data: authenticated\n\n";
  21245. sink.write(event.data(), event.size());
  21246. }
  21247. return false;
  21248. });
  21249. });
  21250. Client client("localhost", get_port());
  21251. Headers headers = {{"Authorization", "Bearer expired"}};
  21252. sse::SSEClient sse(client, "/auth-retry", headers);
  21253. std::atomic<bool> message_received{false};
  21254. // Refresh token on error
  21255. sse.on_error(
  21256. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21257. sse.on_message([&](const sse::SSEMessage &msg) {
  21258. if (msg.data == "authenticated") { message_received.store(true); }
  21259. });
  21260. sse.set_reconnect_interval(100);
  21261. sse.set_max_reconnect_attempts(3);
  21262. sse.start_async();
  21263. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21264. sse.stop();
  21265. // Should have reconnected after 401 and succeeded with new token
  21266. EXPECT_GE(connection_count.load(), 2);
  21267. EXPECT_TRUE(message_received.load());
  21268. }
  21269. TEST(Issue2318Test, EmptyHostString) {
  21270. {
  21271. httplib::Client cli_empty("", PORT);
  21272. auto res = cli_empty.Get("/");
  21273. ASSERT_FALSE(res);
  21274. EXPECT_EQ(httplib::Error::Connection, res.error());
  21275. }
  21276. {
  21277. httplib::Client cli(" ", PORT);
  21278. auto res = cli.Get("/");
  21279. ASSERT_FALSE(res);
  21280. EXPECT_EQ(httplib::Error::Connection, res.error());
  21281. }
  21282. }
  21283. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21284. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21285. Server svr;
  21286. // Set a small payload limit (1KB)
  21287. svr.set_payload_max_length(1024);
  21288. svr.Post("/test", [&](const Request &req, Response &res) {
  21289. res.set_content("Body size: " + std::to_string(req.body.size()),
  21290. "text/plain");
  21291. });
  21292. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21293. auto se = detail::scope_exit([&] {
  21294. svr.stop();
  21295. listen_thread.join();
  21296. });
  21297. svr.wait_until_ready();
  21298. // Create data that compresses well but exceeds limit when decompressed
  21299. // 8KB of repeated null bytes compresses to a very small size
  21300. std::string original_data(8 * 1024, '\0');
  21301. // Compress the data using gzip
  21302. std::string compressed_data;
  21303. detail::gzip_compressor compressor;
  21304. compressor.compress(original_data.data(), original_data.size(), true,
  21305. [&](const char *data, size_t size) {
  21306. compressed_data.append(data, size);
  21307. return true;
  21308. });
  21309. // Verify compression worked (compressed should be much smaller)
  21310. ASSERT_LT(compressed_data.size(), original_data.size());
  21311. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21312. // Send compressed data with Content-Encoding: gzip
  21313. Client cli(HOST, PORT);
  21314. Headers headers = {{"Content-Encoding", "gzip"}};
  21315. auto res =
  21316. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21317. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21319. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21320. }
  21321. #endif
  21322. // ============================================================================
  21323. // OpenSSL-Specific Tests
  21324. // ============================================================================
  21325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21326. X509 *readCertificate(const std::string &strFileName) {
  21327. std::ifstream inStream(strFileName);
  21328. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21329. std::istreambuf_iterator<char>());
  21330. if (strCertPEM.empty()) return (nullptr);
  21331. BIO *pbCert = BIO_new(BIO_s_mem());
  21332. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21333. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21334. BIO_free(pbCert);
  21335. return (pCert);
  21336. }
  21337. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21338. std::ifstream inStream(strFileName);
  21339. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21340. std::istreambuf_iterator<char>());
  21341. if (strPrivateKeyPEM.empty()) return (nullptr);
  21342. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21343. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21344. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21345. BIO_free(pbPrivKey);
  21346. return (pPrivateKey);
  21347. }
  21348. TEST(BindServerTest, UpdateCerts) {
  21349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21350. int port = svr.bind_to_any_port("0.0.0.0");
  21351. ASSERT_TRUE(svr.is_valid());
  21352. ASSERT_TRUE(port > 0);
  21353. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21354. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21355. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21356. ASSERT_TRUE(cert != nullptr);
  21357. ASSERT_TRUE(ca_cert != nullptr);
  21358. ASSERT_TRUE(key != nullptr);
  21359. X509_STORE *cert_store = X509_STORE_new();
  21360. X509_STORE_add_cert(cert_store, ca_cert);
  21361. // svr.update_certs(cert, key, cert_store); // deprecated
  21362. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21363. CLIENT_CA_CERT_FILE);
  21364. ASSERT_TRUE(svr.is_valid());
  21365. svr.stop();
  21366. X509_STORE_free(cert_store);
  21367. X509_free(cert);
  21368. X509_free(ca_cert);
  21369. EVP_PKEY_free(key);
  21370. }
  21371. // Test that update_certs() updates client CA list correctly
  21372. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21373. // Start with file-based constructor
  21374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21375. ASSERT_TRUE(svr.is_valid());
  21376. // Initially no client CA list should be set
  21377. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21378. ASSERT_TRUE(ssl_ctx != nullptr);
  21379. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21380. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21381. EXPECT_EQ(0, count_before);
  21382. // Now update with client CA (PEM string)
  21383. std::string cert_pem, key_pem, ca_pem;
  21384. read_file(SERVER_CERT_FILE, cert_pem);
  21385. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21386. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21387. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21388. ASSERT_TRUE(svr.is_valid());
  21389. // Now client CA list should be set
  21390. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21391. ASSERT_TRUE(ca_list_after != nullptr);
  21392. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21393. }
  21394. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21395. // Test that the file-path SSLServer constructor properly sets the client CA
  21396. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21398. ASSERT_TRUE(svr.is_valid());
  21399. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21400. ASSERT_TRUE(ssl_ctx != nullptr);
  21401. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21402. ASSERT_TRUE(ca_list != nullptr);
  21403. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21404. }
  21405. #endif
  21406. // ============================================================================
  21407. // MbedTLS-Specific Tests
  21408. // ============================================================================
  21409. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21410. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21411. using namespace httplib::tls;
  21412. // Track if callback was invoked
  21413. bool callback_invoked = false;
  21414. // The callback receives void* ctx which is actually MbedTlsContext*
  21415. // We can access the mbedtls_ssl_config via the context
  21416. auto setup_callback = [&callback_invoked](void *ctx) {
  21417. callback_invoked = true;
  21418. // Cast to MbedTlsContext* to access the ssl config
  21419. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21420. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21421. // Use static variables to hold certificate data (simplified for test)
  21422. static mbedtls_x509_crt own_cert;
  21423. static mbedtls_pk_context own_key;
  21424. static mbedtls_x509_crt ca_chain;
  21425. static bool initialized = false;
  21426. if (!initialized) {
  21427. mbedtls_x509_crt_init(&own_cert);
  21428. mbedtls_pk_init(&own_key);
  21429. mbedtls_x509_crt_init(&ca_chain);
  21430. // Load server certificate
  21431. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21432. return false;
  21433. }
  21434. // Load server private key.
  21435. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21436. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21437. #if MBEDTLS_VERSION_MAJOR == 3
  21438. ,
  21439. mbedtls_ctr_drbg_random, nullptr
  21440. #endif
  21441. ) != 0) {
  21442. return false;
  21443. }
  21444. // Load CA chain for client verification
  21445. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21446. return false;
  21447. }
  21448. initialized = true;
  21449. }
  21450. // Configure the SSL config
  21451. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21452. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21453. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21454. // Set minimum TLS version using mbedTLS native API
  21455. #if MBEDTLS_VERSION_MAJOR >= 3
  21456. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21457. #else
  21458. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21459. MBEDTLS_SSL_MINOR_VERSION_3);
  21460. #endif
  21461. return true;
  21462. };
  21463. SSLServer svr(setup_callback);
  21464. ASSERT_TRUE(svr.is_valid());
  21465. ASSERT_TRUE(callback_invoked);
  21466. svr.Get("/test", [&](const Request &req, Response &res) {
  21467. res.set_content("test", "text/plain");
  21468. auto cert = req.peer_cert();
  21469. ASSERT_TRUE(static_cast<bool>(cert));
  21470. auto common_name = cert.subject_cn();
  21471. EXPECT_EQ("Common Name", common_name);
  21472. });
  21473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21474. auto se = detail::scope_exit([&] {
  21475. svr.stop();
  21476. t.join();
  21477. ASSERT_FALSE(svr.is_running());
  21478. });
  21479. svr.wait_until_ready();
  21480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21481. cli.enable_server_certificate_verification(false);
  21482. cli.set_connection_timeout(30);
  21483. auto res = cli.Get("/test");
  21484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21485. ASSERT_EQ(StatusCode::OK_200, res->status);
  21486. }
  21487. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21488. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21489. // keep-alive SSL session, which reads through that config in
  21490. // mbedtls_ssl_close_notify.
  21491. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21493. ASSERT_TRUE(svr.is_valid());
  21494. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21495. res.set_content("test", "text/plain");
  21496. });
  21497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21498. auto se = detail::scope_exit([&] {
  21499. svr.stop();
  21500. t.join();
  21501. ASSERT_FALSE(svr.is_running());
  21502. });
  21503. svr.wait_until_ready();
  21504. {
  21505. SSLClient cli(HOST, PORT);
  21506. cli.enable_server_certificate_verification(false);
  21507. cli.set_keep_alive(true);
  21508. auto res = cli.Get("/test");
  21509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21510. ASSERT_EQ(StatusCode::OK_200, res->status);
  21511. // cli is destructed here with the keep-alive SSL session still open.
  21512. }
  21513. }
  21514. #endif
  21515. // WebSocket Tests
  21516. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21517. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21518. // defining the meaning of these bits has been negotiated.
  21519. auto make_frame = [](uint8_t first_byte) {
  21520. std::string frame;
  21521. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21522. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21523. frame += "Hello";
  21524. return frame;
  21525. };
  21526. // RSV1 set (0x40)
  21527. {
  21528. detail::BufferStream strm;
  21529. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21530. ws::Opcode opcode;
  21531. std::string payload;
  21532. bool fin;
  21533. EXPECT_EQ(
  21534. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21535. ws::impl::FrameRead::Fail);
  21536. }
  21537. // RSV2 set (0x20)
  21538. {
  21539. detail::BufferStream strm;
  21540. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21541. ws::Opcode opcode;
  21542. std::string payload;
  21543. bool fin;
  21544. EXPECT_EQ(
  21545. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21546. ws::impl::FrameRead::Fail);
  21547. }
  21548. // RSV3 set (0x10)
  21549. {
  21550. detail::BufferStream strm;
  21551. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21552. ws::Opcode opcode;
  21553. std::string payload;
  21554. bool fin;
  21555. EXPECT_EQ(
  21556. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21557. ws::impl::FrameRead::Fail);
  21558. }
  21559. // No RSV bits set - should succeed
  21560. {
  21561. detail::BufferStream strm;
  21562. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21563. ws::Opcode opcode;
  21564. std::string payload;
  21565. bool fin;
  21566. EXPECT_EQ(
  21567. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21568. ws::impl::FrameRead::Ok);
  21569. EXPECT_EQ(ws::Opcode::Text, opcode);
  21570. EXPECT_EQ("Hello", payload);
  21571. EXPECT_TRUE(fin);
  21572. }
  21573. }
  21574. TEST(WebSocketTest, ControlFrameValidation) {
  21575. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21576. // payload length <= 125.
  21577. // Ping with FIN=0 - must be rejected
  21578. {
  21579. detail::BufferStream strm;
  21580. std::string frame;
  21581. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21582. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21583. strm.write(frame.data(), frame.size());
  21584. ws::Opcode opcode;
  21585. std::string payload;
  21586. bool fin;
  21587. EXPECT_EQ(
  21588. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21589. ws::impl::FrameRead::Fail);
  21590. }
  21591. // Close with FIN=0 - must be rejected
  21592. {
  21593. detail::BufferStream strm;
  21594. std::string frame;
  21595. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21596. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21597. strm.write(frame.data(), frame.size());
  21598. ws::Opcode opcode;
  21599. std::string payload;
  21600. bool fin;
  21601. EXPECT_EQ(
  21602. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21603. ws::impl::FrameRead::Fail);
  21604. }
  21605. // Ping with payload_len=126 (extended length) - must be rejected
  21606. {
  21607. detail::BufferStream strm;
  21608. std::string frame;
  21609. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21610. frame += static_cast<char>(126); // payload_len=126 (>125)
  21611. frame += static_cast<char>(0x00); // extended length high byte
  21612. frame += static_cast<char>(126); // extended length low byte
  21613. frame += std::string(126, 'x');
  21614. strm.write(frame.data(), frame.size());
  21615. ws::Opcode opcode;
  21616. std::string payload;
  21617. bool fin;
  21618. EXPECT_EQ(
  21619. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21620. ws::impl::FrameRead::Fail);
  21621. }
  21622. // Ping with FIN=1 and payload_len=125 - should succeed
  21623. {
  21624. detail::BufferStream strm;
  21625. std::string frame;
  21626. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21627. frame += static_cast<char>(125); // payload_len=125
  21628. frame += std::string(125, 'x');
  21629. strm.write(frame.data(), frame.size());
  21630. ws::Opcode opcode;
  21631. std::string payload;
  21632. bool fin;
  21633. EXPECT_EQ(
  21634. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21635. ws::impl::FrameRead::Ok);
  21636. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21637. EXPECT_EQ(125u, payload.size());
  21638. EXPECT_TRUE(fin);
  21639. }
  21640. }
  21641. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21642. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21643. // length MUST be 0.
  21644. // MSB set - must be rejected
  21645. {
  21646. detail::BufferStream strm;
  21647. std::string frame;
  21648. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21649. frame += static_cast<char>(127); // 64-bit extended length
  21650. frame += static_cast<char>(0x80); // MSB set (invalid)
  21651. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21652. strm.write(frame.data(), frame.size());
  21653. ws::Opcode opcode;
  21654. std::string payload;
  21655. bool fin;
  21656. EXPECT_EQ(
  21657. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21658. ws::impl::FrameRead::Fail);
  21659. }
  21660. // MSB clear - should pass length parsing (will be rejected by max_len,
  21661. // but that's a different check; use a small length to verify)
  21662. {
  21663. detail::BufferStream strm;
  21664. std::string frame;
  21665. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21666. frame += static_cast<char>(127); // 64-bit extended length
  21667. frame += std::string(7, '\0'); // high bytes = 0
  21668. frame += static_cast<char>(0x03); // length = 3
  21669. frame += "abc";
  21670. strm.write(frame.data(), frame.size());
  21671. ws::Opcode opcode;
  21672. std::string payload;
  21673. bool fin;
  21674. EXPECT_EQ(
  21675. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21676. ws::impl::FrameRead::Ok);
  21677. EXPECT_EQ(ws::Opcode::Text, opcode);
  21678. EXPECT_EQ("abc", payload);
  21679. }
  21680. }
  21681. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21682. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21683. // Valid UTF-8
  21684. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21685. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21686. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21687. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21688. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21689. // Invalid UTF-8
  21690. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21691. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21692. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21693. EXPECT_FALSE(
  21694. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21695. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21696. }
  21697. TEST(WebSocketTest, ConnectAndDisconnect) {
  21698. Server svr;
  21699. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21700. std::string msg;
  21701. while (ws.read(msg)) {}
  21702. });
  21703. auto port = svr.bind_to_any_port(HOST);
  21704. std::thread t([&]() { svr.listen_after_bind(); });
  21705. svr.wait_until_ready();
  21706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21707. auto res = client.connect();
  21708. ASSERT_TRUE(res);
  21709. EXPECT_EQ(Error::Success, res.error());
  21710. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21711. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21712. EXPECT_TRUE(client.is_open());
  21713. client.close();
  21714. EXPECT_FALSE(client.is_open());
  21715. svr.stop();
  21716. t.join();
  21717. }
  21718. TEST(WebSocketTest, ValidURL) {
  21719. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21720. EXPECT_TRUE(ws1.is_valid());
  21721. ws::WebSocketClient ws2("ws://example.com/path");
  21722. EXPECT_TRUE(ws2.is_valid());
  21723. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21724. EXPECT_TRUE(ws3.is_valid());
  21725. #ifdef CPPHTTPLIB_SSL_ENABLED
  21726. ws::WebSocketClient wss1("wss://example.com/path");
  21727. EXPECT_TRUE(wss1.is_valid());
  21728. ws::WebSocketClient wss2("wss://example.com:443/path");
  21729. EXPECT_TRUE(wss2.is_valid());
  21730. #endif
  21731. }
  21732. TEST(WebSocketTest, InvalidURL) {
  21733. // No scheme
  21734. ws::WebSocketClient ws1("localhost:8080/path");
  21735. EXPECT_FALSE(ws1.is_valid());
  21736. // No path
  21737. ws::WebSocketClient ws2("ws://localhost:8080");
  21738. EXPECT_FALSE(ws2.is_valid());
  21739. // Empty string
  21740. ws::WebSocketClient ws3("");
  21741. EXPECT_FALSE(ws3.is_valid());
  21742. // Missing host
  21743. ws::WebSocketClient ws4("ws://:8080/path");
  21744. EXPECT_FALSE(ws4.is_valid());
  21745. // Port number overflow — should not crash
  21746. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21747. EXPECT_FALSE(ws5.is_valid());
  21748. // Port out of range
  21749. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21750. EXPECT_FALSE(ws6.is_valid());
  21751. }
  21752. TEST(WebSocketTest, UnsupportedScheme) {
  21753. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21754. ws::WebSocketClient ws1("http://localhost:8080/path");
  21755. EXPECT_FALSE(ws1.is_valid());
  21756. ws::WebSocketClient ws2("https://localhost:8080/path");
  21757. EXPECT_FALSE(ws2.is_valid());
  21758. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21759. EXPECT_FALSE(ws3.is_valid());
  21760. #else
  21761. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21762. std::invalid_argument);
  21763. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21764. std::invalid_argument);
  21765. #endif
  21766. }
  21767. TEST(WebSocketTest, ConnectWhenInvalid) {
  21768. ws::WebSocketClient ws("not a valid url");
  21769. EXPECT_FALSE(ws.is_valid());
  21770. auto res = ws.connect();
  21771. EXPECT_FALSE(res);
  21772. EXPECT_EQ(Error::Connection, res.error());
  21773. EXPECT_EQ(-1, res.status());
  21774. }
  21775. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21776. // Grab a port that is free, then close it again so nothing listens there
  21777. Server svr;
  21778. auto port = svr.bind_to_any_port(HOST);
  21779. svr.stop();
  21780. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21781. auto res = client.connect();
  21782. ASSERT_FALSE(res);
  21783. EXPECT_EQ(Error::Connection, res.error());
  21784. EXPECT_EQ(-1, res.status());
  21785. }
  21786. TEST(WebSocketTest, DefaultPort) {
  21787. ws::WebSocketClient ws1("ws://example.com/path");
  21788. EXPECT_TRUE(ws1.is_valid());
  21789. // ws:// defaults to port 80 (verified by successful parse)
  21790. #ifdef CPPHTTPLIB_SSL_ENABLED
  21791. ws::WebSocketClient ws2("wss://example.com/path");
  21792. EXPECT_TRUE(ws2.is_valid());
  21793. // wss:// defaults to port 443 (verified by successful parse)
  21794. #endif
  21795. }
  21796. TEST(WebSocketTest, IPv6LiteralAddress) {
  21797. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21798. EXPECT_TRUE(ws1.is_valid());
  21799. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21800. EXPECT_TRUE(ws2.is_valid());
  21801. }
  21802. TEST(WebSocketTest, ComplexPath) {
  21803. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21804. EXPECT_TRUE(ws1.is_valid());
  21805. ws::WebSocketClient ws2("ws://localhost:8080/");
  21806. EXPECT_TRUE(ws2.is_valid());
  21807. }
  21808. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21809. Server svr;
  21810. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21811. std::string msg;
  21812. while (ws.read(msg)) {}
  21813. });
  21814. auto port = svr.bind_to_any_port(HOST);
  21815. std::thread t([&]() { svr.listen_after_bind(); });
  21816. svr.wait_until_ready();
  21817. auto another_host = "example.com";
  21818. auto wrong_ip = "192.0.2.1";
  21819. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21820. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21821. ASSERT_TRUE(client.connect());
  21822. EXPECT_TRUE(client.is_open());
  21823. client.close();
  21824. svr.stop();
  21825. t.join();
  21826. }
  21827. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21828. Server svr;
  21829. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21830. std::string msg;
  21831. while (ws.read(msg)) {}
  21832. });
  21833. auto port = svr.bind_to_any_port(HOST);
  21834. std::thread t([&]() { svr.listen_after_bind(); });
  21835. svr.wait_until_ready();
  21836. auto wrong_ip = "192.0.2.1";
  21837. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21838. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21839. client.set_connection_timeout(1);
  21840. client.set_read_timeout(1);
  21841. client.set_write_timeout(1);
  21842. EXPECT_FALSE(client.connect());
  21843. EXPECT_FALSE(client.is_open());
  21844. svr.stop();
  21845. t.join();
  21846. }
  21847. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21848. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21849. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21850. // (RFC 6761) is only a map key and the Host header value.
  21851. auto host = "target.invalid";
  21852. Server svr;
  21853. std::string received_host;
  21854. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21855. received_host = req.get_header_value("Host");
  21856. std::string msg;
  21857. while (ws.read(msg)) {}
  21858. });
  21859. auto port = svr.bind_to_any_port(HOST);
  21860. std::thread t([&]() { svr.listen_after_bind(); });
  21861. // ASSERT_* below returns from the test body, which would leave t joinable
  21862. // and make ~thread call std::terminate.
  21863. auto se = detail::scope_exit([&] {
  21864. svr.stop();
  21865. if (t.joinable()) { t.join(); }
  21866. });
  21867. svr.wait_until_ready();
  21868. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21869. std::to_string(port) + "/ws");
  21870. client.set_hostname_addr_map({{host, HOST}});
  21871. ASSERT_TRUE(client.connect());
  21872. EXPECT_TRUE(client.is_open());
  21873. client.close();
  21874. svr.stop();
  21875. t.join();
  21876. // The mapping only redirects the connection; the identity stays host_.
  21877. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21878. }
  21879. class WebSocketIntegrationTest : public ::testing::Test {
  21880. protected:
  21881. void SetUp() override {
  21882. server_ = httplib::detail::make_unique<Server>();
  21883. setup_server();
  21884. start_server();
  21885. }
  21886. void TearDown() override {
  21887. server_->stop();
  21888. if (server_thread_.joinable()) { server_thread_.join(); }
  21889. }
  21890. void setup_server() {
  21891. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21892. std::string msg;
  21893. ws::ReadResult ret;
  21894. while ((ret = ws.read(msg))) {
  21895. if (ret == ws::Binary) {
  21896. ws.send(msg.data(), msg.size());
  21897. } else {
  21898. ws.send(msg);
  21899. }
  21900. }
  21901. });
  21902. server_->WebSocket("/ws-echo-string",
  21903. [](const Request &, ws::WebSocket &ws) {
  21904. std::string msg;
  21905. while (ws.read(msg)) {
  21906. ws.send("echo: " + msg);
  21907. }
  21908. });
  21909. server_->WebSocket(
  21910. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21911. // Echo back request metadata
  21912. ws.send("path:" + req.path);
  21913. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21914. std::string msg;
  21915. while (ws.read(msg)) {}
  21916. });
  21917. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21918. std::string msg;
  21919. ws.read(msg); // wait for a message
  21920. ws.close();
  21921. });
  21922. server_->WebSocket("/ws-close-status",
  21923. [](const Request &, ws::WebSocket &ws) {
  21924. std::string msg;
  21925. ws.read(msg); // wait for a message
  21926. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21927. });
  21928. server_->WebSocket(
  21929. "/ws-subprotocol",
  21930. [](const Request &, ws::WebSocket &ws) {
  21931. std::string msg;
  21932. while (ws.read(msg)) {
  21933. ws.send(msg);
  21934. }
  21935. },
  21936. [](const std::vector<std::string> &protocols) -> std::string {
  21937. for (const auto &p : protocols) {
  21938. if (p == "graphql-ws") { return p; }
  21939. }
  21940. return "";
  21941. });
  21942. server_->WebSocket(
  21943. "/ws-subprotocol-unoffered",
  21944. [](const Request &, ws::WebSocket &ws) {
  21945. std::string msg;
  21946. while (ws.read(msg)) {
  21947. ws.send(msg);
  21948. }
  21949. },
  21950. [](const std::vector<std::string> &) -> std::string {
  21951. return "admin";
  21952. });
  21953. }
  21954. void start_server() {
  21955. port_ = server_->bind_to_any_port(HOST);
  21956. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21957. server_->wait_until_ready();
  21958. }
  21959. std::unique_ptr<Server> server_;
  21960. std::thread server_thread_;
  21961. int port_ = 0;
  21962. };
  21963. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21965. "/ws-echo");
  21966. ASSERT_TRUE(client.connect());
  21967. ASSERT_TRUE(client.is_open());
  21968. ASSERT_TRUE(client.send("Hello WebSocket"));
  21969. std::string msg;
  21970. EXPECT_EQ(ws::Text, client.read(msg));
  21971. EXPECT_EQ("Hello WebSocket", msg);
  21972. client.close();
  21973. }
  21974. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21976. "/ws-echo");
  21977. ASSERT_TRUE(client.connect());
  21978. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21979. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21980. std::string msg;
  21981. EXPECT_EQ(ws::Binary, client.read(msg));
  21982. EXPECT_EQ(binary_data, msg);
  21983. client.close();
  21984. }
  21985. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21986. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21987. "/ws-echo");
  21988. ASSERT_TRUE(client.connect());
  21989. for (int i = 0; i < 10; i++) {
  21990. auto text = "message " + std::to_string(i);
  21991. ASSERT_TRUE(client.send(text));
  21992. std::string msg;
  21993. ASSERT_TRUE(client.read(msg));
  21994. EXPECT_EQ(text, msg);
  21995. }
  21996. client.close();
  21997. }
  21998. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22000. "/ws-close");
  22001. ASSERT_TRUE(client.connect());
  22002. // Send a message to trigger the server to close
  22003. ASSERT_TRUE(client.send("trigger close"));
  22004. // The server will close, so read should return false
  22005. std::string msg;
  22006. EXPECT_FALSE(client.read(msg));
  22007. EXPECT_FALSE(client.is_open());
  22008. }
  22009. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22010. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22011. "/ws-echo");
  22012. ASSERT_TRUE(client.connect());
  22013. // 128KB message
  22014. std::string large_data(128 * 1024, 'X');
  22015. ASSERT_TRUE(client.send(large_data));
  22016. std::string msg;
  22017. ASSERT_TRUE(client.read(msg));
  22018. EXPECT_EQ(large_data, msg);
  22019. client.close();
  22020. }
  22021. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22023. "/ws-echo");
  22024. ASSERT_TRUE(client.connect());
  22025. const int num_threads = 4;
  22026. std::vector<std::thread> threads;
  22027. std::atomic<int> send_count{0};
  22028. for (int t = 0; t < num_threads; t++) {
  22029. threads.emplace_back([&client, &send_count, t]() {
  22030. for (int i = 0; i < 5; i++) {
  22031. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22032. if (client.send(text)) { send_count++; }
  22033. }
  22034. });
  22035. }
  22036. for (auto &th : threads) {
  22037. th.join();
  22038. }
  22039. int received = 0;
  22040. std::string msg;
  22041. while (received < send_count.load()) {
  22042. if (!client.read(msg)) { break; }
  22043. received++;
  22044. }
  22045. EXPECT_EQ(send_count.load(), received);
  22046. client.close();
  22047. }
  22048. TEST_F(WebSocketIntegrationTest, ReadString) {
  22049. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22050. "/ws-echo-string");
  22051. ASSERT_TRUE(client.connect());
  22052. ASSERT_TRUE(client.send("hello"));
  22053. std::string msg;
  22054. ASSERT_TRUE(client.read(msg));
  22055. EXPECT_EQ("echo: hello", msg);
  22056. ASSERT_TRUE(client.send("world"));
  22057. ASSERT_TRUE(client.read(msg));
  22058. EXPECT_EQ("echo: world", msg);
  22059. client.close();
  22060. }
  22061. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22062. Headers headers = {{"X-Test-Header", "test-value"}};
  22063. ws::WebSocketClient client(
  22064. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22065. ASSERT_TRUE(client.connect());
  22066. std::string msg;
  22067. ASSERT_TRUE(client.read(msg));
  22068. EXPECT_EQ("path:/ws-request-info", msg);
  22069. ASSERT_TRUE(client.read(msg));
  22070. EXPECT_EQ("header:test-value", msg);
  22071. client.close();
  22072. }
  22073. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22074. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22075. "/ws-echo");
  22076. client.set_read_timeout(1, 0); // 1 second
  22077. ASSERT_TRUE(client.connect());
  22078. // Don't send anything — server echo handler waits for a message, so read()
  22079. // should time out. The connection survives it: nothing was consumed.
  22080. std::string msg;
  22081. EXPECT_EQ(client.read(msg), ws::Timeout);
  22082. EXPECT_TRUE(client.is_open());
  22083. // And it is still usable afterwards.
  22084. EXPECT_TRUE(client.send("after timeout"));
  22085. EXPECT_EQ(client.read(msg), ws::Text);
  22086. EXPECT_EQ(msg, "after timeout");
  22087. }
  22088. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22089. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22090. "/ws-echo");
  22091. client.set_read_timeout(1, 0);
  22092. ASSERT_TRUE(client.connect());
  22093. ASSERT_TRUE(client.send("first"));
  22094. std::string msg;
  22095. ASSERT_EQ(client.read(msg), ws::Text);
  22096. ASSERT_EQ(msg, "first");
  22097. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22098. // not be used with a read timeout: it would reprocess the previous message.
  22099. EXPECT_EQ(client.read(msg), ws::Timeout);
  22100. EXPECT_EQ(msg, "first");
  22101. }
  22102. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22103. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22104. "/ws-echo");
  22105. ASSERT_TRUE(client.connect());
  22106. // Setting it once the connection is open reaches the live stream, not just
  22107. // the seed for the next connect().
  22108. client.set_read_timeout(1, 0);
  22109. std::string msg;
  22110. EXPECT_EQ(client.read(msg), ws::Timeout);
  22111. EXPECT_TRUE(client.is_open());
  22112. }
  22113. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22114. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22115. "/ws-echo");
  22116. client.set_read_timeout(5, 0);
  22117. ASSERT_TRUE(client.connect());
  22118. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22119. // The server should reject it and close the connection.
  22120. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22121. client.send(oversized);
  22122. // The server's read() should have failed due to payload limit,
  22123. // so our read() should return false (connection closed).
  22124. std::string msg;
  22125. EXPECT_FALSE(client.read(msg));
  22126. }
  22127. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22129. "/ws-echo");
  22130. client.set_read_timeout(10, 0);
  22131. ASSERT_TRUE(client.connect());
  22132. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22133. // This should succeed.
  22134. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22135. ASSERT_TRUE(client.send(at_limit));
  22136. std::string msg;
  22137. ASSERT_TRUE(client.read(msg));
  22138. EXPECT_EQ(at_limit.size(), msg.size());
  22139. client.close();
  22140. }
  22141. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22142. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22143. "/nonexistent");
  22144. auto res = client.connect();
  22145. EXPECT_FALSE(res);
  22146. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22147. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22148. EXPECT_FALSE(client.is_open());
  22149. }
  22150. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22152. "/ws-echo");
  22153. ASSERT_TRUE(client.connect());
  22154. ASSERT_TRUE(client.send(""));
  22155. std::string msg;
  22156. EXPECT_EQ(ws::Text, client.read(msg));
  22157. EXPECT_EQ("", msg);
  22158. client.close();
  22159. }
  22160. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22161. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22162. "/ws-echo");
  22163. // First connection
  22164. ASSERT_TRUE(client.connect());
  22165. ASSERT_TRUE(client.send("first"));
  22166. std::string msg;
  22167. ASSERT_TRUE(client.read(msg));
  22168. EXPECT_EQ("first", msg);
  22169. client.close();
  22170. EXPECT_FALSE(client.is_open());
  22171. // Reconnect using the same client object
  22172. ASSERT_TRUE(client.connect());
  22173. ASSERT_TRUE(client.is_open());
  22174. ASSERT_TRUE(client.send("second"));
  22175. ASSERT_TRUE(client.read(msg));
  22176. EXPECT_EQ("second", msg);
  22177. client.close();
  22178. }
  22179. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22181. "/ws-close-status");
  22182. ASSERT_TRUE(client.connect());
  22183. // Trigger the server to close with GoingAway status
  22184. ASSERT_TRUE(client.send("trigger"));
  22185. // read() should return false after receiving the close frame
  22186. std::string msg;
  22187. EXPECT_FALSE(client.read(msg));
  22188. EXPECT_FALSE(client.is_open());
  22189. }
  22190. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22192. "/ws-echo");
  22193. ASSERT_TRUE(client.connect());
  22194. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22195. EXPECT_FALSE(client.is_open());
  22196. }
  22197. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22198. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22199. ws::WebSocketClient client(
  22200. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22201. ASSERT_TRUE(client.connect());
  22202. // Server should have selected graphql-ws
  22203. EXPECT_EQ("graphql-ws", client.subprotocol());
  22204. client.close();
  22205. }
  22206. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22207. Headers headers;
  22208. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22209. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22210. ws::WebSocketClient client(
  22211. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22212. ASSERT_TRUE(client.connect());
  22213. // The offer on the second field line counts too, so graphql-ws is selected
  22214. EXPECT_EQ("graphql-ws", client.subprotocol());
  22215. client.close();
  22216. }
  22217. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22218. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22219. ws::WebSocketClient client(
  22220. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22221. ASSERT_TRUE(client.connect());
  22222. // Server should not have selected any subprotocol
  22223. EXPECT_TRUE(client.subprotocol().empty());
  22224. client.close();
  22225. }
  22226. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22227. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22228. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22229. "/ws-subprotocol-unoffered",
  22230. headers);
  22231. ASSERT_TRUE(client.connect());
  22232. EXPECT_TRUE(client.subprotocol().empty());
  22233. client.close();
  22234. }
  22235. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22236. // Connect without requesting any subprotocol
  22237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22238. "/ws-subprotocol");
  22239. ASSERT_TRUE(client.connect());
  22240. EXPECT_TRUE(client.subprotocol().empty());
  22241. client.close();
  22242. }
  22243. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22244. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22245. "/ws-echo");
  22246. client.set_tcp_nodelay(true);
  22247. client.set_connection_timeout(3, 0);
  22248. bool socket_options_called = false;
  22249. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22250. ASSERT_TRUE(client.connect());
  22251. ASSERT_TRUE(client.is_open());
  22252. EXPECT_TRUE(socket_options_called);
  22253. ASSERT_TRUE(client.send("hello"));
  22254. std::string msg;
  22255. auto result = client.read(msg);
  22256. EXPECT_EQ(result, ws::ReadResult::Text);
  22257. EXPECT_EQ(msg, "hello");
  22258. client.close();
  22259. }
  22260. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22262. "/ws-echo");
  22263. client.set_connection_timeout(std::chrono::seconds(3));
  22264. client.set_write_timeout(std::chrono::seconds(3));
  22265. // A sub-second remainder exercises the seconds/microseconds split.
  22266. client.set_read_timeout(std::chrono::milliseconds(1500));
  22267. ASSERT_TRUE(client.connect());
  22268. auto start = std::chrono::steady_clock::now();
  22269. std::string msg;
  22270. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22271. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22272. std::chrono::steady_clock::now() - start)
  22273. .count();
  22274. // Above 1s so that dropping the microseconds half of the split fails here.
  22275. // Ignoring the setter altogether would not reach this line at all: a client
  22276. // waits forever by default.
  22277. EXPECT_GE(elapsed, 1400);
  22278. EXPECT_LT(elapsed, 30000);
  22279. }
  22280. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22281. Server svr;
  22282. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22283. if (!req.has_header("Authorization")) {
  22284. res.status = StatusCode::Unauthorized_401;
  22285. res.set_content("Unauthorized", "text/plain");
  22286. return Server::HandlerResponse::Handled;
  22287. }
  22288. return Server::HandlerResponse::Unhandled;
  22289. });
  22290. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22291. std::string msg;
  22292. while (ws.read(msg)) {
  22293. ws.send(msg);
  22294. }
  22295. });
  22296. auto port = svr.bind_to_any_port("localhost");
  22297. std::thread t([&]() { svr.listen_after_bind(); });
  22298. svr.wait_until_ready();
  22299. // Without Authorization header - should be rejected before upgrade
  22300. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22301. EXPECT_FALSE(client1.connect());
  22302. // The rejection is framed like any other HTTP response
  22303. {
  22304. Client cli("localhost", port);
  22305. Headers headers = {{"Upgrade", "websocket"},
  22306. {"Connection", "Upgrade"},
  22307. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22308. {"Sec-WebSocket-Version", "13"}};
  22309. auto res = cli.Get("/ws", headers);
  22310. ASSERT_TRUE(res);
  22311. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22312. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22313. EXPECT_EQ("Unauthorized", res->body);
  22314. }
  22315. // With Authorization header - should succeed
  22316. Headers headers = {{"Authorization", "Bearer token123"}};
  22317. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22318. headers);
  22319. ASSERT_TRUE(client2.connect());
  22320. ASSERT_TRUE(client2.send("hello"));
  22321. std::string msg;
  22322. ASSERT_TRUE(client2.read(msg));
  22323. EXPECT_EQ("hello", msg);
  22324. client2.close();
  22325. svr.stop();
  22326. t.join();
  22327. }
  22328. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22329. Server svr;
  22330. std::atomic<int> pre_request_calls{0};
  22331. std::atomic<bool> route_matched{false};
  22332. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22333. pre_request_calls++;
  22334. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22335. if (req.get_header_value("Authorization") != "Bearer token123") {
  22336. res.status = StatusCode::Unauthorized_401;
  22337. res.set_content("Unauthorized", "text/plain");
  22338. return Server::HandlerResponse::Handled;
  22339. }
  22340. return Server::HandlerResponse::Unhandled;
  22341. });
  22342. std::atomic<bool> handler_called{false};
  22343. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22344. handler_called = true;
  22345. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22346. });
  22347. auto port = svr.bind_to_any_port("localhost");
  22348. std::thread t([&]() { svr.listen_after_bind(); });
  22349. svr.wait_until_ready();
  22350. // Without Authorization header - should be rejected before upgrade
  22351. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22352. "/ws/1");
  22353. EXPECT_FALSE(client1.connect());
  22354. EXPECT_FALSE(handler_called);
  22355. EXPECT_EQ(1, pre_request_calls);
  22356. EXPECT_TRUE(route_matched);
  22357. // The rejection is an ordinary HTTP response, not a protocol switch
  22358. {
  22359. Client cli("localhost", port);
  22360. Headers headers = {{"Upgrade", "websocket"},
  22361. {"Connection", "Upgrade"},
  22362. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22363. {"Sec-WebSocket-Version", "13"}};
  22364. auto res = cli.Get("/ws/1", headers);
  22365. ASSERT_TRUE(res);
  22366. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22367. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22368. EXPECT_EQ("Unauthorized", res->body);
  22369. }
  22370. EXPECT_FALSE(handler_called);
  22371. // With Authorization header - should succeed
  22372. Headers headers = {{"Authorization", "Bearer token123"}};
  22373. ws::WebSocketClient client2(
  22374. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22375. ASSERT_TRUE(client2.connect());
  22376. std::string msg;
  22377. ASSERT_TRUE(client2.read(msg));
  22378. EXPECT_EQ("/ws/:id 2", msg);
  22379. EXPECT_TRUE(handler_called);
  22380. client2.close();
  22381. svr.stop();
  22382. t.join();
  22383. }
  22384. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22385. Server svr;
  22386. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22387. // A read timeout is how a handler gets control back. Without it, a handler
  22388. // parked in read() can never write on the connection it is reading.
  22389. ws.set_read_timeout(std::chrono::milliseconds(100));
  22390. std::string msg;
  22391. while (ws.is_open()) {
  22392. auto r = ws.read(msg);
  22393. if (r == httplib::ws::Timeout) {
  22394. ws.send("tick");
  22395. continue;
  22396. }
  22397. if (r == httplib::ws::Fail) { break; }
  22398. ws.send(msg);
  22399. }
  22400. });
  22401. auto port = svr.bind_to_any_port("localhost");
  22402. std::thread t([&]() { svr.listen_after_bind(); });
  22403. svr.wait_until_ready();
  22404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22405. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22406. ASSERT_TRUE(client.connect());
  22407. // The client sends nothing, so anything it receives came out of the
  22408. // handler's timeout path.
  22409. std::string msg;
  22410. ASSERT_EQ(client.read(msg), ws::Text);
  22411. EXPECT_EQ("tick", msg);
  22412. client.close();
  22413. svr.stop();
  22414. t.join();
  22415. }
  22416. // Stream::read may return fewer bytes than asked for. This is that contract at
  22417. // its worst -- one byte per call -- which is what a frame header straddling a
  22418. // read buffer's boundary looks like to the frame parser.
  22419. class WsByteAtATimeStream : public Stream {
  22420. public:
  22421. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22422. bool is_readable() const override { return true; }
  22423. bool wait_readable() const override { return true; }
  22424. bool wait_writable() const override { return true; }
  22425. ssize_t read(char *ptr, size_t size) override {
  22426. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22427. *ptr = data_[pos_++];
  22428. return 1;
  22429. }
  22430. ssize_t write(const char *, size_t size) override {
  22431. return static_cast<ssize_t>(size);
  22432. }
  22433. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22434. ip = "127.0.0.1";
  22435. port = 0;
  22436. }
  22437. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22438. ip = "127.0.0.1";
  22439. port = 0;
  22440. }
  22441. socket_t socket() const override { return INVALID_SOCKET; }
  22442. time_t duration() const override { return 0; }
  22443. private:
  22444. std::string data_;
  22445. size_t pos_ = 0;
  22446. };
  22447. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22448. // The payload uses the 16-bit extended length, so the header, the length
  22449. // and the mask key are all multi-byte fields here. Each used to be read
  22450. // with a single read() call, which fails as soon as one is split. The
  22451. // payload is also a little over one read chunk, so it is read in two.
  22452. std::string body;
  22453. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22454. body += static_cast<char>(i % 251);
  22455. }
  22456. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22457. std::string frame;
  22458. frame += static_cast<char>(0x81); // FIN + Text
  22459. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22460. frame += static_cast<char>(body.size() >> 8);
  22461. frame += static_cast<char>(body.size() & 0xff);
  22462. for (size_t i = 0; i < 4; i++) {
  22463. frame += static_cast<char>(mask[i]);
  22464. }
  22465. for (size_t i = 0; i < body.size(); i++) {
  22466. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22467. }
  22468. WsByteAtATimeStream strm(frame);
  22469. ws::Opcode opcode;
  22470. std::string payload;
  22471. bool fin = false;
  22472. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22473. /*expect_masked=*/true, body.size()),
  22474. ws::impl::FrameRead::Ok);
  22475. EXPECT_TRUE(fin);
  22476. EXPECT_EQ(opcode, ws::Opcode::Text);
  22477. EXPECT_EQ(payload, body);
  22478. }
  22479. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22480. std::string body(2000, 'x');
  22481. std::string frame;
  22482. frame += static_cast<char>(0x82); // FIN + Binary
  22483. frame += static_cast<char>(126); // 16-bit length follows
  22484. frame += static_cast<char>(body.size() >> 8);
  22485. frame += static_cast<char>(body.size() & 0xff);
  22486. frame += body;
  22487. detail::BufferStream strm;
  22488. strm.write(frame.data(), frame.size());
  22489. ws::Opcode opcode;
  22490. std::string payload;
  22491. bool fin;
  22492. EXPECT_EQ(
  22493. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22494. ws::impl::FrameRead::Ok);
  22495. EXPECT_EQ(body, payload);
  22496. }
  22497. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22498. // The header announces the largest payload allowed, and only 3 bytes of it
  22499. // ever arrive.
  22500. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22501. std::string frame;
  22502. frame += static_cast<char>(0x82); // FIN + Binary
  22503. frame += static_cast<char>(127); // 64-bit length follows
  22504. for (int shift = 56; shift >= 0; shift -= 8) {
  22505. frame += static_cast<char>((len >> shift) & 0xff);
  22506. }
  22507. frame += "abc";
  22508. detail::BufferStream strm;
  22509. strm.write(frame.data(), frame.size());
  22510. ws::Opcode opcode;
  22511. std::string payload;
  22512. bool fin;
  22513. EXPECT_EQ(
  22514. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22515. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22516. ws::impl::FrameRead::Fail);
  22517. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22518. }
  22519. TEST(WebSocketTest, QueryStringInHandshake) {
  22520. Server svr;
  22521. std::mutex mtx;
  22522. std::string received_target;
  22523. std::string received_token;
  22524. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22525. {
  22526. std::lock_guard<std::mutex> lock(mtx);
  22527. received_target = req.target;
  22528. if (req.has_param("token")) {
  22529. received_token = req.get_param_value("token");
  22530. }
  22531. }
  22532. std::string msg;
  22533. while (ws.read(msg)) {
  22534. ws.send(msg);
  22535. }
  22536. });
  22537. auto port = svr.bind_to_any_port("localhost");
  22538. std::thread t([&]() { svr.listen_after_bind(); });
  22539. svr.wait_until_ready();
  22540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22541. "/ws?token=ABC&session=123");
  22542. ASSERT_TRUE(client.connect());
  22543. // Round-trip ensures the handler has run and captured the request.
  22544. ASSERT_TRUE(client.send("hello"));
  22545. std::string msg;
  22546. ASSERT_TRUE(client.read(msg));
  22547. EXPECT_EQ("hello", msg);
  22548. client.close();
  22549. {
  22550. std::lock_guard<std::mutex> lock(mtx);
  22551. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22552. EXPECT_EQ("ABC", received_token);
  22553. }
  22554. svr.stop();
  22555. t.join();
  22556. }
  22557. // Run a handshake against a throwaway server and hand the request the server
  22558. // received back to the caller, so tests can assert on the headers the client
  22559. // actually put on the wire.
  22560. static void capture_websocket_handshake_request(
  22561. const Headers &client_headers,
  22562. std::function<void(const Request &, int port)> verify) {
  22563. Server svr;
  22564. std::mutex mtx;
  22565. Request received;
  22566. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22567. {
  22568. std::lock_guard<std::mutex> lock(mtx);
  22569. received = req;
  22570. }
  22571. std::string msg;
  22572. while (ws.read(msg)) {
  22573. ws.send(msg);
  22574. }
  22575. });
  22576. auto port = svr.bind_to_any_port("localhost");
  22577. std::thread t([&]() { svr.listen_after_bind(); });
  22578. auto se = detail::scope_exit([&] {
  22579. svr.stop();
  22580. t.join();
  22581. });
  22582. svr.wait_until_ready();
  22583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22584. client_headers);
  22585. ASSERT_TRUE(client.connect());
  22586. ASSERT_TRUE(client.send("hello"));
  22587. std::string msg;
  22588. ASSERT_TRUE(client.read(msg));
  22589. client.close();
  22590. {
  22591. std::lock_guard<std::mutex> lock(mtx);
  22592. verify(received, port);
  22593. }
  22594. }
  22595. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22596. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22597. // Non-default port must be present in the Host header. Default ports
  22598. // (80/443) are omitted; that logic is covered by
  22599. // MakeHostAndPortStringTest.
  22600. EXPECT_EQ("localhost:" + std::to_string(port),
  22601. req.get_header_value("Host"));
  22602. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22603. req.get_header_value("User-Agent"));
  22604. EXPECT_FALSE(req.has_header("Accept"));
  22605. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22606. EXPECT_FALSE(req.has_header("Content-Length"));
  22607. });
  22608. }
  22609. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22610. capture_websocket_handshake_request(
  22611. {{"Host", "example.com"},
  22612. {"User-Agent", "custom-agent"},
  22613. {"X-Custom", "value"}},
  22614. [](const Request &req, int) {
  22615. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22616. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22617. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22618. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22619. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22620. });
  22621. }
  22622. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22623. capture_websocket_handshake_request(
  22624. {{"Upgrade", "bogus"},
  22625. {"Connection", "close"},
  22626. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22627. {"Sec-WebSocket-Version", "8"}},
  22628. [](const Request &req, int) {
  22629. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22630. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22631. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22632. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22633. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22634. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22635. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22636. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22637. req.get_header_value("Sec-WebSocket-Key"));
  22638. });
  22639. }
  22640. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22641. // A header the client refuses to send must abort the handshake before any
  22642. // part of it reaches the wire; a lone request line would otherwise sit in
  22643. // the peer's buffer as a truncated request.
  22644. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22645. ASSERT_NE(INVALID_SOCKET, srv);
  22646. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22647. sockaddr_in addr{};
  22648. addr.sin_family = AF_INET;
  22649. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22650. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22651. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22652. ASSERT_EQ(0, ::listen(srv, 1));
  22653. sockaddr_in bound{};
  22654. socklen_t bound_len = sizeof(bound);
  22655. ASSERT_EQ(
  22656. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22657. auto port = ntohs(bound.sin_port);
  22658. ssize_t received = -1;
  22659. std::thread t([&] {
  22660. // Bound every blocking call so a regression fails the test with a bad
  22661. // value instead of hanging the suite.
  22662. fd_set rfds;
  22663. FD_ZERO(&rfds);
  22664. FD_SET(srv, &rfds);
  22665. timeval tv{5, 0};
  22666. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22667. 0) {
  22668. return;
  22669. }
  22670. sockaddr_in cli_addr{};
  22671. socklen_t cli_len = sizeof(cli_addr);
  22672. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22673. if (cli == INVALID_SOCKET) { return; }
  22674. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22675. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22676. char buf[4096];
  22677. received = ::recv(cli, buf, sizeof(buf), 0);
  22678. });
  22679. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22680. // connect() has already shut the socket down by the time it returns false,
  22681. // so the peer sees EOF without waiting for the client to be destroyed.
  22682. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22683. {{"X-Bad", "a\r\nInjected: 1"}});
  22684. EXPECT_FALSE(client.connect());
  22685. t.join();
  22686. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22687. EXPECT_EQ(0, received);
  22688. }
  22689. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22690. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22691. // contains "upgrade" as a substring is a different token and must not
  22692. // start a WebSocket handshake.
  22693. auto make_request = [](const std::vector<std::string> &connection_values) {
  22694. Request req;
  22695. req.method = "GET";
  22696. req.headers.emplace("Upgrade", "websocket");
  22697. for (const auto &value : connection_values) {
  22698. req.headers.emplace("Connection", value);
  22699. }
  22700. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22701. req.headers.emplace("Sec-WebSocket-Version", "13");
  22702. return req;
  22703. };
  22704. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22705. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22706. EXPECT_TRUE(
  22707. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22708. EXPECT_TRUE(
  22709. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22710. EXPECT_TRUE(
  22711. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22712. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22713. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22714. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22715. EXPECT_FALSE(
  22716. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22717. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22718. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22719. }
  22720. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22721. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22722. // asks recipients to match each protocol-name case-insensitively, and RFC
  22723. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22724. // client naming websocket alongside another protocol, or on a second field
  22725. // line, is offering websocket; a value that merely contains "websocket" as a
  22726. // substring is a different protocol name and is not.
  22727. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22728. Request req;
  22729. req.method = "GET";
  22730. for (const auto &value : upgrade_values) {
  22731. req.headers.emplace("Upgrade", value);
  22732. }
  22733. req.headers.emplace("Connection", "Upgrade");
  22734. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22735. req.headers.emplace("Sec-WebSocket-Version", "13");
  22736. return req;
  22737. };
  22738. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22739. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22740. EXPECT_TRUE(
  22741. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22742. EXPECT_TRUE(
  22743. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22744. EXPECT_TRUE(
  22745. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22746. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22747. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22748. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22749. EXPECT_FALSE(
  22750. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22751. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22752. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22753. }
  22754. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22755. Server svr;
  22756. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22757. auto port = svr.bind_to_any_port("localhost");
  22758. std::thread t([&]() { svr.listen_after_bind(); });
  22759. auto se = detail::scope_exit([&] {
  22760. svr.stop();
  22761. t.join();
  22762. });
  22763. svr.wait_until_ready();
  22764. Headers headers = {{"Upgrade", "websocket"},
  22765. {"Connection", "notupgrade"},
  22766. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22767. {"Sec-WebSocket-Version", "13"}};
  22768. Client cli("localhost", port);
  22769. auto res = cli.Get("/ws", headers);
  22770. // The route exists only as a WebSocket route, so a request that fails the
  22771. // handshake check falls through to ordinary routing.
  22772. ASSERT_TRUE(res);
  22773. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22774. }
  22775. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22776. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22777. // Connection value is the only thing left for the client to reject.
  22778. Server svr;
  22779. svr.Get("/ws", [](const Request &req, Response &res) {
  22780. res.status = StatusCode::SwitchingProtocol_101;
  22781. res.set_header("Upgrade", "websocket");
  22782. res.set_header("Connection", "notupgrade");
  22783. res.set_header("Sec-WebSocket-Accept",
  22784. detail::websocket_accept_key(
  22785. req.get_header_value("Sec-WebSocket-Key")));
  22786. });
  22787. auto port = svr.bind_to_any_port("localhost");
  22788. std::thread t([&]() { svr.listen_after_bind(); });
  22789. auto se = detail::scope_exit([&] {
  22790. svr.stop();
  22791. t.join();
  22792. });
  22793. svr.wait_until_ready();
  22794. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22795. auto res = client.connect();
  22796. EXPECT_FALSE(res);
  22797. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22798. EXPECT_FALSE(client.is_open());
  22799. }
  22800. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22801. Server svr;
  22802. svr.Get("/ws", [](const Request &req, Response &res) {
  22803. res.status = StatusCode::SwitchingProtocol_101;
  22804. res.set_header("Upgrade", "websocket");
  22805. res.set_header("Connection", "Upgrade");
  22806. res.set_header("Sec-WebSocket-Accept",
  22807. detail::websocket_accept_key(
  22808. req.get_header_value("Sec-WebSocket-Key")));
  22809. res.set_header("Sec-WebSocket-Protocol", "admin");
  22810. });
  22811. auto port = svr.bind_to_any_port("localhost");
  22812. std::thread t([&]() { svr.listen_after_bind(); });
  22813. auto se = detail::scope_exit([&] {
  22814. svr.stop();
  22815. t.join();
  22816. });
  22817. svr.wait_until_ready();
  22818. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22819. // Server selects a subprotocol the client never offered
  22820. {
  22821. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22822. ws::WebSocketClient client(url, headers);
  22823. auto res = client.connect();
  22824. EXPECT_FALSE(res);
  22825. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22826. EXPECT_FALSE(client.is_open());
  22827. EXPECT_TRUE(client.subprotocol().empty());
  22828. }
  22829. // Client offered none but the server named one anyway
  22830. {
  22831. ws::WebSocketClient client(url);
  22832. auto res = client.connect();
  22833. EXPECT_FALSE(res);
  22834. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22835. EXPECT_FALSE(client.is_open());
  22836. EXPECT_TRUE(client.subprotocol().empty());
  22837. }
  22838. }
  22839. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22840. // The socket path doubles as the URL host, so it must not contain '/'.
  22841. const char *shard = getenv("GTEST_SHARD_INDEX");
  22842. const std::string sock_path =
  22843. shard ? std::string("httplib-ws-") + shard + ".sock"
  22844. : std::string("httplib-ws.sock");
  22845. std::remove(sock_path.c_str());
  22846. Server svr;
  22847. std::mutex mtx;
  22848. std::string received_host;
  22849. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22850. {
  22851. std::lock_guard<std::mutex> lock(mtx);
  22852. received_host = req.get_header_value("Host");
  22853. }
  22854. std::string msg;
  22855. while (ws.read(msg)) {
  22856. ws.send(msg);
  22857. }
  22858. });
  22859. svr.set_address_family(AF_UNIX);
  22860. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22861. auto se = detail::scope_exit([&] {
  22862. svr.stop();
  22863. t.join();
  22864. std::remove(sock_path.c_str());
  22865. });
  22866. svr.wait_until_ready();
  22867. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22868. client.set_address_family(AF_UNIX);
  22869. ASSERT_TRUE(client.connect());
  22870. ASSERT_TRUE(client.send("hello"));
  22871. std::string msg;
  22872. ASSERT_TRUE(client.read(msg));
  22873. client.close();
  22874. {
  22875. std::lock_guard<std::mutex> lock(mtx);
  22876. // There is no host:port for a Unix socket, so the same "localhost"
  22877. // placeholder the HTTP client uses is expected.
  22878. EXPECT_EQ("localhost", received_host);
  22879. }
  22880. }
  22881. // Two threads must never parse WebSocket frames from the same stream.
  22882. // close() used to read the peer's Close reply with its own frame read, so it
  22883. // raced a reader thread that was in the middle of a payload: the payload loop
  22884. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22885. // so bytes taken by close() were replaced with bytes from further along the
  22886. // stream. The message kept its length and silently changed content.
  22887. //
  22888. // The raw peer below sends a frame header plus part of the payload, waits for
  22889. // the handler to call close(), and only then sends the rest. Whichever thread
  22890. // would win the race for those bytes, the message must arrive intact, because
  22891. // close() must not touch the stream while read() owns it.
  22892. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22893. #ifndef _WIN32
  22894. signal(SIGPIPE, SIG_IGN);
  22895. #endif
  22896. const size_t payload_len = 120; // fits the 7-bit length field
  22897. const size_t prefix_len = 8;
  22898. const int attempts = 8;
  22899. std::string expected(payload_len, '\0');
  22900. for (size_t i = 0; i < payload_len; i++) {
  22901. expected[i] = static_cast<char>('a' + i % 26);
  22902. }
  22903. std::atomic<bool> peer_stalled{false};
  22904. std::atomic<bool> handler_done{false};
  22905. std::mutex received_mutex;
  22906. std::vector<std::string> received;
  22907. // Bound every wait, so a regression fails the test instead of hanging the
  22908. // suite.
  22909. auto wait_for = [](const std::atomic<bool> &flag) {
  22910. for (int i = 0; i < 500 && !flag; i++) {
  22911. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22912. }
  22913. };
  22914. Server svr;
  22915. svr.set_websocket_ping_interval(0);
  22916. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22917. std::thread reader([&]() {
  22918. std::string msg;
  22919. while (ws.read(msg)) {
  22920. std::lock_guard<std::mutex> guard(received_mutex);
  22921. received.push_back(msg);
  22922. }
  22923. });
  22924. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22925. // inside read_websocket_frame() when close() runs.
  22926. wait_for(peer_stalled);
  22927. ws.close();
  22928. reader.join();
  22929. handler_done = true;
  22930. });
  22931. auto port = svr.bind_to_any_port("127.0.0.1");
  22932. std::thread t([&]() { svr.listen_after_bind(); });
  22933. auto se = detail::scope_exit([&] {
  22934. svr.stop();
  22935. t.join();
  22936. });
  22937. svr.wait_until_ready();
  22938. auto send_bytes = [](socket_t s, const std::string &data) {
  22939. #ifdef _WIN32
  22940. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22941. #else
  22942. auto n = ::send(s, data.data(), data.size(), 0);
  22943. #endif
  22944. return n == static_cast<decltype(n)>(data.size());
  22945. };
  22946. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22947. // Every length used here fits the 7-bit length field.
  22948. auto masked_header = [](uint8_t first_byte, size_t len) {
  22949. std::string h;
  22950. h += static_cast<char>(first_byte);
  22951. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22952. h.append(4, '\0'); // mask key
  22953. return h;
  22954. };
  22955. for (int attempt = 0; attempt < attempts; attempt++) {
  22956. peer_stalled = false;
  22957. handler_done = false;
  22958. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22959. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22960. auto se_sock = detail::scope_exit([&] {
  22961. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22962. });
  22963. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22964. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22965. sockaddr_in addr{};
  22966. addr.sin_family = AF_INET;
  22967. addr.sin_port = htons(static_cast<uint16_t>(port));
  22968. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22969. ASSERT_EQ(
  22970. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22971. << "attempt " << attempt;
  22972. ASSERT_TRUE(send_bytes(sock,
  22973. "GET /ws HTTP/1.1\r\n"
  22974. "Host: 127.0.0.1\r\n"
  22975. "Upgrade: websocket\r\n"
  22976. "Connection: Upgrade\r\n"
  22977. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22978. "Sec-WebSocket-Version: 13\r\n"
  22979. "\r\n"))
  22980. << "attempt " << attempt;
  22981. std::string response;
  22982. while (response.find("\r\n\r\n") == std::string::npos) {
  22983. char buf[512];
  22984. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22985. if (n <= 0) { break; }
  22986. response.append(buf, static_cast<size_t>(n));
  22987. }
  22988. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22989. << "attempt " << attempt;
  22990. // Send the header of a Binary message but only the first prefix_len bytes
  22991. // of its payload, leaving the reader thread stalled inside the payload.
  22992. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22993. expected.substr(0, prefix_len)))
  22994. << "attempt " << attempt;
  22995. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22996. peer_stalled = true;
  22997. // Let close() send its Close frame and park in its own read before the
  22998. // rest of the payload arrives, so both threads are waiting for it.
  22999. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23000. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23001. close_frame += static_cast<char>(0x03); // status 1000
  23002. close_frame += static_cast<char>(0xE8);
  23003. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23004. << "attempt " << attempt;
  23005. // Closing the peer releases the reader thread even on the buggy path,
  23006. // where it waits for bytes another thread already consumed.
  23007. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23008. detail::close_socket(sock);
  23009. sock = INVALID_SOCKET;
  23010. wait_for(handler_done);
  23011. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23012. }
  23013. std::lock_guard<std::mutex> guard(received_mutex);
  23014. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23015. << "a message in flight when close() ran was dropped";
  23016. for (size_t i = 0; i < received.size(); i++) {
  23017. EXPECT_EQ(expected, received[i]) << "message " << i;
  23018. }
  23019. }
  23020. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23021. // returning the socket, or INVALID_SOCKET.
  23022. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23023. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23024. if (sock == INVALID_SOCKET) { return sock; }
  23025. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23026. sockaddr_in addr{};
  23027. addr.sin_family = AF_INET;
  23028. addr.sin_port = htons(static_cast<uint16_t>(port));
  23029. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23030. std::string req = "GET " + path +
  23031. " HTTP/1.1\r\n"
  23032. "Host: 127.0.0.1\r\n"
  23033. "Upgrade: websocket\r\n"
  23034. "Connection: Upgrade\r\n"
  23035. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23036. "Sec-WebSocket-Version: 13\r\n"
  23037. "\r\n";
  23038. std::string res;
  23039. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23040. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23041. static_cast<int>(req.size())) {
  23042. char c;
  23043. while (res.find("\r\n\r\n") == std::string::npos &&
  23044. ::recv(sock, &c, 1, 0) == 1) {
  23045. res += c;
  23046. }
  23047. }
  23048. if (res.find(" 101 ") == std::string::npos) {
  23049. detail::close_socket(sock);
  23050. return INVALID_SOCKET;
  23051. }
  23052. return sock;
  23053. }
  23054. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23055. // The payload must fit the 7-bit length field.
  23056. static std::string masked_frame(uint8_t first_byte,
  23057. const std::string &payload) {
  23058. std::string f;
  23059. f += static_cast<char>(first_byte);
  23060. f += static_cast<char>(0x80 | payload.size());
  23061. f.append(4, '\0');
  23062. return f + payload;
  23063. }
  23064. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23065. std::atomic<bool> done{false};
  23066. std::string received;
  23067. Server svr;
  23068. svr.set_websocket_ping_interval(0);
  23069. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23070. std::string msg;
  23071. if (ws.read(msg) == ws::Binary) { received = msg; }
  23072. done = true;
  23073. });
  23074. auto port = svr.bind_to_any_port("127.0.0.1");
  23075. std::thread t([&]() { svr.listen_after_bind(); });
  23076. auto se = detail::scope_exit([&] {
  23077. svr.stop();
  23078. t.join();
  23079. });
  23080. svr.wait_until_ready();
  23081. auto sock = connect_raw_websocket(port, "/ws");
  23082. ASSERT_NE(INVALID_SOCKET, sock);
  23083. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23084. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23085. masked_frame(0x89, "p") + // FIN + Ping
  23086. masked_frame(0x80, "lo"); // FIN + Continuation
  23087. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23088. for (int i = 0; i < 500 && !done; i++) {
  23089. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23090. }
  23091. ASSERT_TRUE(done);
  23092. EXPECT_EQ("Hello", received);
  23093. // The Ping between the fragments is answered with a Pong.
  23094. char pong[3];
  23095. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23096. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23097. }
  23098. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23099. Server svr;
  23100. svr.set_websocket_ping_interval(-1);
  23101. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23102. std::string msg;
  23103. while (ws.read(msg)) {}
  23104. });
  23105. auto port = svr.bind_to_any_port("127.0.0.1");
  23106. std::thread t([&]() { svr.listen_after_bind(); });
  23107. auto se = detail::scope_exit([&] {
  23108. svr.stop();
  23109. t.join();
  23110. });
  23111. svr.wait_until_ready();
  23112. auto sock = connect_raw_websocket(port, "/ws");
  23113. ASSERT_NE(INVALID_SOCKET, sock);
  23114. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23115. // Nothing comes while the client stays quiet.
  23116. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23117. char c;
  23118. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23119. }
  23120. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23121. Server svr;
  23122. svr.set_websocket_ping_interval(0);
  23123. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23124. std::string msg;
  23125. while (ws.read(msg)) {}
  23126. });
  23127. auto port = svr.bind_to_any_port("127.0.0.1");
  23128. std::thread t([&]() { svr.listen_after_bind(); });
  23129. auto se = detail::scope_exit([&] {
  23130. svr.stop();
  23131. t.join();
  23132. });
  23133. svr.wait_until_ready();
  23134. // Each Close payload and the reply it should get: an echo when valid, 1002
  23135. // otherwise.
  23136. std::vector<std::pair<std::string, std::string>> cases = {
  23137. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23138. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23139. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23140. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23141. };
  23142. // Also between the fragments of a message.
  23143. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23144. for (const auto &c : cases) {
  23145. auto sock = connect_raw_websocket(port, "/ws");
  23146. ASSERT_NE(INVALID_SOCKET, sock);
  23147. auto frames = prefix + masked_frame(0x88, c.first);
  23148. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23149. std::string reply;
  23150. char buf[256];
  23151. while (reply.size() < 2 + c.second.size()) {
  23152. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23153. if (n <= 0) { break; }
  23154. reply.append(buf, static_cast<size_t>(n));
  23155. }
  23156. detail::close_socket(sock);
  23157. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23158. c.second,
  23159. reply);
  23160. }
  23161. }
  23162. }
  23163. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23164. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23165. protected:
  23166. void SetUp() override {
  23167. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23168. SERVER_PRIVATE_KEY_FILE);
  23169. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23170. std::string msg;
  23171. ws::ReadResult ret;
  23172. while ((ret = ws.read(msg))) {
  23173. if (ret == ws::Binary) {
  23174. ws.send(msg.data(), msg.size());
  23175. } else {
  23176. ws.send(msg);
  23177. }
  23178. }
  23179. });
  23180. port_ = server_->bind_to_any_port(HOST);
  23181. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23182. server_->wait_until_ready();
  23183. }
  23184. void TearDown() override {
  23185. server_->stop();
  23186. if (server_thread_.joinable()) { server_thread_.join(); }
  23187. }
  23188. std::unique_ptr<SSLServer> server_;
  23189. std::thread server_thread_;
  23190. int port_ = 0;
  23191. };
  23192. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23193. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23194. {
  23195. ws::WebSocketClient client(url);
  23196. client.enable_server_certificate_verification(false);
  23197. auto calls = 0;
  23198. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23199. calls++;
  23200. return false;
  23201. });
  23202. EXPECT_FALSE(client.connect());
  23203. EXPECT_GT(calls, 0);
  23204. }
  23205. {
  23206. ws::WebSocketClient client(url);
  23207. client.enable_server_certificate_verification(false);
  23208. client.set_session_verifier([](tls::session_t) {
  23209. return SSLVerifierResponse::CertificateRejected;
  23210. });
  23211. EXPECT_FALSE(client.connect());
  23212. }
  23213. {
  23214. ws::WebSocketClient client(url);
  23215. client.enable_server_certificate_verification(false);
  23216. client.set_session_verifier([](tls::session_t) {
  23217. return SSLVerifierResponse::CertificateAccepted;
  23218. });
  23219. EXPECT_TRUE(client.connect());
  23220. }
  23221. }
  23222. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23223. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23224. "/ws-echo");
  23225. client.enable_server_certificate_verification(false);
  23226. ASSERT_TRUE(client.connect());
  23227. ASSERT_TRUE(client.is_open());
  23228. ASSERT_TRUE(client.send("Hello WSS"));
  23229. std::string msg;
  23230. EXPECT_EQ(ws::Text, client.read(msg));
  23231. EXPECT_EQ("Hello WSS", msg);
  23232. client.close();
  23233. }
  23234. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23235. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23236. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23237. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23238. // client (without calling close() first) is the only path that runs
  23239. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23240. // bug exactly.
  23241. //
  23242. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23243. // when linked against an instrumented libssl; run under Valgrind to catch it
  23244. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23245. // suite (the freed session otherwise stalls on the close handshake) — this test
  23246. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23247. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23248. {
  23249. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23250. "/ws-echo");
  23251. client.enable_server_certificate_verification(false);
  23252. client.set_read_timeout(2, 0);
  23253. client.set_write_timeout(2, 0);
  23254. ASSERT_TRUE(client.connect());
  23255. ASSERT_TRUE(client.is_open());
  23256. ASSERT_TRUE(client.send("still open"));
  23257. // Intentionally do NOT call client.close(): leaving scope runs
  23258. // shutdown_and_close() with the WebSocket still open, which must send the
  23259. // close frame while the TLS session is still alive.
  23260. }
  23261. }
  23262. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23263. // shutdown_and_close() at the start of connect(), reproducing the same
  23264. // use-after-free within the test body rather than at scope exit. The second
  23265. // connect must succeed and echo, proving the close handshake ran over a live
  23266. // session. See the note above about memory-tool requirements.
  23267. TEST_F(WebSocketSSLIntegrationTest,
  23268. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23269. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23270. "/ws-echo");
  23271. client.enable_server_certificate_verification(false);
  23272. client.set_read_timeout(2, 0);
  23273. client.set_write_timeout(2, 0);
  23274. ASSERT_TRUE(client.connect());
  23275. ASSERT_TRUE(client.is_open());
  23276. ASSERT_TRUE(client.send("still open"));
  23277. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23278. // the still-open connection, which must not touch a freed TLS session.
  23279. ASSERT_TRUE(client.connect());
  23280. ASSERT_TRUE(client.is_open());
  23281. ASSERT_TRUE(client.send("after reconnect"));
  23282. std::string msg;
  23283. EXPECT_EQ(ws::Text, client.read(msg));
  23284. EXPECT_EQ("after reconnect", msg);
  23285. client.close();
  23286. }
  23287. #endif
  23288. #ifdef CPPHTTPLIB_SSL_ENABLED
  23289. class WebSocketSSLCATest : public ::testing::Test {
  23290. protected:
  23291. void SetUp() override {
  23292. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23293. SERVER_PRIVATE_KEY_FILE);
  23294. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23295. std::string msg;
  23296. while (ws.read(msg)) {
  23297. ws.send(msg);
  23298. }
  23299. });
  23300. port_ = server_->bind_to_any_port("127.0.0.1");
  23301. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23302. server_->wait_until_ready();
  23303. }
  23304. void TearDown() override {
  23305. server_->stop();
  23306. if (server_thread_.joinable()) { server_thread_.join(); }
  23307. }
  23308. std::string url() const {
  23309. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23310. }
  23311. std::unique_ptr<SSLServer> server_;
  23312. std::thread server_thread_;
  23313. int port_ = 0;
  23314. };
  23315. // A custom CA loaded as PEM verifies the server with full certificate
  23316. // verification enabled
  23317. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23318. ws::WebSocketClient client(url());
  23319. std::string cert;
  23320. read_file(SERVER_CERT2_FILE, cert);
  23321. client.load_ca_cert_store(cert.c_str(), cert.size());
  23322. ASSERT_TRUE(client.connect());
  23323. ASSERT_TRUE(client.send("hello"));
  23324. std::string msg;
  23325. EXPECT_EQ(ws::Text, client.read(msg));
  23326. EXPECT_EQ("hello", msg);
  23327. client.close();
  23328. }
  23329. // A custom CA that does not cover the server must fail verification (the
  23330. // custom CA is exclusive; system certs are not loaded alongside it)
  23331. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23332. ws::WebSocketClient client(url());
  23333. std::string cert;
  23334. read_file(CLIENT_CA_CERT_FILE, cert);
  23335. client.load_ca_cert_store(cert.c_str(), cert.size());
  23336. auto res = client.connect();
  23337. ASSERT_FALSE(res);
  23338. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23339. EXPECT_EQ(-1, res.status());
  23340. EXPECT_NE(0u, res.ssl_backend_error());
  23341. }
  23342. // The same CA as a file path rather than PEM in memory
  23343. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23344. ws::WebSocketClient client(url());
  23345. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23346. ASSERT_TRUE(client.connect());
  23347. ASSERT_TRUE(client.send("hello"));
  23348. std::string msg;
  23349. EXPECT_EQ(ws::Text, client.read(msg));
  23350. EXPECT_EQ("hello", msg);
  23351. client.close();
  23352. }
  23353. // ...and a CA file that does not cover the server still fails, so it is the
  23354. // path above that decides the outcome
  23355. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23356. ws::WebSocketClient client(url());
  23357. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23358. ASSERT_FALSE(client.connect());
  23359. }
  23360. // Regression test: reconnecting with a native custom CA store used to reuse
  23361. // a store handle the previous TLS context had already freed (use-after-free
  23362. // under the OpenSSL backend). The context now lives as long as the client.
  23363. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23364. ws::WebSocketClient client(url());
  23365. std::string cert;
  23366. read_file(SERVER_CERT2_FILE, cert);
  23367. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23368. ASSERT_TRUE(client.connect());
  23369. client.close();
  23370. ASSERT_TRUE(client.connect());
  23371. ASSERT_TRUE(client.send("again"));
  23372. std::string msg;
  23373. EXPECT_EQ(ws::Text, client.read(msg));
  23374. EXPECT_EQ("again", msg);
  23375. client.close();
  23376. }
  23377. // Regression test: a certificate with a trusted chain but no identity match
  23378. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23379. // verification entirely for IP hosts, so this connection succeeded there.
  23380. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23381. // chain verification while the identity check must still fail.
  23382. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23384. ASSERT_TRUE(svr.is_valid());
  23385. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23386. std::string msg;
  23387. while (ws.read(msg)) {
  23388. ws.send(msg);
  23389. }
  23390. });
  23391. auto port = svr.bind_to_any_port("127.0.0.1");
  23392. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23393. auto se = detail::scope_exit([&] {
  23394. svr.stop();
  23395. t.join();
  23396. });
  23397. svr.wait_until_ready();
  23398. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23399. "/echo");
  23400. std::string cert;
  23401. read_file(SERVER_CERT_FILE, cert);
  23402. client.load_ca_cert_store(cert.c_str(), cert.size());
  23403. ASSERT_FALSE(client.connect());
  23404. }
  23405. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23406. // SNI, so nothing binds the host name to the TLS session. These bind the
  23407. // server to "localhost" instead, the only shape that exercises the SNI and
  23408. // hostname-verification path with certificate verification left enabled.
  23409. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23410. protected:
  23411. void Start(const char *cert_file) {
  23412. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23413. SERVER_PRIVATE_KEY_FILE);
  23414. ASSERT_TRUE(server_->is_valid());
  23415. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23416. std::string msg;
  23417. while (ws.read(msg)) {
  23418. ws.send(msg);
  23419. }
  23420. });
  23421. port_ = server_->bind_to_any_port("localhost");
  23422. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23423. server_->wait_until_ready();
  23424. }
  23425. void TearDown() override {
  23426. if (server_) { server_->stop(); }
  23427. if (server_thread_.joinable()) { server_thread_.join(); }
  23428. }
  23429. std::string url() const {
  23430. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23431. }
  23432. std::unique_ptr<SSLServer> server_;
  23433. std::thread server_thread_;
  23434. int port_ = 0;
  23435. };
  23436. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23437. // out and the connection is usable
  23438. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23439. Start(SERVER_CERT2_FILE);
  23440. ws::WebSocketClient client(url());
  23441. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23442. ASSERT_TRUE(client.connect());
  23443. ASSERT_TRUE(client.send("hello"));
  23444. std::string msg;
  23445. EXPECT_EQ(ws::Text, client.read(msg));
  23446. EXPECT_EQ("hello", msg);
  23447. client.close();
  23448. }
  23449. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23450. // while the identity check must still reject "localhost"
  23451. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23452. Start(SERVER_CERT_FILE);
  23453. ws::WebSocketClient client(url());
  23454. client.set_ca_cert_path(SERVER_CERT_FILE);
  23455. auto res = client.connect();
  23456. ASSERT_FALSE(res);
  23457. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23458. EXPECT_EQ(-1, res.status());
  23459. }
  23460. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23461. // disabled: the chain is still checked, only the identity check is skipped
  23462. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23463. Start(SERVER_CERT_FILE);
  23464. ws::WebSocketClient client(url());
  23465. client.set_ca_cert_path(SERVER_CERT_FILE);
  23466. client.enable_server_hostname_verification(false);
  23467. ASSERT_TRUE(client.connect());
  23468. ASSERT_TRUE(client.send("hello"));
  23469. std::string msg;
  23470. EXPECT_EQ(ws::Text, client.read(msg));
  23471. EXPECT_EQ("hello", msg);
  23472. client.close();
  23473. }
  23474. // A CA that did not sign the server certificate fails the chain, even though
  23475. // the name would match
  23476. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23477. Start(SERVER_CERT2_FILE);
  23478. ws::WebSocketClient client(url());
  23479. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23480. ASSERT_FALSE(client.connect());
  23481. }
  23482. // With verification disabled, neither the chain nor the name is checked
  23483. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23484. Start(SERVER_CERT_FILE);
  23485. ws::WebSocketClient client(url());
  23486. client.enable_server_certificate_verification(false);
  23487. ASSERT_TRUE(client.connect());
  23488. ASSERT_TRUE(client.send("hello"));
  23489. std::string msg;
  23490. EXPECT_EQ(ws::Text, client.read(msg));
  23491. EXPECT_EQ("hello", msg);
  23492. client.close();
  23493. }
  23494. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23495. protected:
  23496. void SetUp() override {
  23497. server_ = httplib::detail::make_unique<SSLServer>(
  23498. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23499. ASSERT_TRUE(server_->is_valid());
  23500. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23501. std::string msg;
  23502. while (ws.read(msg)) {
  23503. ws.send(msg);
  23504. }
  23505. });
  23506. port_ = server_->bind_to_any_port("localhost");
  23507. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23508. server_->wait_until_ready();
  23509. }
  23510. void TearDown() override {
  23511. server_->stop();
  23512. if (server_thread_.joinable()) { server_thread_.join(); }
  23513. }
  23514. std::string url() const {
  23515. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23516. }
  23517. void ConnectWithClientCert(const std::string &client_cert_file,
  23518. const std::string &client_private_key_file,
  23519. const char *private_key_password) {
  23520. std::string cert_pem, key_pem;
  23521. read_file(client_cert_file, cert_pem);
  23522. read_file(client_private_key_file, key_pem);
  23523. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23524. key_pem.c_str(), key_pem.size(),
  23525. private_key_password};
  23526. ws::WebSocketClient client(url(), pem);
  23527. ASSERT_TRUE(client.is_valid());
  23528. client.enable_server_certificate_verification(false);
  23529. ASSERT_TRUE(client.connect());
  23530. ASSERT_TRUE(client.send("hello"));
  23531. std::string msg;
  23532. EXPECT_EQ(ws::Text, client.read(msg));
  23533. EXPECT_EQ("hello", msg);
  23534. client.close();
  23535. }
  23536. std::unique_ptr<SSLServer> server_;
  23537. std::thread server_thread_;
  23538. int port_ = 0;
  23539. };
  23540. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23541. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23542. }
  23543. // Control for the tests above: the fixture's server really does require a
  23544. // client certificate, so it is the PEM the constructor installed that decides
  23545. // the outcome.
  23546. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23547. ws::WebSocketClient client(url());
  23548. ASSERT_TRUE(client.is_valid());
  23549. client.enable_server_certificate_verification(false);
  23550. EXPECT_FALSE(client.connect());
  23551. }
  23552. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23553. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23554. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23555. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23556. }
  23557. #endif
  23558. #if !defined(_WIN32)
  23559. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23560. auto secret_dir = std::string("./symlink_test_secret");
  23561. auto served_dir = std::string("./symlink_test_served");
  23562. auto secret_file = secret_dir + "/secret.txt";
  23563. auto symlink_path = served_dir + "/escape";
  23564. // Setup: create directories and files
  23565. mkdir(secret_dir.c_str(), 0755);
  23566. mkdir(served_dir.c_str(), 0755);
  23567. {
  23568. std::ofstream ofs(secret_file);
  23569. ofs << "SECRET_DATA";
  23570. }
  23571. // Create symlink using absolute path so it resolves correctly
  23572. #ifdef PATH_MAX
  23573. char abs_secret[PATH_MAX];
  23574. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23575. #else
  23576. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23577. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23578. ASSERT_NE(nullptr, abs_secret);
  23579. #endif
  23580. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23581. auto se = detail::scope_exit([&] {
  23582. unlink(symlink_path.c_str());
  23583. unlink(secret_file.c_str());
  23584. rmdir(served_dir.c_str());
  23585. rmdir(secret_dir.c_str());
  23586. });
  23587. Server svr;
  23588. svr.set_mount_point("/", served_dir);
  23589. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23590. auto se2 = detail::scope_exit([&] {
  23591. svr.stop();
  23592. listen_thread.join();
  23593. });
  23594. svr.wait_until_ready();
  23595. Client cli("localhost", PORT);
  23596. // Symlink pointing outside base dir should be blocked
  23597. auto res = cli.Get("/escape/secret.txt");
  23598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23599. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23600. }
  23601. #endif
  23602. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23603. // "GET /smuggled" request), reads the first response, and only then sends the
  23604. // embedded request as the body. Returns how many times /smuggled ran.
  23605. //
  23606. // The body is sent AFTER receiving the first response (as in the original
  23607. // PoC) so that the stream_line_reader cannot buffer it together with the
  23608. // headers of the first request.
  23609. static int count_smuggled_requests(const std::string &outer_head,
  23610. std::string &first_response) {
  23611. Server svr;
  23612. svr.set_mount_point("/", "./www");
  23613. std::atomic<int> smuggled_count(0);
  23614. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23615. smuggled_count++;
  23616. res.set_content("oops", "text/plain");
  23617. });
  23618. svr.Post("/post", [&](const Request &req, Response &res) {
  23619. res.set_content(req.body, "text/plain");
  23620. });
  23621. auto port = svr.bind_to_any_port("localhost");
  23622. thread t = thread([&] { svr.listen_after_bind(); });
  23623. auto se = detail::scope_exit([&] {
  23624. svr.stop();
  23625. t.join();
  23626. });
  23627. svr.wait_until_ready();
  23628. auto error = Error::Success;
  23629. auto sock = detail::create_client_socket(
  23630. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23631. /*connection_timeout_sec=*/2, 0,
  23632. /*read_timeout_sec=*/2, 0,
  23633. /*write_timeout_sec=*/2, 0, std::string(), error);
  23634. EXPECT_NE(INVALID_SOCKET, sock);
  23635. if (sock == INVALID_SOCKET) { return -1; }
  23636. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23637. // The "smuggled" request will be sent as the body of the outer request
  23638. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23639. "Host: localhost\r\n"
  23640. "Connection: close\r\n"
  23641. "\r\n";
  23642. auto head = outer_head;
  23643. auto len = std::to_string(smuggled.size());
  23644. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23645. pos = head.find("{len}", pos + len.size())) {
  23646. head.replace(pos, 5, len);
  23647. }
  23648. // Step 1: Send only the outer request headers (no body yet)
  23649. auto sent = send(sock, head.data(), head.size(), 0);
  23650. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23651. // Step 2: Read the first response
  23652. char buf[4096];
  23653. for (;;) {
  23654. auto n = recv(sock, buf, sizeof(buf), 0);
  23655. if (n <= 0) break;
  23656. first_response.append(buf, static_cast<size_t>(n));
  23657. // Stop once we have a complete response (headers + body)
  23658. auto hdr_end = first_response.find("\r\n\r\n");
  23659. if (hdr_end != std::string::npos) {
  23660. // Check for Content-Length to know when the body is complete
  23661. auto cl_pos = first_response.find("Content-Length:");
  23662. if (cl_pos != std::string::npos) {
  23663. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23664. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23665. auto cl = std::stoul(
  23666. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23667. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23668. } else {
  23669. break; // No Content-Length, assume headers-only response
  23670. }
  23671. }
  23672. }
  23673. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23674. // vulnerable server the keep-alive loop reads this as a second request. The
  23675. // server may already have closed the connection, so the result is ignored.
  23676. send(sock, smuggled.data(), smuggled.size(), 0);
  23677. // Half-close so that a server which drained the body sees EOF and closes,
  23678. // instead of the read below waiting for the read timeout.
  23679. #ifdef _WIN32
  23680. ::shutdown(sock, SD_SEND);
  23681. #else
  23682. ::shutdown(sock, SHUT_WR);
  23683. #endif
  23684. // Step 4: Read until the server closes the connection
  23685. for (;;) {
  23686. auto n = recv(sock, buf, sizeof(buf), 0);
  23687. if (n <= 0) break;
  23688. }
  23689. return smuggled_count.load();
  23690. }
  23691. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23692. // A GET request with Content-Length to a static file handler must have its
  23693. // body drained before the keep-alive connection is reused. Otherwise the
  23694. // unread body bytes are interpreted as the next HTTP request.
  23695. std::string first_response;
  23696. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23697. "Host: localhost\r\n"
  23698. "Content-Length: {len}\r\n"
  23699. "\r\n",
  23700. first_response));
  23701. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23702. }
  23703. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23704. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23705. // be answered with 400 and the connection closed. Treating it as "no body"
  23706. // leaves the body to be parsed as the next request.
  23707. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23708. const char *targets[] = {
  23709. "GET /file", // handler that never reads the body
  23710. "GET /not-found", // no handler matches (404)
  23711. "POST /post", // handler that reads the body
  23712. };
  23713. for (auto target : targets) {
  23714. for (auto value : values) {
  23715. std::string first_response;
  23716. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23717. " HTTP/1.1\r\n"
  23718. "Host: localhost\r\n"
  23719. "Content-Length: " +
  23720. value + "\r\n\r\n",
  23721. first_response))
  23722. << target << " with Content-Length: " << value;
  23723. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23724. << target << " with Content-Length: " << value;
  23725. }
  23726. }
  23727. }
  23728. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23729. // A 400 for an unparseable request line leaves the rest of the message
  23730. // unread, so the connection must be closed rather than reused.
  23731. std::string first_response;
  23732. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23733. "Host: localhost\r\n"
  23734. "Content-Length: {len}\r\n"
  23735. "\r\n",
  23736. first_response));
  23737. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23738. }
  23739. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23740. // Same as above for a header block that fails to parse.
  23741. std::string first_response;
  23742. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23743. "Host: localhost\r\n"
  23744. "Bad Header\r\n"
  23745. "Content-Length: {len}\r\n"
  23746. "\r\n",
  23747. first_response));
  23748. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23749. }
  23750. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23751. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23752. // server must not read another request on that connection, even when the
  23753. // request had no body to drain.
  23754. std::string first_response;
  23755. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23756. "Host: localhost\r\n"
  23757. "\r\n",
  23758. first_response));
  23759. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23760. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23761. }
  23762. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23763. // A content reader that stops early leaves the stream inside the body.
  23764. // Draining the whole Content-Length from there, or reading the body again,
  23765. // reads into the next request, and whatever follows is parsed as a request
  23766. // of its own.
  23767. Server svr;
  23768. std::atomic<int> smuggled_count(0);
  23769. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23770. svr.Post("/upload", [](const Request &req, Response &res,
  23771. const ContentReader &content_reader) {
  23772. // Stop at the last chunk, so the whole body has been read however it
  23773. // arrives.
  23774. auto length = req.get_header_value_u64("Content-Length");
  23775. size_t total = 0;
  23776. auto consumed = content_reader([&](const char *, size_t n) {
  23777. total += n;
  23778. return total < length;
  23779. });
  23780. EXPECT_FALSE(consumed);
  23781. if (req.has_param("retry")) {
  23782. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23783. }
  23784. // Replace the 400 the aborted read set, which would close the connection.
  23785. res.set_redirect("/done");
  23786. });
  23787. auto port = svr.bind_to_any_port(HOST);
  23788. thread t = thread([&] { svr.listen_after_bind(); });
  23789. auto se = detail::scope_exit([&] {
  23790. svr.stop();
  23791. t.join();
  23792. });
  23793. svr.wait_until_ready();
  23794. // A front end sees the second request as a POST whose body is the GET. The
  23795. // first body is as long as the POST's headers, so draining it again reads
  23796. // exactly those and leaves the GET to be parsed next.
  23797. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23798. "Host: localhost\r\n"
  23799. "\r\n";
  23800. std::string second_head = "POST /post HTTP/1.1\r\n"
  23801. "Host: localhost\r\n"
  23802. "Content-Length: " +
  23803. std::to_string(inner.size()) +
  23804. "\r\n"
  23805. "\r\n";
  23806. for (auto target : {"/upload", "/upload?retry"}) {
  23807. smuggled_count = 0;
  23808. std::string request = "POST " + std::string(target) +
  23809. " HTTP/1.1\r\n"
  23810. "Host: localhost\r\n"
  23811. "Content-Length: " +
  23812. std::to_string(second_head.size()) +
  23813. "\r\n"
  23814. "\r\n" +
  23815. std::string(second_head.size(), 'A') + second_head +
  23816. inner;
  23817. std::string response;
  23818. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23819. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23820. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23821. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23822. EXPECT_EQ(0, smuggled_count.load()) << target;
  23823. }
  23824. }
  23825. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23826. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23827. // must be rejected with 400 Bad Request.
  23828. Server svr;
  23829. svr.Post("/test", [&](const Request &, Response &res) {
  23830. res.set_content("ok", "text/plain");
  23831. });
  23832. thread t = thread([&] { svr.listen(HOST, PORT); });
  23833. auto se = detail::scope_exit([&] {
  23834. svr.stop();
  23835. t.join();
  23836. ASSERT_FALSE(svr.is_running());
  23837. });
  23838. svr.wait_until_ready();
  23839. // Exact "chunked"
  23840. {
  23841. auto req = "POST /test HTTP/1.1\r\n"
  23842. "Host: localhost\r\n"
  23843. "Content-Length: 5\r\n"
  23844. "Transfer-Encoding: chunked\r\n"
  23845. "Connection: close\r\n"
  23846. "\r\n"
  23847. "hello";
  23848. std::string response;
  23849. ASSERT_TRUE(send_request(1, req, &response));
  23850. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23851. response.substr(0, response.find("\r\n")));
  23852. }
  23853. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23854. {
  23855. auto req = "POST /test HTTP/1.1\r\n"
  23856. "Host: localhost\r\n"
  23857. "Content-Length: 5\r\n"
  23858. "Transfer-Encoding: gzip, chunked\r\n"
  23859. "Connection: close\r\n"
  23860. "\r\n"
  23861. "hello";
  23862. std::string response;
  23863. ASSERT_TRUE(send_request(1, req, &response));
  23864. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23865. response.substr(0, response.find("\r\n")));
  23866. }
  23867. }
  23868. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23869. Server svr;
  23870. svr.Post("/test", [&](const Request &, Response &res) {
  23871. res.set_content("ok", "text/plain");
  23872. });
  23873. thread t = thread([&] { svr.listen(HOST, PORT); });
  23874. auto se = detail::scope_exit([&] {
  23875. svr.stop();
  23876. t.join();
  23877. ASSERT_FALSE(svr.is_running());
  23878. });
  23879. svr.wait_until_ready();
  23880. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23881. // length cannot be determined, so the server must answer 400 and close
  23882. // rather than treat the request as bodyless and leave the body in the
  23883. // socket for the next request to pick up.
  23884. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23885. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23886. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23887. std::string response;
  23888. ASSERT_TRUE(send_request(1, req, &response));
  23889. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23890. response.substr(0, response.find("\r\n")))
  23891. << transfer_encoding;
  23892. }
  23893. // RFC 9110 5.3: the codings may also be split across several
  23894. // Transfer-Encoding lines, which combine in the order they were received.
  23895. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23896. // just like the single-line "chunked, gzip" above.
  23897. {
  23898. auto req = "POST /test HTTP/1.1\r\n"
  23899. "Host: localhost\r\n"
  23900. "Transfer-Encoding: chunked\r\n"
  23901. "Transfer-Encoding: gzip\r\n"
  23902. "\r\n"
  23903. "0\r\n\r\n";
  23904. std::string response;
  23905. ASSERT_TRUE(send_request(1, req, &response));
  23906. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23907. response.substr(0, response.find("\r\n")));
  23908. }
  23909. // A sequence ending in chunked stays valid.
  23910. auto req = "POST /test HTTP/1.1\r\n"
  23911. "Host: localhost\r\n"
  23912. "Transfer-Encoding: gzip, chunked\r\n"
  23913. "Connection: close\r\n"
  23914. "\r\n"
  23915. "0\r\n\r\n";
  23916. std::string response;
  23917. ASSERT_TRUE(send_request(1, req, &response));
  23918. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23919. // ...including when it is spread over several lines.
  23920. auto split_req = "POST /test HTTP/1.1\r\n"
  23921. "Host: localhost\r\n"
  23922. "Transfer-Encoding: gzip\r\n"
  23923. "Transfer-Encoding: chunked\r\n"
  23924. "Connection: close\r\n"
  23925. "\r\n"
  23926. "0\r\n\r\n";
  23927. std::string split_response;
  23928. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23929. EXPECT_EQ("HTTP/1.1 200 OK",
  23930. split_response.substr(0, split_response.find("\r\n")));
  23931. }
  23932. // Regression for issue #2450: a DELETE without Content-Length on a
  23933. // keep-alive connection must not let the post-response drain consume the
  23934. // next request's bytes.
  23935. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23936. Server svr;
  23937. std::atomic<int> delete_count(0);
  23938. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23939. delete_count++;
  23940. res.status = StatusCode::NoContent_204;
  23941. });
  23942. auto port = svr.bind_to_any_port(HOST);
  23943. thread t = thread([&] { svr.listen_after_bind(); });
  23944. auto se = detail::scope_exit([&] {
  23945. svr.stop();
  23946. t.join();
  23947. });
  23948. svr.wait_until_ready();
  23949. auto error = Error::Success;
  23950. auto sock = detail::create_client_socket(
  23951. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23952. /*connection_timeout_sec=*/2, 0,
  23953. /*read_timeout_sec=*/2, 0,
  23954. /*write_timeout_sec=*/2, 0, std::string(), error);
  23955. ASSERT_NE(INVALID_SOCKET, sock);
  23956. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23957. auto send_request_and_read_response = [&](const std::string &req,
  23958. std::string &out) -> bool {
  23959. auto sent = send(sock, req.data(), req.size(), 0);
  23960. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23961. char buf[4096];
  23962. for (;;) {
  23963. auto n = recv(sock, buf, sizeof(buf), 0);
  23964. if (n <= 0) { return !out.empty(); }
  23965. out.append(buf, static_cast<size_t>(n));
  23966. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23967. }
  23968. };
  23969. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23970. "Host: localhost\r\n"
  23971. "\r\n";
  23972. std::string resp1;
  23973. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23974. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23975. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23976. "Host: localhost\r\n"
  23977. "Connection: close\r\n"
  23978. "\r\n";
  23979. std::string resp2;
  23980. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23981. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23982. EXPECT_EQ(2, delete_count.load());
  23983. }
  23984. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23985. Server svr;
  23986. svr.Post("/ingest", [&](const Request &, Response &res,
  23987. const ContentReader &content_reader) {
  23988. auto consumed = content_reader([](const char *, size_t) { return false; });
  23989. EXPECT_FALSE(consumed);
  23990. res.status = StatusCode::Conflict_409;
  23991. res.set_header("Connection", "close");
  23992. });
  23993. auto port = svr.bind_to_any_port(HOST);
  23994. thread t = thread([&] { svr.listen_after_bind(); });
  23995. auto se = detail::scope_exit([&] {
  23996. svr.stop();
  23997. t.join();
  23998. });
  23999. svr.wait_until_ready();
  24000. auto error = Error::Success;
  24001. auto sock = detail::create_client_socket(
  24002. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24003. /*connection_timeout_sec=*/2, 0,
  24004. /*read_timeout_sec=*/1, 0,
  24005. /*write_timeout_sec=*/2, 0, std::string(), error);
  24006. ASSERT_NE(INVALID_SOCKET, sock);
  24007. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24008. std::string request = "POST /ingest HTTP/1.1\r\n"
  24009. "Host: localhost\r\n"
  24010. "Transfer-Encoding: chunked\r\n"
  24011. "\r\n"
  24012. "4\r\n"
  24013. "data\r\n";
  24014. auto sent = send(sock, request.data(), request.size(), 0);
  24015. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24016. std::string response;
  24017. ssize_t received = 0;
  24018. do {
  24019. char buf[4096];
  24020. received = recv(sock, buf, sizeof(buf), 0);
  24021. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24022. } while (received > 0);
  24023. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24024. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24025. EXPECT_EQ(0, received);
  24026. }
  24027. namespace no_proxy_test {
  24028. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24029. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24030. // calling listen().
  24031. class ScopedServer {
  24032. public:
  24033. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24034. ~ScopedServer() {
  24035. svr_.stop();
  24036. if (th_.joinable()) { th_.join(); }
  24037. }
  24038. Server &svr() { return svr_; }
  24039. int port() const { return port_; }
  24040. void listen() {
  24041. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24042. svr_.wait_until_ready();
  24043. }
  24044. private:
  24045. Server svr_;
  24046. std::thread th_;
  24047. int port_ = 0;
  24048. };
  24049. class ProxyAndTargetServers {
  24050. public:
  24051. ProxyAndTargetServers() {
  24052. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24053. proxy_hits_++;
  24054. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24055. res.set_content("via-proxy", "text/plain");
  24056. });
  24057. target_.Get(".*", [this](const Request &req, Response &res) {
  24058. target_hits_++;
  24059. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24060. res.set_content("direct", "text/plain");
  24061. });
  24062. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24063. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24064. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24065. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24066. proxy_mock_.wait_until_ready();
  24067. target_.wait_until_ready();
  24068. }
  24069. ~ProxyAndTargetServers() {
  24070. proxy_mock_.stop();
  24071. target_.stop();
  24072. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24073. if (target_thread_.joinable()) { target_thread_.join(); }
  24074. }
  24075. Server &proxy_mock() { return proxy_mock_; }
  24076. Server &target() { return target_; }
  24077. int proxy_port() const { return proxy_port_; }
  24078. int target_port() const { return target_port_; }
  24079. int proxy_hits() const { return proxy_hits_.load(); }
  24080. int target_hits() const { return target_hits_.load(); }
  24081. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24082. void reset_counters() {
  24083. proxy_hits_ = 0;
  24084. target_hits_ = 0;
  24085. last_had_proxy_authz_ = false;
  24086. }
  24087. private:
  24088. Server proxy_mock_;
  24089. Server target_;
  24090. std::thread proxy_thread_;
  24091. std::thread target_thread_;
  24092. int proxy_port_ = 0;
  24093. int target_port_ = 0;
  24094. std::atomic<int> proxy_hits_{0};
  24095. std::atomic<int> target_hits_{0};
  24096. std::atomic<bool> last_had_proxy_authz_{false};
  24097. };
  24098. inline std::unique_ptr<Client> make_client(const std::string &host,
  24099. ProxyAndTargetServers &s) {
  24100. auto cli = detail::make_unique<Client>(host, s.target_port());
  24101. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24102. cli->set_proxy("127.0.0.1", s.proxy_port());
  24103. return cli;
  24104. }
  24105. } // namespace no_proxy_test
  24106. using no_proxy_test::make_client;
  24107. using no_proxy_test::ProxyAndTargetServers;
  24108. TEST(NoProxyTest, ExactHostnameBypasses) {
  24109. ProxyAndTargetServers s;
  24110. auto cli = make_client("example.com", s);
  24111. cli->set_no_proxy({"example.com"});
  24112. auto res = cli->Get("/");
  24113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24114. EXPECT_EQ(0, s.proxy_hits());
  24115. EXPECT_EQ(1, s.target_hits());
  24116. }
  24117. TEST(NoProxyTest, SubdomainBypasses) {
  24118. ProxyAndTargetServers s;
  24119. auto cli = make_client("foo.example.com", s);
  24120. cli->set_no_proxy({"example.com"});
  24121. auto res = cli->Get("/");
  24122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24123. EXPECT_EQ(0, s.proxy_hits());
  24124. EXPECT_EQ(1, s.target_hits());
  24125. }
  24126. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24127. // Regression guard: "evilexample.com" must not be considered a subdomain
  24128. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24129. // check would let traffic bypass the proxy and leak credentials direct
  24130. // to the attacker host.
  24131. ProxyAndTargetServers s;
  24132. auto cli = make_client("evilexample.com", s);
  24133. cli->set_no_proxy({"example.com"});
  24134. auto res = cli->Get("/");
  24135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24136. EXPECT_GE(s.proxy_hits(), 1);
  24137. EXPECT_EQ(0, s.target_hits());
  24138. }
  24139. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24140. ProxyAndTargetServers s;
  24141. auto cli = make_client("example.com.evil.com", s);
  24142. cli->set_no_proxy({"example.com"});
  24143. auto res = cli->Get("/");
  24144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24145. EXPECT_GE(s.proxy_hits(), 1);
  24146. EXPECT_EQ(0, s.target_hits());
  24147. }
  24148. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24149. ProxyAndTargetServers s;
  24150. auto cli = make_client("example.com", s);
  24151. cli->set_no_proxy({".example.com"});
  24152. auto res = cli->Get("/");
  24153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24154. EXPECT_EQ(0, s.proxy_hits());
  24155. EXPECT_EQ(1, s.target_hits());
  24156. }
  24157. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24158. ProxyAndTargetServers s;
  24159. auto cli = make_client("Example.COM", s);
  24160. cli->set_no_proxy({"EXAMPLE.com"});
  24161. auto res = cli->Get("/");
  24162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24163. EXPECT_EQ(0, s.proxy_hits());
  24164. EXPECT_EQ(1, s.target_hits());
  24165. }
  24166. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24167. ProxyAndTargetServers s;
  24168. auto cli = make_client("example.com.", s);
  24169. cli->set_no_proxy({"example.com"});
  24170. auto res = cli->Get("/");
  24171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24172. EXPECT_EQ(0, s.proxy_hits());
  24173. EXPECT_EQ(1, s.target_hits());
  24174. }
  24175. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24176. // Trailing dots must be normalized on BOTH sides — host and entry.
  24177. // An implementation that only strips the host-side trailing dot would
  24178. // fail to match host "example.com" against entry "example.com." because
  24179. // a literal substring search would compare 11 chars against 12.
  24180. ProxyAndTargetServers s;
  24181. auto cli = make_client("example.com", s);
  24182. cli->set_no_proxy({"example.com."});
  24183. auto res = cli->Get("/");
  24184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24185. EXPECT_EQ(0, s.proxy_hits());
  24186. EXPECT_EQ(1, s.target_hits());
  24187. }
  24188. TEST(NoProxyTest, WildcardBypassesEverything) {
  24189. ProxyAndTargetServers s;
  24190. auto cli = make_client("anything.invalid.test", s);
  24191. cli->set_no_proxy({"*"});
  24192. auto res = cli->Get("/");
  24193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24194. EXPECT_EQ(0, s.proxy_hits());
  24195. EXPECT_EQ(1, s.target_hits());
  24196. }
  24197. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24198. ProxyAndTargetServers s;
  24199. Client cli("127.0.0.1", s.target_port());
  24200. cli.set_proxy("127.0.0.1", s.proxy_port());
  24201. cli.set_no_proxy({"127.0.0.1"});
  24202. auto res = cli.Get("/");
  24203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24204. EXPECT_EQ(0, s.proxy_hits());
  24205. EXPECT_EQ(1, s.target_hits());
  24206. }
  24207. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24208. ProxyAndTargetServers s;
  24209. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24210. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24211. cli.set_proxy("127.0.0.1", s.proxy_port());
  24212. cli.set_no_proxy({"::1"});
  24213. auto res = cli.Get("/");
  24214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24215. EXPECT_EQ(0, s.proxy_hits());
  24216. EXPECT_EQ(1, s.target_hits());
  24217. }
  24218. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24219. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24220. // must still be recognized as IPv6 for CIDR matching. Implementations
  24221. // that detect IPv6 only when the host begins with '[' would parse the
  24222. // host as a hostname and miss the match.
  24223. ProxyAndTargetServers s;
  24224. Client cli("fe80::1", s.target_port());
  24225. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24226. cli.set_proxy("127.0.0.1", s.proxy_port());
  24227. cli.set_no_proxy({"fe80::/10"});
  24228. auto res = cli.Get("/");
  24229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24230. EXPECT_EQ(0, s.proxy_hits());
  24231. EXPECT_EQ(1, s.target_hits());
  24232. }
  24233. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24234. ProxyAndTargetServers s;
  24235. Client cli("::1", s.target_port());
  24236. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24237. cli.set_proxy("127.0.0.1", s.proxy_port());
  24238. cli.set_no_proxy({"[::1]"});
  24239. auto res = cli.Get("/");
  24240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24241. EXPECT_EQ(0, s.proxy_hits());
  24242. EXPECT_EQ(1, s.target_hits());
  24243. }
  24244. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24245. ProxyAndTargetServers s;
  24246. Client cli("fe80::1", s.target_port());
  24247. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24248. cli.set_proxy("127.0.0.1", s.proxy_port());
  24249. cli.set_no_proxy({"[fe80::]/10"});
  24250. auto res = cli.Get("/");
  24251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24252. EXPECT_EQ(0, s.proxy_hits());
  24253. EXPECT_EQ(1, s.target_hits());
  24254. }
  24255. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24256. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24257. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24258. // tricks via address-family conversion.
  24259. ProxyAndTargetServers s;
  24260. Client cli("::ffff:127.0.0.1", s.target_port());
  24261. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24262. cli.set_proxy("127.0.0.1", s.proxy_port());
  24263. cli.set_no_proxy({"127.0.0.1"});
  24264. auto res = cli.Get("/");
  24265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24266. EXPECT_GE(s.proxy_hits(), 1);
  24267. EXPECT_EQ(0, s.target_hits());
  24268. }
  24269. TEST(NoProxyTest, IPv4CidrMatch) {
  24270. ProxyAndTargetServers s;
  24271. Client cli("127.0.0.1", s.target_port());
  24272. cli.set_proxy("127.0.0.1", s.proxy_port());
  24273. cli.set_no_proxy({"127.0.0.0/8"});
  24274. auto res = cli.Get("/");
  24275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24276. EXPECT_EQ(0, s.proxy_hits());
  24277. EXPECT_EQ(1, s.target_hits());
  24278. }
  24279. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24280. ProxyAndTargetServers s;
  24281. Client cli("127.0.0.1", s.target_port());
  24282. cli.set_proxy("127.0.0.1", s.proxy_port());
  24283. cli.set_no_proxy({"10.0.0.0/8"});
  24284. auto res = cli.Get("/");
  24285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24286. EXPECT_GE(s.proxy_hits(), 1);
  24287. EXPECT_EQ(0, s.target_hits());
  24288. }
  24289. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24290. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24291. // IPv4 target matches.
  24292. ProxyAndTargetServers s;
  24293. Client cli("127.0.0.1", s.target_port());
  24294. cli.set_proxy("127.0.0.1", s.proxy_port());
  24295. cli.set_no_proxy({"0.0.0.0/0"});
  24296. auto res = cli.Get("/");
  24297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24298. EXPECT_EQ(0, s.proxy_hits());
  24299. EXPECT_EQ(1, s.target_hits());
  24300. }
  24301. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24302. ProxyAndTargetServers s;
  24303. Client cli("127.0.0.1", s.target_port());
  24304. cli.set_proxy("127.0.0.1", s.proxy_port());
  24305. cli.set_no_proxy({"127.0.0.1"});
  24306. auto res = cli.Get("/");
  24307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24308. EXPECT_EQ(0, s.proxy_hits());
  24309. EXPECT_EQ(1, s.target_hits());
  24310. }
  24311. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24312. ProxyAndTargetServers s;
  24313. Client cli("127.0.0.1", s.target_port());
  24314. cli.set_proxy("127.0.0.1", s.proxy_port());
  24315. cli.set_no_proxy({"127.0.0.0/33"});
  24316. auto res = cli.Get("/");
  24317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24318. EXPECT_GE(s.proxy_hits(), 1);
  24319. EXPECT_EQ(0, s.target_hits());
  24320. }
  24321. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24322. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24323. ProxyAndTargetServers s;
  24324. Client cli("127.0.0.1", s.target_port());
  24325. cli.set_proxy("127.0.0.1", s.proxy_port());
  24326. cli.set_no_proxy({"127.0.0.1/"});
  24327. auto res = cli.Get("/");
  24328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24329. EXPECT_GE(s.proxy_hits(), 1);
  24330. EXPECT_EQ(0, s.target_hits());
  24331. }
  24332. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24333. ProxyAndTargetServers s;
  24334. auto cli = make_client("internal.corp", s);
  24335. cli->set_proxy_basic_auth("u", "p");
  24336. cli->set_no_proxy({"internal.corp"});
  24337. auto res = cli->Get("/");
  24338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24339. EXPECT_EQ(1, s.target_hits());
  24340. EXPECT_EQ(0, s.proxy_hits());
  24341. EXPECT_FALSE(s.last_had_proxy_authz())
  24342. << "Proxy-Authorization must not be sent direct to the target";
  24343. }
  24344. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24345. ProxyAndTargetServers s;
  24346. auto cli = make_client("public.example", s);
  24347. cli->set_proxy_basic_auth("u", "p");
  24348. cli->set_no_proxy({"internal.corp"}); // does not match
  24349. auto res = cli->Get("/");
  24350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24351. EXPECT_GE(s.proxy_hits(), 1);
  24352. EXPECT_TRUE(s.last_had_proxy_authz());
  24353. }
  24354. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24355. std::atomic<int> hits{0};
  24356. std::atomic<int> hits_with_authz{0};
  24357. no_proxy_test::ScopedServer proxy_mock;
  24358. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24359. hits++;
  24360. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24361. if (req.target.find("/redir") != std::string::npos) {
  24362. res.set_redirect("http://other.example/landed");
  24363. } else {
  24364. res.set_content("via-proxy", "text/plain");
  24365. }
  24366. });
  24367. proxy_mock.listen();
  24368. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24369. hits = 0;
  24370. hits_with_authz = 0;
  24371. Client cli("public.example", 80);
  24372. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24373. cli.set_proxy_basic_auth(c.first, c.second);
  24374. cli.set_follow_location(true);
  24375. // The redirect to another host goes through the proxy as well
  24376. auto res = cli.Get("/redir");
  24377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24378. EXPECT_EQ(2, hits.load());
  24379. EXPECT_EQ(2, hits_with_authz.load());
  24380. }
  24381. }
  24382. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24383. ProxyAndTargetServers s;
  24384. auto cli = make_client("anything.test", s);
  24385. auto res = cli->Get("/");
  24386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24387. EXPECT_GE(s.proxy_hits(), 1);
  24388. EXPECT_EQ(0, s.target_hits());
  24389. }
  24390. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24391. ProxyAndTargetServers s;
  24392. auto cli = make_client("example.com", s);
  24393. cli->set_no_proxy({"example.com:8080"});
  24394. auto res = cli->Get("/");
  24395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24396. EXPECT_GE(s.proxy_hits(), 1);
  24397. EXPECT_EQ(0, s.target_hits());
  24398. }
  24399. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24400. ProxyAndTargetServers s;
  24401. auto cli = make_client("anything.test", s);
  24402. cli->set_no_proxy({"", " ", "\t"});
  24403. auto res = cli->Get("/");
  24404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24405. EXPECT_GE(s.proxy_hits(), 1);
  24406. EXPECT_EQ(0, s.target_hits());
  24407. }
  24408. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24409. // An entry with leading/trailing whitespace must still match — env-style
  24410. // values are commonly pasted with stray spaces and an implementation
  24411. // that feeds the raw token directly to inet_pton would fail to match
  24412. // valid CIDRs because of the spaces.
  24413. ProxyAndTargetServers s;
  24414. Client cli("127.0.0.1", s.target_port());
  24415. cli.set_proxy("127.0.0.1", s.proxy_port());
  24416. cli.set_no_proxy({" 127.0.0.0/8 "});
  24417. auto res = cli.Get("/");
  24418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24419. EXPECT_EQ(0, s.proxy_hits());
  24420. EXPECT_EQ(1, s.target_hits());
  24421. }
  24422. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24423. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24424. // go direct and must NOT carry Proxy-Authorization.
  24425. std::atomic<int> proxy_hits{0};
  24426. std::atomic<int> target_hits{0};
  24427. std::atomic<bool> target_saw_authz{false};
  24428. no_proxy_test::ScopedServer proxy_mock, target;
  24429. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24430. proxy_hits++;
  24431. res.status = 302;
  24432. res.set_header("Location", "http://127.0.0.1:" +
  24433. std::to_string(target.port()) + "/landed");
  24434. });
  24435. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24436. target_hits++;
  24437. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24438. res.set_content("direct", "text/plain");
  24439. });
  24440. proxy_mock.listen();
  24441. target.listen();
  24442. Client cli("public.example", target.port());
  24443. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24444. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24445. cli.set_proxy_basic_auth("u", "p");
  24446. cli.set_no_proxy({"127.0.0.1"});
  24447. cli.set_follow_location(true);
  24448. auto res = cli.Get("/redir");
  24449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24450. EXPECT_GE(proxy_hits.load(), 1);
  24451. EXPECT_GE(target_hits.load(), 1);
  24452. EXPECT_FALSE(target_saw_authz.load());
  24453. }
  24454. #ifdef CPPHTTPLIB_SSL_ENABLED
  24455. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24456. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24457. // proxy creds would be sent to the (possibly hostile) origin.
  24458. std::atomic<int> target_hits{0};
  24459. std::atomic<bool> target_saw_proxy_authz{false};
  24460. no_proxy_test::ScopedServer target;
  24461. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24462. target_hits++;
  24463. if (req.has_header("Proxy-Authorization")) {
  24464. target_saw_proxy_authz = true;
  24465. }
  24466. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24467. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24468. "nonce=\"abc\", algorithm=MD5");
  24469. });
  24470. target.listen();
  24471. // The proxy address is set to the target's port: the bypass MUST kick in;
  24472. // if it doesn't, the test still routes "via proxy" to the same server and
  24473. // the Proxy-Authorization assertion below catches the leak.
  24474. Client cli("evil.example", target.port());
  24475. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24476. cli.set_proxy("127.0.0.1", target.port());
  24477. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24478. cli.set_no_proxy({"evil.example"});
  24479. auto res = cli.Get("/x");
  24480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24481. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24482. EXPECT_EQ(1, target_hits.load());
  24483. EXPECT_FALSE(target_saw_proxy_authz.load());
  24484. }
  24485. #endif
  24486. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24487. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24488. std::atomic<int> proxy_hits{0};
  24489. std::atomic<int> bypass_hits{0};
  24490. std::atomic<bool> proxy_saw_c_url{false};
  24491. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24492. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24493. proxy_hits++;
  24494. if (req.path.find("/start") != std::string::npos) {
  24495. res.status = 302;
  24496. res.set_header("Location", "http://127.0.0.1:" +
  24497. std::to_string(bypass_server.port()) +
  24498. "/middle");
  24499. return;
  24500. }
  24501. if (req.path.find("/end") != std::string::npos) {
  24502. proxy_saw_c_url = true;
  24503. res.set_content("c-via-proxy", "text/plain");
  24504. return;
  24505. }
  24506. res.set_content("unexpected", "text/plain");
  24507. });
  24508. // public.example's "advertised" port is arbitrary (the request never lands
  24509. // there — it goes through the proxy), but use a dynamic value to stay
  24510. // friendly with sharded parallel runs.
  24511. int public_port = bypass_server.port();
  24512. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24513. bypass_hits++;
  24514. res.status = 302;
  24515. res.set_header("Location", "http://public.example:" +
  24516. std::to_string(public_port) + "/end");
  24517. });
  24518. proxy_mock.listen();
  24519. bypass_server.listen();
  24520. Client cli("public.example", public_port);
  24521. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24522. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24523. cli.set_no_proxy({"127.0.0.1"});
  24524. cli.set_follow_location(true);
  24525. auto res = cli.Get("/start");
  24526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24527. EXPECT_EQ(StatusCode::OK_200, res->status);
  24528. EXPECT_EQ("c-via-proxy", res->body);
  24529. EXPECT_GE(proxy_hits.load(), 2);
  24530. EXPECT_GE(bypass_hits.load(), 1);
  24531. EXPECT_TRUE(proxy_saw_c_url.load());
  24532. }
  24533. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24534. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24535. // request reconnects to the correct endpoint.
  24536. std::atomic<int> proxy_hits{0};
  24537. std::atomic<int> target_hits{0};
  24538. no_proxy_test::ScopedServer proxy_mock, target;
  24539. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24540. proxy_hits++;
  24541. res.set_content("via-proxy", "text/plain");
  24542. });
  24543. target.svr().Get(".*", [&](const Request &, Response &res) {
  24544. target_hits++;
  24545. res.set_content("direct", "text/plain");
  24546. });
  24547. proxy_mock.listen();
  24548. target.listen();
  24549. Client cli("public.example", target.port());
  24550. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24551. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24552. cli.set_keep_alive(true);
  24553. auto res1 = cli.Get("/a");
  24554. ASSERT_TRUE(res1);
  24555. EXPECT_EQ("via-proxy", res1->body);
  24556. EXPECT_EQ(1, proxy_hits.load());
  24557. EXPECT_EQ(0, target_hits.load());
  24558. cli.set_no_proxy({"public.example"});
  24559. auto res2 = cli.Get("/b");
  24560. ASSERT_TRUE(res2);
  24561. EXPECT_EQ("direct", res2->body);
  24562. EXPECT_EQ(1, proxy_hits.load());
  24563. EXPECT_EQ(1, target_hits.load());
  24564. }
  24565. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24566. namespace proxy_tunnel_test {
  24567. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24568. class ScopedSSLServer {
  24569. public:
  24570. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24571. port_ = svr_.bind_to_any_port("127.0.0.1");
  24572. }
  24573. ~ScopedSSLServer() {
  24574. svr_.stop();
  24575. if (th_.joinable()) { th_.join(); }
  24576. }
  24577. SSLServer &svr() { return svr_; }
  24578. int port() const { return port_; }
  24579. void listen() {
  24580. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24581. svr_.wait_until_ready();
  24582. }
  24583. private:
  24584. SSLServer svr_;
  24585. std::thread th_;
  24586. int port_ = 0;
  24587. };
  24588. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24589. class ScopedConnectProxy {
  24590. public:
  24591. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24592. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24593. if (listen_fd_ < 0) { return; }
  24594. int yes = 1;
  24595. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24596. sockaddr_in a{};
  24597. a.sin_family = AF_INET;
  24598. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24599. a.sin_port = 0;
  24600. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24601. return;
  24602. }
  24603. socklen_t alen = sizeof(a);
  24604. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24605. 0) {
  24606. return;
  24607. }
  24608. port_ = ntohs(a.sin_port);
  24609. if (::listen(listen_fd_, 1) != 0) { return; }
  24610. th_ = std::thread([this] { run(); });
  24611. }
  24612. ~ScopedConnectProxy() {
  24613. stop_ = true;
  24614. if (listen_fd_ >= 0) {
  24615. ::shutdown(listen_fd_, SHUT_RDWR);
  24616. ::close(listen_fd_);
  24617. }
  24618. if (th_.joinable()) { th_.join(); }
  24619. }
  24620. int port() const { return port_; }
  24621. int connect_hits() const { return connect_hits_.load(); }
  24622. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24623. std::string connect_request() const {
  24624. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24625. return connect_request_;
  24626. }
  24627. private:
  24628. void run() {
  24629. while (!stop_.load()) {
  24630. fd_set rfds;
  24631. FD_ZERO(&rfds);
  24632. FD_SET(listen_fd_, &rfds);
  24633. timeval tv{0, 100 * 1000};
  24634. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24635. if (sel <= 0) { continue; }
  24636. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24637. if (client_fd < 0) { continue; }
  24638. std::string req;
  24639. char buf[2048];
  24640. while (req.find("\r\n\r\n") == std::string::npos) {
  24641. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24642. if (n <= 0) { break; }
  24643. req.append(buf, static_cast<size_t>(n));
  24644. }
  24645. if (req.compare(0, 7, "CONNECT") != 0) {
  24646. ::close(client_fd);
  24647. continue;
  24648. }
  24649. connect_hits_++;
  24650. {
  24651. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24652. connect_request_ = req;
  24653. }
  24654. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24655. ::send(client_fd, ok, std::strlen(ok), 0);
  24656. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24657. sockaddr_in o{};
  24658. o.sin_family = AF_INET;
  24659. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24660. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24661. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24662. 0) {
  24663. ::close(client_fd);
  24664. ::close(origin_fd);
  24665. continue;
  24666. }
  24667. auto forward = [](int from, int to) {
  24668. char b[8192];
  24669. for (;;) {
  24670. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24671. if (n <= 0) { break; }
  24672. ssize_t off = 0;
  24673. while (off < n) {
  24674. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24675. if (s <= 0) {
  24676. off = n;
  24677. break;
  24678. }
  24679. off += s;
  24680. }
  24681. }
  24682. ::shutdown(to, SHUT_WR);
  24683. };
  24684. std::thread t1([&] { forward(client_fd, origin_fd); });
  24685. std::thread t2([&] { forward(origin_fd, client_fd); });
  24686. t1.join();
  24687. t2.join();
  24688. ::close(client_fd);
  24689. ::close(origin_fd);
  24690. }
  24691. }
  24692. int forward_port_ = -1;
  24693. int listen_fd_ = -1;
  24694. int port_ = 0;
  24695. std::thread th_;
  24696. std::atomic<bool> stop_{false};
  24697. std::atomic<int> connect_hits_{0};
  24698. mutable std::mutex connect_request_mutex_;
  24699. std::string connect_request_;
  24700. };
  24701. // Sends one request through the CONNECT proxy to the TLS origin with a
  24702. // credential configured for each hop, and checks that each credential reaches
  24703. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24704. // origin's (every header in origin_headers) on the tunnelled request.
  24705. void CredentialsStayWithTheirHop(
  24706. const std::function<void(SSLClient &)> &set_credentials,
  24707. const std::string &scheme,
  24708. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24709. std::atomic<int> origin_hits{0};
  24710. std::atomic<bool> origin_saw_proxy_authz{false};
  24711. std::atomic<bool> origin_saw_headers{false};
  24712. ScopedSSLServer origin;
  24713. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24714. origin_hits++;
  24715. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24716. origin_saw_headers =
  24717. std::all_of(origin_headers.begin(), origin_headers.end(),
  24718. [&](const std::string &h) { return req.has_header(h); });
  24719. res.set_content("ok", "text/plain");
  24720. });
  24721. origin.listen();
  24722. ScopedConnectProxy proxy(origin.port());
  24723. ASSERT_NE(0, proxy.port());
  24724. // Pinned to 127.0.0.1 for the same reason as the test below.
  24725. SSLClient cli("127.0.0.1", origin.port());
  24726. cli.enable_server_certificate_verification(false);
  24727. cli.set_proxy("127.0.0.1", proxy.port());
  24728. set_credentials(cli);
  24729. auto res = cli.Get("/x");
  24730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24731. EXPECT_EQ(StatusCode::OK_200, res->status);
  24732. EXPECT_EQ(1, origin_hits.load());
  24733. EXPECT_EQ(1, proxy.connect_hits());
  24734. EXPECT_TRUE(origin_saw_headers.load());
  24735. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24736. << "Proxy-Authorization must not be sent inside the tunnel";
  24737. auto connect_req = proxy.connect_request();
  24738. EXPECT_NE(std::string::npos,
  24739. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24740. for (const auto &h : origin_headers) {
  24741. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24742. << h << " must not be sent to the proxy on CONNECT";
  24743. }
  24744. }
  24745. } // namespace proxy_tunnel_test
  24746. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24747. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24748. [](SSLClient &cli) {
  24749. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24750. cli.set_basic_auth("origin-user", "origin-pass");
  24751. },
  24752. "Basic");
  24753. }
  24754. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24755. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24756. [](SSLClient &cli) {
  24757. cli.set_proxy_bearer_token_auth("proxy-token");
  24758. cli.set_bearer_token_auth("origin-token");
  24759. },
  24760. "Bearer");
  24761. }
  24762. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24763. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24764. [](SSLClient &cli) {
  24765. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24766. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24767. {"Cookie", "sid=origin-session"},
  24768. {"X-Api-Key", "origin-key"}});
  24769. },
  24770. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24771. }
  24772. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24773. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24774. // retry; otherwise proxy creds would be sent to the origin.
  24775. std::atomic<int> origin_hits{0};
  24776. std::atomic<bool> origin_saw_proxy_authz{false};
  24777. proxy_tunnel_test::ScopedSSLServer origin;
  24778. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24779. origin_hits++;
  24780. if (req.has_header("Proxy-Authorization")) {
  24781. origin_saw_proxy_authz = true;
  24782. }
  24783. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24784. res.set_header("Proxy-Authenticate",
  24785. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24786. "algorithm=MD5");
  24787. });
  24788. origin.listen();
  24789. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24790. ASSERT_NE(0, proxy.port());
  24791. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24792. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24793. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24794. // and answer with its own status, making this test flaky.
  24795. SSLClient cli("127.0.0.1", origin.port());
  24796. cli.enable_server_certificate_verification(false);
  24797. cli.set_proxy("127.0.0.1", proxy.port());
  24798. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24799. auto res = cli.Get("/x");
  24800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24801. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24802. EXPECT_EQ(1, origin_hits.load());
  24803. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24804. EXPECT_EQ(1, proxy.connect_hits());
  24805. }
  24806. #endif